@php
    $customerOptions = $customers->mapWithKeys(fn ($customer) => [$customer->id => $customer->name.' - '.($customer->email ?: $customer->phone ?: 'No contact')])->all();
    $serviceOptions = $services->mapWithKeys(fn ($service) => [$service->id => $service->name.' ('.($currentBusiness?->currency ?? 'USD').' '.number_format((float) $service->price, 2).')'])->all();
    $appointmentOptions = $appointments->mapWithKeys(fn ($appointment) => [
        $appointment->id => trim(($appointment->booking_number ?: 'Appointment').' - '.($appointment->customer?->name ?? 'Customer').' - '.($appointment->service?->name ?? 'Service')),
    ])->all();

    $oldItems = old('items');

    if (is_array($oldItems) && count($oldItems) > 0) {
        $formItems = collect($oldItems);
    } elseif ($invoice->exists && $invoice->items->isNotEmpty()) {
        $formItems = $invoice->items->map(fn ($item) => [
            'service_id' => $item->service_id,
            'description' => $item->description,
            'quantity' => $item->quantity,
            'unit_price' => $item->unit_price,
            'tax_rate' => $item->tax_rate,
        ]);
    } else {
        $firstService = $services->first();
        $formItems = collect([
            [
                'service_id' => $firstService?->id,
                'description' => $firstService?->name ?? 'Service appointment',
                'quantity' => 1,
                'unit_price' => $firstService?->price ?? 0,
                'tax_rate' => 0,
            ],
        ]);
    }

    while ($formItems->count() < 4) {
        $formItems->push(['service_id' => null, 'description' => null, 'quantity' => null, 'unit_price' => null, 'tax_rate' => 0]);
    }

    $statusValue = old('status', $invoice->status_value ?: 'draft');
@endphp

