<x-app-layout>
    <x-slot name="header">
        <h2 class="font-bold text-2xl text-slate-800 flex items-center gap-2">
            <i class="ph-duotone ph-book-open text-indigo-600"></i>
            {{ __('Financial Ledger') }}
        </h2>
    </x-slot>

    <div class="py-10 bg-slate-50 min-h-screen"
         x-data="{
            tab: 'invoices',
            editModal: false,
            historyModal: false,
            activeInvoice: null,
            payments: [],
            editType: '',
            editData: {}
         }">

        <div class="max-w-7xl mx-auto sm:px-6 lg:px-8 space-y-6">

            <div class="flex items-center gap-4 bg-white p-1 rounded-xl shadow-sm ring-1 ring-slate-900/5 w-fit">
                <button @click="tab = 'invoices'" :class="tab === 'invoices' ? 'bg-indigo-600 text-white shadow-md' : 'text-slate-500 hover:bg-slate-50'" class="px-6 py-2 rounded-lg text-sm font-bold transition-all flex items-center gap-2">
                    <i class="ph-bold ph-invoice"></i> Invoices
                </button>
                <button @click="tab = 'expenses'" :class="tab === 'expenses' ? 'bg-rose-600 text-white shadow-md' : 'text-slate-500 hover:bg-slate-50'" class="px-6 py-2 rounded-lg text-sm font-bold transition-all flex items-center gap-2">
                    <i class="ph-bold ph-receipt"></i> Expenses
                </button>
            </div>

            <div x-show="tab === 'invoices'" class="bg-white rounded-2xl shadow-sm ring-1 ring-slate-900/5 overflow-hidden">
                <table class="min-w-full text-left text-sm">
                    <thead class="bg-slate-50 border-b border-slate-100 text-slate-500 uppercase text-[10px] font-black tracking-widest">
                        <tr>
                            <th class="px-6 py-4">Invoice #</th>
                            <th class="px-6 py-4">Client</th>
                            <th class="px-6 py-4">Total Bill</th>
                            <th class="px-6 py-4">Paid So Far</th>
                            <th class="px-6 py-4">Balance</th>
                            <th class="px-6 py-4 text-right">History</th>
                            <th class="px-6 py-4 text-right">Actions</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-100">
                        @foreach($invoices as $inv)
                        @php
                            $paid = $inv->payments->sum('amount');
                            $balance = $inv->total_amount - $paid;
                        @endphp
                        <tr class="hover:bg-slate-50 transition group">
                            <td class="px-6 py-4 font-bold text-slate-700">#{{ $inv->invoice_number }}</td>
                            <td class="px-6 py-4 text-slate-600">{{ $inv->case->client->name }}</td>
                            <td class="px-6 py-4 font-mono font-bold">KES {{ number_format($inv->total_amount) }}</td>
                            <td class="px-6 py-4 font-mono text-emerald-600 font-bold">KES {{ number_format($paid) }}</td>
                            <td class="px-6 py-4 font-mono font-bold {{ $balance > 0 ? 'text-amber-600' : 'text-slate-400' }}">
                                KES {{ number_format($balance) }}
                            </td>
                            <td class="px-6 py-4 text-right">
                                <button @click="
                                    historyModal = true;
                                    activeInvoice = '{{ $inv->invoice_number }}';
                                    payments = {{ $inv->payments->toJson() }};
                                " class="text-xs font-bold bg-slate-100 text-slate-600 px-3 py-1.5 rounded-lg hover:bg-slate-200 transition border border-slate-200 flex items-center gap-2 justify-end ml-auto">
                                    <i class="ph-bold ph-clock-counter-clockwise"></i> View History
                                </button>
                            </td>
                            <td class="px-6 py-4 text-right">
                                <button @click="editModal = true; editType = 'invoice'; editData = { id: {{ $inv->id }}, amount: '{{ $inv->total_amount }}', status: '{{ $inv->status }}' }" class="text-indigo-600 font-bold hover:underline">Edit</button>
                            </td>
                        </tr>
                        @endforeach
                    </tbody>
                </table>
                <div class="p-4">{{ $invoices->links() }}</div>
            </div>

            <div x-show="tab === 'expenses'" style="display: none;" class="bg-white rounded-2xl shadow-sm ring-1 ring-slate-900/5 overflow-hidden">
                </div>
        </div>

        <div x-show="historyModal" style="display: none;" class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-900/60 backdrop-blur-sm" x-transition.opacity>
            <div class="bg-white rounded-3xl p-0 max-w-2xl w-full shadow-2xl overflow-hidden" @click.away="historyModal = false">
                <div class="p-6 border-b border-slate-100 bg-slate-50 flex justify-between items-center">
                    <div>
                        <h3 class="text-lg font-black text-slate-800 flex items-center gap-2">
                            <i class="ph-duotone ph-receipt text-indigo-600"></i> Payment Breakdown
                        </h3>
                        <p class="text-xs text-slate-500">Invoice #<span x-text="activeInvoice"></span></p>
                    </div>
                    <button @click="historyModal = false" class="text-slate-400 hover:text-slate-600"><i class="ph-bold ph-x text-xl"></i></button>
                </div>

                <div class="p-0">
                    <template x-if="payments.length === 0">
                        <div class="p-8 text-center text-slate-500 italic">
                            No payments recorded for this invoice yet.
                        </div>
                    </template>

                    <template x-if="payments.length > 0">
                        <table class="min-w-full text-left text-sm">
                            <thead class="bg-white border-b border-slate-100 text-slate-400 font-bold uppercase text-[10px]">
                                <tr>
                                    <th class="px-6 py-3">Date</th>
                                    <th class="px-6 py-3">Ref / Method</th>
                                    <th class="px-6 py-3 text-right">Amount Paid</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-slate-50">
                                <template x-for="pay in payments" :key="pay.id">
                                    <tr class="hover:bg-slate-50">
                                        <td class="px-6 py-3 text-slate-600" x-text="new Date(pay.payment_date).toLocaleDateString()"></td>
                                        <td class="px-6 py-3">
                                            <div class="font-bold text-slate-700" x-text="pay.transaction_ref || 'N/A'"></div>
                                            <div class="text-[10px] text-slate-400 uppercase" x-text="pay.method"></div>
                                        </td>
                                        <td class="px-6 py-3 text-right font-mono font-bold text-emerald-600">
                                            + KES <span x-text="new Intl.NumberFormat().format(pay.amount)"></span>
                                        </td>
                                    </tr>
                                </template>
                            </tbody>
                            <tfoot class="bg-slate-50 border-t border-slate-100">
                                <tr>
                                    <td colspan="2" class="px-6 py-3 text-right font-bold text-slate-600">Total Paid:</td>
                                    <td class="px-6 py-3 text-right font-black text-slate-800">
                                        KES <span x-text="new Intl.NumberFormat().format(payments.reduce((sum, p) => sum + parseFloat(p.amount), 0))"></span>
                                    </td>
                                </tr>
                            </tfoot>
                        </table>
                    </template>
                </div>

                <div class="p-4 bg-slate-50 text-right">
                    <button @click="historyModal = false" class="px-4 py-2 bg-white border border-slate-300 rounded-lg text-sm font-bold text-slate-700 hover:bg-slate-100 transition">Close</button>
                </div>
            </div>
        </div>

      <div x-show="editModal" style="display: none;" class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-900/60 backdrop-blur-sm" x-transition.opacity>
            <div class="bg-white rounded-3xl p-8 max-w-md w-full shadow-2xl" @click.away="editModal = false">

                <h3 class="text-xl font-black text-slate-800 mb-6 flex items-center gap-2">
                    <i class="ph-bold ph-note-pencil text-indigo-600"></i>
                    Edit <span x-text="editType.charAt(0).toUpperCase() + editType.slice(1)"></span>
                </h3>

                <form :action="editType === 'invoice' ? `/admin/finance/invoice/${editData.id}` : `/admin/finance/payment/${editData.id}`" method="POST">
                    @csrf
                    @method('PUT')

                    <div class="space-y-4">
                        <div>
                            <label class="block text-xs font-bold text-slate-400 uppercase mb-1">Total Amount (KES)</label>
                            <input type="number" name="amount" x-model="editData.amount" class="w-full rounded-xl border-slate-200 font-bold focus:border-indigo-500 focus:ring-indigo-500" required step="0.01" min="0">

                            <template x-if="editType === 'invoice'">
                                <p class="text-[9px] text-slate-400 mt-1 italic">Warning: Do not lower the total below the amount already paid by the client.</p>
                            </template>
                        </div>

                        <template x-if="editType === 'invoice'">
                            <div>
                                <label class="block text-xs font-bold text-slate-400 uppercase mb-1">Invoice Status</label>
                                <select name="status" x-model="editData.status" class="w-full rounded-xl border-slate-200 focus:border-indigo-500 focus:ring-indigo-500">
                                    <option value="unpaid">Unpaid</option>
                                    <option value="partially_paid">Partially Paid</option>
                                    <option value="paid">Fully Paid</option>
                                    <option value="overdue">Overdue</option>
                                </select>
                            </div>
                        </template>

                        <template x-if="editType === 'expense'">
                            <div>
                                <label class="block text-xs font-bold text-slate-400 uppercase mb-1">Reference No.</label>
                                <input type="text" name="transaction_ref" x-model="editData.ref" class="w-full rounded-xl border-slate-200 focus:border-rose-500 focus:ring-rose-500">
                            </div>
                        </template>

                        <div class="flex gap-3 pt-4 border-t border-slate-100 mt-6">
                            <button type="button" @click="editModal = false" class="flex-1 px-4 py-3 bg-slate-100 text-slate-600 rounded-xl font-bold hover:bg-slate-200 transition">
                                Cancel
                            </button>
                            <button type="submit" class="flex-1 px-4 py-3 text-white rounded-xl font-bold shadow-lg transition"
                                    :class="editType === 'invoice' ? 'bg-indigo-600 hover:bg-indigo-700 shadow-indigo-200' : 'bg-rose-600 hover:bg-rose-700 shadow-rose-200'">
                                Save Changes
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>

    </div>
</x-app-layout>
