<x-app-layout>
    <x-slot name="header">
        <div class="flex items-center justify-between">
            <h2 class="font-semibold text-xl text-gray-800 leading-tight">
                Edit Invoice: <span class="text-indigo-600">{{ $invoice->invoice_number }}</span>
            </h2>
            <span class="text-sm text-slate-500 italic">Linked to Case #{{ $case->case_number }}</span>
        </div>
    </x-slot>

    <div class="py-12">
        <div class="max-w-4xl mx-auto sm:px-6 lg:px-8">
            <div class="bg-white shadow-sm sm:rounded-xl p-8 ring-1 ring-slate-900/5">

                <form action="{{ route('admin.invoices.update', $invoice->id) }}" method="POST">
                    @csrf
                    @method('PUT')

                    <div class="grid grid-cols-1 md:grid-cols-2 gap-8 mb-8 border-b border-gray-100 pb-6">
                        <div>
                            <label class="block text-sm font-bold text-slate-700 mb-2 uppercase tracking-wide">Due Date</label>
                            <input type="date" name="due_date" value="{{ $invoice->due_date->format('Y-m-d') }}"
                                   class="w-full border-gray-300 rounded-lg shadow-sm focus:border-indigo-500 focus:ring-indigo-500" required>
                        </div>

                        <div>
                            <label class="block text-sm font-bold text-slate-700 mb-2 uppercase tracking-wide">Payment Status</label>
                            <select name="status" class="w-full border-gray-300 rounded-lg shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                                <option value="unpaid" {{ $invoice->status == 'unpaid' ? 'selected' : '' }}>🔴 Unpaid</option>
                                <option value="paid" {{ $invoice->status == 'paid' ? 'selected' : '' }}>🟢 Paid</option>
                                <option value="overdue" {{ $invoice->status == 'overdue' ? 'selected' : '' }}>⚠️ Overdue</option>
                            </select>
                        </div>
                    </div>

                    <div x-data="invoiceEditor()">

                        <div class="flex justify-between items-center mb-6">
                            <h3 class="text-lg font-bold text-slate-800">Billable Items</h3>
                            <button type="button" @click="addNewItem()"
                                    class="inline-flex items-center gap-2 px-3 py-1.5 bg-indigo-50 text-indigo-700 rounded-lg text-xs font-bold hover:bg-indigo-100 transition">
                                <i class="ph-bold ph-plus"></i> Add Line Item
                            </button>
                        </div>

                        <div class="space-y-3 mb-8">
                            <div class="flex gap-4 text-xs font-bold text-slate-400 uppercase tracking-widest px-1">
                                <div class="flex-1">Description</div>
                                <div class="w-48">Amount (KES)</div>
                                <div class="w-10"></div>
                            </div>

                            <template x-for="(item, index) in items" :key="item.id">
                                <div class="flex gap-4 items-center group">
                                    <div class="flex-1">
                                        <input type="text" name="descriptions[]" x-model="item.description"
                                               placeholder="Description"
                                               class="w-full border-gray-300 rounded-lg shadow-sm focus:border-indigo-500 focus:ring-indigo-500 text-sm" required>
                                    </div>

                                    <div class="w-48">
                                        <input type="number" name="amounts[]" x-model="item.amount"
                                               placeholder="0.00"
                                               class="w-full border-gray-300 rounded-lg shadow-sm focus:border-indigo-500 focus:ring-indigo-500 text-right text-sm" required>
                                    </div>

                                    <div class="w-10 flex justify-center">
                                        <button type="button" @click="removeItem(index)"
                                                class="text-slate-300 hover:text-red-600 transition p-1">
                                            <i class="ph-bold ph-trash text-lg"></i>
                                        </button>
                                    </div>
                                </div>
                            </template>
                        </div>

                        <div class="flex justify-end mb-8">
                            <div class="bg-slate-50 rounded-xl px-6 py-4 border border-slate-100 min-w-[200px]">
                                <p class="text-xs font-bold text-slate-400 uppercase">Total Amount</p>
                                <p class="text-2xl font-black text-slate-900 mt-1">
                                    KES <span x-text="calculateTotal()"></span>
                                </p>
                            </div>
                        </div>

                        <div class="flex justify-between items-center border-t border-gray-100 pt-8">
                            <a href="{{ route('admin.cases.show', $case->id) }}" class="text-sm font-bold text-slate-500 hover:text-slate-700 transition">
                                Cancel Changes
                            </a>
                            <button type="submit" class="bg-indigo-600 text-white px-8 py-3 rounded-xl font-bold hover:bg-indigo-700 shadow-lg shadow-indigo-200 transition transform active:scale-95 flex items-center gap-2">
                                <i class="ph-bold ph-floppy-disk"></i> Update Invoice
                            </button>
                        </div>

                    </div>
                </form>

            </div>
        </div>
    </div>

    <script>
        function invoiceEditor() {
            return {
                // Initialize items with existing data from the database
                items: @json($invoice->items->map(fn($item) => [
                    'id' => $item->id,
                    'description' => $item->description,
                    'amount' => $item->amount
                ])),

                addNewItem() {
                    this.items.push({
                        id: 'new-' + Date.now(),
                        description: '',
                        amount: 0
                    });
                },

                removeItem(index) {
                    if (this.items.length > 1) {
                        this.items.splice(index, 1);
                    } else {
                        alert("An invoice must have at least one line item.");
                    }
                },

                calculateTotal() {
                    const total = this.items.reduce((sum, item) => sum + (parseFloat(item.amount) || 0), 0);
                    return new Intl.NumberFormat().format(total);
                }
            }
        }
    </script>
</x-app-layout>