<form method="POST" action="{{ $formAction }}" class="space-y-5">
    @csrf
    @if ($formMethod !== 'POST')
        @method($formMethod)
    @endif

    @if ($errors->any())
        <div class="rounded-lg border border-red-200 bg-red-50 p-4">
            <p class="text-sm font-extrabold text-booklio-danger">Please fix the highlighted invoice fields.</p>
            <ul class="mt-2 list-inside list-disc space-y-1 text-xs font-semibold text-red-700">
                @foreach ($errors->all() as $message)
                    <li>{{ $message }}</li>
                @endforeach
            </ul>
        </div>
    @endif

    <x-ui.card title="Invoice Details">
        <div class="grid gap-4 sm:grid-cols-2">
            <x-form.input name="invoice_number" label="Invoice Number" :value="$invoice->invoice_number" placeholder="Auto-generated if empty" />
            <x-form.select name="status" label="Status" :value="$statusValue" :options="$statusOptions" />
            <x-form.select name="customer_id" label="Customer" :value="$invoice->customer_id" placeholder="Choose customer" :options="$customerOptions" />
            <x-form.select name="appointment_id" label="Appointment" :value="$invoice->appointment_id" placeholder="No linked appointment" :options="$appointmentOptions" />
            <x-form.input name="issue_date" label="Issue Date" type="date" :value="$invoice->issue_date?->format('Y-m-d') ?? now()->toDateString()" />
            <x-form.input name="due_date" label="Due Date" type="date" :value="$invoice->due_date?->format('Y-m-d')" />
            <x-form.input name="currency" label="Currency" :value="$invoice->currency ?: ($currentBusiness?->currency ?? 'USD')" maxlength="3" />
            <x-form.input name="discount_total" label="Discount" type="number" step="0.01" min="0" :value="$invoice->discount_total ?: 0" />
        </div>
    </x-ui.card>

    <x-ui.card title="Line Items" padding="p-0">
        <div class="overflow-x-auto booklio-scrollbar">
            <table class="min-w-[900px] w-full divide-y divide-booklio-border">
                <thead class="bg-slate-50">
                    <tr>
                        @foreach (['Service', 'Description', 'Qty', 'Price', 'Tax %', 'Line Total'] as $heading)
                            <th class="px-5 py-4 text-left text-xs font-bold uppercase tracking-wide text-booklio-muted">{{ $heading }}</th>
                        @endforeach
                    </tr>
                </thead>
                <tbody class="divide-y divide-booklio-border bg-white">
                    @foreach ($formItems as $index => $item)
                        @php
                            $quantity = old("items.$index.quantity", $item['quantity'] ?? null);
                            $unitPrice = old("items.$index.unit_price", $item['unit_price'] ?? null);
                            $lineTotal = (float) $quantity * (float) $unitPrice;
                        @endphp
                        <tr>
                            <td class="px-5 py-4">
                                <select name="items[{{ $index }}][service_id]" class="h-10 w-full rounded-lg border border-booklio-border bg-white px-3 text-sm font-semibold text-slate-700 outline-none focus:border-booklio-primary focus:ring-4 focus:ring-blue-100">
                                    <option value="">Custom item</option>
                                    @foreach ($serviceOptions as $value => $label)
                                        <option value="{{ $value }}" @selected((string) old("items.$index.service_id", $item['service_id'] ?? '') === (string) $value)>{{ $label }}</option>
                                    @endforeach
                                </select>
                            </td>
                            <td class="px-5 py-4">
                                <input name="items[{{ $index }}][description]" value="{{ old("items.$index.description", $item['description'] ?? '') }}" class="h-10 w-full rounded-lg border border-booklio-border px-3 text-sm font-semibold outline-none focus:border-booklio-primary focus:ring-4 focus:ring-blue-100" placeholder="Service or item description">
                            </td>
                            <td class="px-5 py-4">
                                <input name="items[{{ $index }}][quantity]" type="number" step="0.01" min="0" value="{{ $quantity }}" class="h-10 w-24 rounded-lg border border-booklio-border px-3 text-sm font-semibold outline-none focus:border-booklio-primary focus:ring-4 focus:ring-blue-100">
                            </td>
                            <td class="px-5 py-4">
                                <input name="items[{{ $index }}][unit_price]" type="number" step="0.01" min="0" value="{{ $unitPrice }}" class="h-10 w-28 rounded-lg border border-booklio-border px-3 text-sm font-semibold outline-none focus:border-booklio-primary focus:ring-4 focus:ring-blue-100">
                            </td>
                            <td class="px-5 py-4">
                                <input name="items[{{ $index }}][tax_rate]" type="number" step="0.01" min="0" max="100" value="{{ old("items.$index.tax_rate", $item['tax_rate'] ?? 0) }}" class="h-10 w-24 rounded-lg border border-booklio-border px-3 text-sm font-semibold outline-none focus:border-booklio-primary focus:ring-4 focus:ring-blue-100">
                            </td>
                            <td class="px-5 py-4 text-sm font-extrabold">{{ ($invoice->currency ?: ($currentBusiness?->currency ?? 'USD')).' '.number_format($lineTotal, 2) }}</td>
                        </tr>
                    @endforeach
                </tbody>
            </table>
        </div>
        <div class="border-t border-booklio-border p-5">
            <p class="text-xs font-semibold text-booklio-muted">Blank rows are ignored. Dynamic add/remove controls can be wired later when the invoice editor JavaScript is expanded.</p>
        </div>
    </x-ui.card>

    <x-ui.card title="Notes">
        <div class="grid gap-4 sm:grid-cols-2">
            <x-form.textarea name="notes" label="Invoice Notes" :value="$invoice->notes" placeholder="Internal or customer-facing invoice note..." rows="4" />
            <x-form.textarea name="footer_note" label="Footer Note" :value="$invoice->footer_note" placeholder="Thank you for choosing us." rows="4" />
        </div>
    </x-ui.card>

    <div class="flex flex-col gap-3 sm:flex-row sm:justify-end">
        <x-ui.button variant="secondary" href="{{ route('admin.invoices.index') }}">Cancel</x-ui.button>
        <x-ui.button type="submit">{{ $submitLabel }}</x-ui.button>
    </div>
</form>
