<x-app-layout>
    <x-slot name="header">
        <div class="flex items-center justify-between w-full">
            <div>
                <h1 class="text-lg font-semibold text-gray-800">Edit Note Draft</h1>
                <p class="text-xs text-gray-400 mt-0.5">Edit an existing draft Credit / Debit Note</p>
            </div>
            <a href="{{ route('notes.index') }}" class="text-sm text-gray-500 hover:text-gray-700 font-medium">
                Back to Notes
            </a>
        </div>
    </x-slot>

    <div x-data="noteForm()" class="max-w-7xl mx-auto space-y-6">
        @if ($errors->any())
            <div class="p-4 bg-rose-50 border border-rose-200 text-rose-800 rounded-xl text-sm space-y-1">
                <strong>Please resolve the following errors:</strong>
                <ul class="list-disc list-inside">
                    @foreach ($errors->all() as $error)
                        <li>{{ $error }}</li>
                    @endforeach
                </ul>
            </div>
        @endif

        <form action="{{ route('notes.update', $note->id) }}" method="POST" class="grid grid-cols-1 lg:grid-cols-3 gap-6">
            @csrf
            @method('PUT')

            <!-- Left Panel: Note details & items -->
            <div class="lg:col-span-2 space-y-6">
                <!-- 1. Header and Selector -->
                <div class="bg-white rounded-xl border border-gray-100 shadow-sm p-6 space-y-4">
                    <h2 class="text-sm font-semibold text-gray-700 border-b border-gray-50 pb-2">1. Original Invoice Reference</h2>
                    
                    <div class="grid grid-cols-1 sm:grid-cols-3 gap-4">
                        <!-- Select Linked Invoice -->
                        <div>
                            <label class="block text-xs font-medium text-gray-500 mb-1">Select Synced Invoice *</label>
                            <select x-model="selectedInvoiceId" @change="selectInvoice()" name="original_invoice_id" required
                                class="w-full rounded-lg border-gray-200 text-sm focus:border-indigo-400 focus:ring-indigo-400">
                                <option value="">Select Invoice...</option>
                                @foreach($invoices as $inv)
                                    <option value="{{ $inv->id }}" data-invoice="{{ json_encode($inv) }}">
                                        {{ $inv->local_invoice_no }} ({{ $inv->fbr_invoice_number }})
                                    </option>
                                @endforeach
                            </select>
                        </div>

                        <!-- Note Type -->
                        <div>
                            <label class="block text-xs font-medium text-gray-500 mb-1">Note Type *</label>
                            <select x-model="form.note_type" name="note_type" required
                                class="w-full rounded-lg border-gray-200 text-sm focus:border-indigo-400 focus:ring-indigo-400">
                                <option value="credit">Credit Note</option>
                                <option value="debit">Debit Note</option>
                            </select>
                        </div>

                        <!-- Note Date -->
                        <div>
                            <label class="block text-xs font-medium text-gray-500 mb-1">Note Date *</label>
                            <input type="date" x-model="form.invoice_date" name="invoice_date" required
                                class="w-full rounded-lg border-gray-200 text-sm focus:border-indigo-400 focus:ring-indigo-400">
                        </div>
                    </div>

                    <!-- FBR Rules Live Indicators -->
                    <div x-show="originalInvoice" class="p-4 rounded-lg bg-gray-50 border border-gray-100 text-xs space-y-2">
                        <div class="grid grid-cols-2 gap-4">
                            <div>
                                <span class="text-gray-400 block uppercase">Original Date</span>
                                <span class="font-semibold text-gray-700" x-text="originalInvoice?.invoice_date"></span>
                            </div>
                            <div>
                                <span class="text-gray-400 block uppercase">Original Net Amount</span>
                                <span class="font-semibold text-gray-700" x-text="'Rs. ' + Number(originalInvoice?.total_amount).toFixed(2)"></span>
                            </div>
                        </div>

                        <div class="border-t border-gray-200/50 pt-2 flex flex-col gap-1.5">
                            <!-- 180 Days Limit Indicator -->
                            <div class="flex items-center gap-2">
                                <span class="w-2 h-2 rounded-full" :class="isDateWithin180Days ? 'bg-emerald-500' : 'bg-rose-500'"></span>
                                <span x-text="isDateWithin180Days ? 'Date is within valid 180-day window' : 'Note Date exceeds 180 days from original invoice!'"></span>
                            </div>
                            <!-- Date sequence indicator -->
                            <div class="flex items-center gap-2">
                                <span class="w-2 h-2 rounded-full" :class="isDateValidSequence ? 'bg-emerald-500' : 'bg-rose-500'"></span>
                                <span x-text="isDateValidSequence ? 'Date sequence is correct (>= original date)' : 'Note date cannot be earlier than original invoice date!'"></span>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 2. Reason of Issue -->
                <div class="bg-white rounded-xl border border-gray-100 shadow-sm p-6 space-y-4">
                    <h2 class="text-sm font-semibold text-gray-700 border-b border-gray-50 pb-2">2. Correction Details</h2>
                    
                    <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                        <div>
                            <label class="block text-xs font-medium text-gray-500 mb-1">Reason Code *</label>
                            <select x-model="form.reason" name="reason" required
                                class="w-full rounded-lg border-gray-200 text-sm focus:border-indigo-400 focus:ring-indigo-400">
                                <option value="">Select Reason...</option>
                                <option value="Return of Goods">Return of Goods</option>
                                <option value="Rate Difference">Rate Difference</option>
                                <option value="Calculation Error">Calculation / Quantity Error</option>
                                <option value="Others">Others</option>
                            </select>
                        </div>

                        <div x-show="form.reason === 'Others'">
                            <label class="block text-xs font-medium text-gray-500 mb-1">Specify Remarks *</label>
                            <input type="text" x-model="form.remarks" name="remarks" :required="form.reason === 'Others'"
                                class="w-full rounded-lg border-gray-200 text-sm focus:border-indigo-400 focus:ring-indigo-400"
                                placeholder="State specific reason...">
                        </div>
                    </div>
                </div>

                <!-- 3. Line Items -->
                <div class="bg-white rounded-xl border border-gray-100 shadow-sm p-6 space-y-4">
                    <h2 class="text-sm font-semibold text-gray-700 border-b border-gray-50 pb-2">3. Line Items</h2>
                    
                    <div class="overflow-x-auto">
                        <table class="w-full text-left border-collapse text-xs">
                            <thead>
                                <tr class="border-b border-gray-100 text-gray-400 uppercase tracking-wider">
                                    <th class="py-2.5 pr-4 w-1/3">Product details</th>
                                    <th class="py-2.5 px-2 w-16 text-center">Qty</th>
                                    <th class="py-2.5 px-2 w-28 text-right">Price (Excl)</th>
                                    <th class="py-2.5 px-2 w-28 text-right">Sales Tax</th>
                                    <th class="py-2.5 px-2 w-28 text-right">Total</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-gray-100">
                                <template x-for="(row, idx) in form.items" :key="idx">
                                    <tr class="align-middle">
                                        <td class="py-4 pr-4">
                                            <div class="font-semibold text-gray-800" x-text="row.product_description"></div>
                                            <div class="text-[10px] text-gray-400 font-mono mt-0.5" x-text="`HS: ${row.hs_code || 'N/A'}`"></div>
                                            <input type="hidden" :name="`items[${idx}][item_id]`" :value="row.item_id">
                                            <input type="hidden" :name="`items[${idx}][hs_code]`" :value="row.hs_code">
                                            <input type="hidden" :name="`items[${idx}][product_description]`" :value="row.product_description">
                                            <input type="hidden" :name="`items[${idx}][uom]`" :value="row.uom">
                                            <input type="hidden" :name="`items[${idx}][rate]`" :value="row.rate">
                                        </td>
                                        <td class="py-4 px-2">
                                            <input type="number" step="0.0001" x-model.number="row.quantity" :name="`items[${idx}][quantity]`"
                                                @input="recalculateRow(idx)" required
                                                class="w-full text-center rounded-lg border-gray-200 text-xs focus:border-indigo-400 focus:ring-indigo-400 py-1.5 px-2">
                                        </td>
                                        <td class="py-4 px-2">
                                            <input type="number" step="0.01" x-model.number="row.value_sales_excluding_st" :name="`items[${idx}][value_sales_excluding_st]`"
                                                @input="recalculateRow(idx)" required
                                                class="w-full rounded-lg border-gray-200 text-xs focus:border-indigo-400 focus:ring-indigo-400 py-1.5 px-2 text-right">
                                        </td>
                                        <td class="py-4 px-2">
                                            <input type="number" step="0.01" x-model.number="row.sales_tax_applicable" :name="`items[${idx}][sales_tax_applicable]`"
                                                @input="recalculateRow(idx)" required
                                                class="w-full rounded-lg border-gray-200 text-xs focus:border-indigo-400 focus:ring-indigo-400 py-1.5 px-2 text-right">
                                        </td>
                                        <td class="py-4 px-2 text-right font-semibold text-gray-800"
                                            x-text="Number(row.value_sales_excluding_st + row.sales_tax_applicable).toFixed(2)">
                                        </td>
                                    </tr>
                                </template>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <!-- Right Panel: Summary & Submission -->
            <div class="space-y-6">
                <div class="bg-white rounded-xl border border-gray-100 shadow-sm p-6 space-y-4 sticky top-6">
                    <h2 class="text-sm font-semibold text-gray-700 border-b border-gray-50 pb-2">Summary</h2>
                    
                    <div class="space-y-2 text-xs">
                        <div class="flex justify-between">
                            <span class="text-gray-400">Subtotal (Excl. Tax)</span>
                            <span class="font-semibold text-gray-700" x-text="'Rs. ' + subtotal.toFixed(2)"></span>
                        </div>
                        <div class="flex justify-between">
                            <span class="text-gray-400">Sales Tax</span>
                            <span class="font-semibold text-gray-700" x-text="'Rs. ' + salesTax.toFixed(2)"></span>
                        </div>
                        <div class="border-t border-gray-100 pt-2 flex justify-between text-sm font-bold">
                            <span class="text-gray-800">Total Net Amount</span>
                            <span class="text-indigo-600" x-text="'Rs. ' + totalAmount.toFixed(2)"></span>
                        </div>
                    </div>

                    <!-- FBR constraint checks -->
                    <div class="space-y-2 pt-2 border-t border-gray-100 text-xs">
                        <!-- Value bounds checks -->
                        <div x-show="form.note_type === 'credit'" class="flex items-center gap-2">
                            <span class="w-2 h-2 rounded-full" :class="isCreditSubtotalValid ? 'bg-emerald-500' : 'bg-rose-500'"></span>
                            <span x-text="isCreditSubtotalValid ? 'Credited amount is within original values' : 'Credit amount exceeds original invoice subtotal!'"></span>
                        </div>
                        <div x-show="form.note_type === 'debit'" class="flex items-center gap-2">
                            <span class="w-2 h-2 rounded-full" :class="isDebitTaxValid ? 'bg-emerald-500' : 'bg-rose-500'"></span>
                            <span x-text="isDebitTaxValid ? 'Sales tax value is within original limits' : 'Debit tax exceeds original invoice sales tax!'"></span>
                        </div>
                    </div>

                    <div class="flex flex-col gap-2 pt-2">
                        <label class="inline-flex items-center gap-2 text-xs font-semibold text-gray-700">
                            <input type="checkbox" name="sync_immediately" value="1"
                                class="rounded border-gray-300 text-indigo-600 focus:ring-indigo-500">
                            Sync immediately to FBR
                        </label>
                        <button type="submit" :disabled="!isFormSubmittable"
                            class="w-full text-center py-2.5 rounded-lg bg-indigo-600 hover:bg-indigo-700 text-white text-xs font-semibold transition disabled:opacity-50 disabled:cursor-not-allowed">
                            Update Note Draft
                        </button>
                    </div>
                </div>
            </div>
        </form>
    </div>

    <script>
        function noteForm() {
            return {
                selectedInvoiceId: '{{ $note->original_invoice_id }}',
                originalInvoice: null,
                form: {
                    note_type: '{{ $note->invoice_type === \App\Enums\FbrInvoiceType::CreditNote ? "credit" : "debit" }}',
                    invoice_date: '{{ $note->invoice_date->format("Y-m-d") }}',
                    reason: '{{ $note->reason }}',
                    remarks: '{{ $note->remarks }}',
                    notes: '{{ $note->notes }}',
                    items: {!! json_encode($note->items->map(function($i) {
                        return [
                            'item_id' => $i->item_id,
                            'hs_code' => $i->hs_code,
                            'product_description' => $i->product_description,
                            'uom' => $i->uom,
                            'rate' => $i->rate,
                            'quantity' => (float)$i->quantity,
                            'value_sales_excluding_st' => (float)$i->value_sales_excluding_st,
                            'sales_tax_applicable' => (float)$i->sales_tax_applicable,
                            'sales_tax_withheld_at_source' => (float)$i->sales_tax_withheld_at_source,
                        ];
                    })) !!}
                },
                init() {
                    this.selectInvoice();
                },
                selectInvoice() {
                    const select = document.querySelector('select[name="original_invoice_id"]');
                    const selectedOption = select.options[select.selectedIndex];
                    if (selectedOption && selectedOption.dataset.invoice) {
                        this.originalInvoice = JSON.parse(selectedOption.dataset.invoice);
                    } else {
                        this.originalInvoice = null;
                    }
                },
                recalculateRow(idx) {
                    const row = this.form.items[idx];
                    row.value_sales_excluding_st = row.quantity * row.rate;
                    row.sales_tax_applicable = Math.round(row.value_sales_excluding_st * (18 / 100) * 100) / 100;
                },
                get subtotal() {
                    return this.form.items.reduce((acc, i) => acc + i.value_sales_excluding_st, 0);
                },
                get salesTax() {
                    return this.form.items.reduce((acc, i) => acc + i.sales_tax_applicable, 0);
                },
                get totalAmount() {
                    return this.subtotal + this.salesTax;
                },
                // FBR Constraint Computations
                get isDateWithin180Days() {
                    if (!this.originalInvoice) return true;
                    const diffTime = Math.abs(new Date(this.form.invoice_date) - new Date(this.originalInvoice.invoice_date));
                    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
                    return diffDays <= 180;
                },
                get isDateValidSequence() {
                    if (!this.originalInvoice) return true;
                    return new Date(this.form.invoice_date) >= new Date(this.originalInvoice.invoice_date);
                },
                get isCreditSubtotalValid() {
                    if (!this.originalInvoice || this.form.note_type !== 'credit') return true;
                    return this.subtotal <= Number(this.originalInvoice.subtotal);
                },
                get isDebitTaxValid() {
                    if (!this.originalInvoice || this.form.note_type !== 'debit') return true;
                    return this.salesTax <= Number(this.originalInvoice.total_tax);
                },
                get isFormSubmittable() {
                    return this.originalInvoice &&
                        this.isDateWithin180Days &&
                        this.isDateValidSequence &&
                        this.isCreditSubtotalValid &&
                        this.isDebitTaxValid &&
                        this.form.reason !== '';
                }
            }
        }
    </script>
</x-app-layout>
