<x-app-layout>
    <div class="flex flex-col md:flex-row md:items-center justify-between mb-6 md:mb-8 gap-4 md:gap-0">
        <div class="flex items-center gap-3 md:gap-4">
            <div class="header-icon-size ios-icon-container shadow-lg flex items-center justify-center">
                <img src="{{ asset('uploads/dashboard-icons/Expenses.jpg') }}" alt="Expenses" class="w-full h-full object-cover">
            </div>
            <div>
                <h2 class="text-2xl font-bold text-slate-800">Expenses Log</h2>
                <p class="text-slate-500 text-xs mt-1">Record business outgoings, purchases, utility bills, and operations.</p>
            </div>
        </div>
        @if(!auth()->user()->isAccountant())
        <div class="mt-4 md:mt-0 flex space-x-3" x-data="">
            <button @click="$dispatch('open-category-modal')" class="inline-flex items-center justify-center py-2.5 px-4 bg-black hover:bg-slate-800 text-white text-sm font-semibold rounded-xl border border-slate-200 transition duration-150">
                📁 Manage Categories
            </button>
            <a href="{{ route('expenses.create') }}" class="inline-flex items-center justify-center py-2.5 px-5 bg-brand-500 hover:bg-brand-600 text-white text-sm font-semibold rounded-xl shadow-sm transition duration-150">
                <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M12 4v16m8-8H4"></path>
                </svg>
                Add New Expense
            </a>
        </div>
        @endif
    </div>

    <!-- Filters Section -->
    <div x-data="{ openFilter: false }" class="bg-white border border-slate-200 rounded-2xl p-4 mb-4 md:mb-6">
        <div class="flex items-center justify-between md:hidden cursor-pointer" @click="openFilter = !openFilter">
            <div class="flex items-center gap-2 text-xs font-bold uppercase tracking-wider text-slate-600">
                <svg class="w-4 h-4 text-brand-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M3 4a1 1 0 011-1h16a1 1 0 011 1v2.586a1 1 0 01-.293.707l-6.414 6.414a1 1 0 00-.293.707V17l-4 4v-6.586a1 1 0 00-.293-.707L3.293 7.293A1 1 0 013 6.586V4z"></path></svg>
                <span>Filter Records</span>
            </div>
            <svg class="w-4 h-4 text-slate-500 transition-transform duration-200" :class="{'rotate-180': openFilter}" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M19 9l-7 7-7-7"></path></svg>
        </div>

        <form action="{{ route('expenses.index') }}" method="GET"
              class="grid grid-cols-1 md:grid-cols-4 gap-4 items-end mt-4 md:mt-0"
              x-show="true"
              :class="{'hidden': !openFilter, 'md:grid': true}">
            <div>
                <label class="block text-xs font-semibold text-slate-500 uppercase tracking-wider mb-1.5">Date From</label>
                <input type="date" name="date_from" value="{{ $dateFrom }}"
                    class="w-full py-2 px-3 bg-white border border-slate-300 focus:border-brand-500 focus:ring-0 rounded-xl text-slate-700 text-sm focus:outline-none transition duration-150">
            </div>

            <div>
                <label class="block text-xs font-semibold text-slate-500 uppercase tracking-wider mb-1.5">Date To</label>
                <input type="date" name="date_to" value="{{ $dateTo }}"
                    class="w-full py-2 px-3 bg-white border border-slate-300 focus:border-brand-500 focus:ring-0 rounded-xl text-slate-700 text-sm focus:outline-none transition duration-150">
            </div>

            <div>
                <label class="block text-xs font-semibold text-slate-500 uppercase tracking-wider mb-1.5">Category</label>
                <select name="category_id"
                    class="w-full py-2 px-3 bg-white border border-slate-300 focus:border-brand-500 focus:ring-0 rounded-xl text-slate-700 text-sm focus:outline-none transition duration-150">
                    <option value="">All Categories</option>
                    @foreach($parentCategories as $parent)
                        <option value="{{ $parent->id }}" {{ $categoryId == $parent->id ? 'selected' : '' }} class="font-bold text-slate-500">{{ $parent->name }}</option>
                        @foreach($parent->children as $child)
                            <option value="{{ $child->id }}" {{ $categoryId == $child->id ? 'selected' : '' }}>&nbsp;&nbsp;&mdash;&nbsp;{{ $child->name }}</option>
                        @endforeach
                    @endforeach
                </select>
            </div>

            <div class="flex gap-2">
                <button type="submit" class="flex-1 py-2.5 px-4 bg-brand-500 hover:bg-brand-600 text-white font-semibold rounded-xl text-sm transition duration-150">
                    Filter
                </button>
                @if($dateFrom || $dateTo || $categoryId || $search)
                    <a href="{{ route('expenses.index') }}" class="py-2.5 px-3 bg-red-50 hover:bg-red-100 text-red-600 rounded-xl text-sm border border-red-200 transition duration-150">
                        Reset
                    </a>
                @endif
            </div>
        </form>
    </div>

    <!-- Summary Box -->
    <div class="flex justify-between items-center mb-6 bg-white border border-slate-200 rounded-xl p-4">
        <span class="text-xs text-slate-500 font-semibold uppercase tracking-wider">Filtered Expenses Total:</span>
        <span class="text-lg md:text-xl font-bold text-rose-650 font-mono text-red-600">{{ $currencySymbol }}{{ number_format($totalExpense, 2) }}</span>
    </div>

    <!-- Data Table Registry -->
    <div class="bg-white border border-slate-200 rounded-xl shadow-sm p-5 overflow-hidden">
        <div class="overflow-x-auto">
            <table class="w-full text-left text-sm border-collapse">
                <thead>
                    <tr class="border-b border-slate-200 text-slate-400 text-xs uppercase tracking-wider">
                        <th class="pb-3 font-semibold">Date</th>
                        <th class="pb-3 font-semibold">Category</th>
                        <th class="pb-3 font-semibold">Payee</th>
                        <th class="pb-3 font-semibold">Paid From</th>
                        <th class="pb-3 font-semibold">Transaction ID</th>
                        <th class="pb-3 font-semibold text-right">Amount</th>
                        <th class="pb-3 font-semibold text-center">Actions</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-slate-200 text-base">
                    @forelse($expenses as $exp)
                        <tr class="hover:bg-slate-50">
                            <td class="py-3.5">{{ $exp->date->format('d-m-Y') }}</td>
                            <td class="py-3.5">
                                @if($exp->category)
                                    @if($exp->category->parent)
                                        <span class="text-slate-400 text-xs block">{{ $exp->category->parent->name }}</span>
                                    @endif
                                    <span class="font-medium text-slate-700">{{ $exp->category->name }}</span>
                                @else
                                    <span class="text-slate-400 italic">Uncategorized</span>
                                @endif
                            </td>
                            <td class="py-3.5 text-slate-700">{{ $exp->payee_bank_name ?: '-' }}</td>
                            <td class="py-3.5 text-slate-600">{{ $exp->bankAccount ? $exp->bankAccount->name : '-' }}</td>
                            <td class="py-3.5 font-mono text-xs text-slate-500">{{ $exp->transaction_id ?? '-' }}</td>
                            <td class="py-3.5 text-right font-mono text-rose-600 font-bold">
                                @if($exp->original_currency)
                                    <span class="block text-xs text-slate-400 font-normal">{{ number_format($exp->original_amount, 2) }} {{ $exp->original_currency }}</span>
                                @endif
                                <span>{{ $currencySymbol }}{{ number_format($exp->amount, 2) }}</span>
                            </td>
                            <td class="py-3.5 text-center">
                                <div class="flex items-center justify-center space-x-2">
                                    <a href="{{ route('expenses.show', $exp->id) }}" class="text-black hover:text-slate-700 text-sm font-semibold">👁 View</a>
                                    @if(!auth()->user()->isAccountant())
                                    <a href="{{ route('expenses.edit', $exp->id) }}" class="text-brand-500 hover:text-brand-600 text-sm font-semibold">✏️ Edit</a>
                                    @endif
                                    @if(auth()->user()->isAdmin())
                                        <form action="{{ route('expenses.destroy', $exp->id) }}" method="POST" onsubmit="return confirm('Delete this record permanently?')">
                                            @csrf
                                            @method('DELETE')
                                            <button type="submit" class="text-red-600 hover:text-red-500 text-sm font-semibold">🗑 Del</button>
                                        </form>
                                    @endif
                                </div>
                            </td>
                        </tr>
                    @empty
                        <tr>
                            <td colspan="7" class="py-12 text-center text-slate-400">No expense records logged.</td>
                        </tr>
                    @endforelse
                </tbody>
            </table>
        </div>

        <div class="mt-4 border-t border-slate-200 pt-4">
            {{ $expenses->links() }}
        </div>
    </div>

    <!-- Inline Category Management Modal -->
    <div x-data="{ 
        open: false, 
        parents: [],
        newCategoryName: '',
        newParentId: '',
        saving: false,
        
        editingId: null,
        editingName: '',
        editingParentId: '',
        
        async fetchCategories() {
            try {
                let url = new URL('{{ route('expenses.categories.list') }}', window.location.origin);
                let res = await fetch(url.pathname + url.search);
                if (!res.ok) {
                    throw new Error('Server returned status: ' + res.status);
                }
                let data = await res.json();
                this.parents = data.categories;
            } catch(e) {
                console.error('Failed to fetch categories:', e);
                alert('Failed to load categories: ' + e.message);
            }
        },

        async saveCategory() {
            if(!this.newCategoryName) return;
            this.saving = true;
            try {
                let params = new URLSearchParams();
                params.append('name', this.newCategoryName);
                if(this.newParentId) params.append('parent_id', this.newParentId);
                params.append('_token', '{{ csrf_token() }}');
                
                let url = new URL('{{ route('expenses.categories.store-ajax') }}', window.location.origin);
                let res = await fetch(url.pathname + url.search, {
                    method: 'POST',
                    body: params,
                    headers: { 'Accept': 'application/json' }
                });
                if (!res.ok) {
                    throw new Error('Server returned status: ' + res.status);
                }
                this.newCategoryName = '';
                this.newParentId = '';
                await this.fetchCategories();
                alert('Category added successfully.');
            } catch(e) {
                console.error('Failed to save category:', e);
                alert('Failed to save category: ' + e.message);
            }
            finally { this.saving = false; }
        },

        startEdit(category) {
            this.editingId = category.id;
            this.editingName = category.name;
            this.editingParentId = category.parent_id || '';
        },

        async updateCategory(id) {
            if(!this.editingName) return;
            try {
                let params = new URLSearchParams();
                params.append('name', this.editingName);
                if(this.editingParentId) params.append('parent_id', this.editingParentId);
                params.append('_token', '{{ csrf_token() }}');
                
                let targetUrl = '{{ route('expenses.categories.update-ajax', ['category' => 'TEMP_ID']) }}'.replace('TEMP_ID', id);
                let url = new URL(targetUrl, window.location.origin);
                let res = await fetch(url.pathname + url.search, {
                    method: 'POST',
                    body: params,
                    headers: { 'Accept': 'application/json' }
                });
                if (!res.ok) {
                    throw new Error('Server returned status: ' + res.status);
                }
                this.editingId = null;
                await this.fetchCategories();
                alert('Category updated successfully.');
            } catch(e) {
                console.error('Failed to update category:', e);
                alert('Failed to update category: ' + e.message);
            }
        },

        async deleteCategory(id) {
            if(!confirm('Are you sure you want to delete this category? Any associated expenses will be uncategorized.')) return;
            try {
                let params = new URLSearchParams();
                params.append('_token', '{{ csrf_token() }}');
                
                let targetUrl = '{{ route('expenses.categories.destroy-ajax', ['id' => 'TEMP_ID']) }}'.replace('TEMP_ID', id);
                let url = new URL(targetUrl, window.location.origin);
                let res = await fetch(url.pathname + url.search, {
                    method: 'POST',
                    body: params,
                    headers: { 'Accept': 'application/json' }
                });
                if (!res.ok) {
                    throw new Error('Server returned status: ' + res.status);
                }
                await this.fetchCategories();
            } catch(e) {
                console.error('Failed to delete category:', e);
                alert('Failed to delete category: ' + e.message);
            }
        }
    }" x-on:open-category-modal.window="open = true; fetchCategories()" class="relative">
        <div x-show="open" x-cloak class="fixed inset-0 z-50 flex items-center justify-center bg-black/40" @click.self="open = false">
            <div class="bg-white rounded-2xl shadow-2xl p-6 w-full max-w-3xl mx-4 max-h-[85vh] overflow-y-auto">
                <div class="flex items-center justify-between border-b border-slate-200 pb-3 mb-4">
                    <h3 class="text-lg font-bold text-slate-800">📂 Manage Expense Categories</h3>
                    <button @click="open = false" class="text-slate-400 hover:text-slate-600 text-2xl leading-none">&times;</button>
                </div>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <!-- Create Category -->
                    <div class="bg-slate-50 border border-slate-200 rounded-xl p-4 space-y-4 h-max">
                        <h4 class="text-sm font-semibold text-slate-700">Add New Category</h4>
                        <div class="space-y-3">
                            <div>
                                <label class="block text-xs font-semibold text-slate-600 mb-1">Category Name *</label>
                                <input type="text" x-model="newCategoryName" placeholder="e.g. Office Supplies"
                                    class="w-full py-2 px-3 border border-slate-300 rounded-xl text-sm focus:outline-none focus:border-brand-500">
                            </div>
                            <div>
                                <label class="block text-xs font-semibold text-slate-600 mb-1">Parent Category (optional)</label>
                                <select x-model="newParentId" class="w-full py-2 px-3 border border-slate-300 rounded-xl text-sm text-slate-700">
                                    <option value="">-- No Parent (Make Main Category) --</option>
                                    <template x-for="p in parents.filter(c => !c.parent_id)" :key="p.id">
                                        <option :value="p.id" x-text="p.name"></option>
                                    </template>
                                </select>
                            </div>
                            <button type="button" @click="saveCategory()" :disabled="saving || !newCategoryName"
                                class="w-full py-2 bg-brand-500 hover:bg-brand-600 disabled:opacity-55 text-white font-semibold rounded-xl text-sm transition">
                                <span x-text="saving ? 'Saving...' : 'Add Category'"></span>
                            </button>
                        </div>
                    </div>

                    <!-- Categories list -->
                    <div class="space-y-3">
                        <h4 class="text-sm font-semibold text-slate-700">Existing Categories</h4>
                        <div class="space-y-2 max-h-[45vh] overflow-y-auto pr-1">
                            <template x-for="p in parents" :key="p.id">
                                <div class="bg-white border border-slate-200 rounded-xl p-3 shadow-xs">
                                    <!-- View Mode -->
                                    <div x-show="editingId !== p.id" class="flex justify-between items-center">
                                        <span class="font-bold text-sm text-slate-800" :class="p.parent_id ? 'pl-4 text-slate-600 font-medium' : ''" x-text="p.parent_id ? '↳ ' + p.name : p.name"></span>
                                        <div class="flex items-center space-x-2">
                                            <button type="button" @click="startEdit(p)" class="text-brand-500 text-xs font-semibold hover:underline">Edit</button>
                                            <span class="text-slate-300">|</span>
                                            <button type="button" @click="deleteCategory(p.id)" class="text-rose-600 text-xs font-semibold hover:underline">Delete</button>
                                        </div>
                                    </div>
                                    
                                    <!-- Edit Mode -->
                                    <div x-show="editingId === p.id" class="space-y-3" x-cloak>
                                        <div>
                                            <label class="block text-xxs font-semibold text-slate-500 uppercase tracking-wider mb-1">Edit Category Name</label>
                                            <input type="text" x-model="editingName" class="w-full py-1 px-2 border border-slate-300 rounded-lg text-sm focus:outline-none focus:border-brand-500">
                                        </div>
                                        <div>
                                            <label class="block text-xxs font-semibold text-slate-500 uppercase tracking-wider mb-1">Parent Category</label>
                                            <select x-model="editingParentId" class="w-full py-1 px-2 border border-slate-300 rounded-lg text-sm text-slate-700">
                                                <option value="">-- No Parent (Make Main Category) --</option>
                                                <template x-for="parentOpt in parents.filter(c => !c.parent_id && c.id !== p.id)" :key="parentOpt.id">
                                                    <option :value="parentOpt.id" :selected="parentOpt.id == editingParentId" x-text="parentOpt.name"></option>
                                                </template>
                                            </select>
                                        </div>
                                        <div class="flex justify-end space-x-2 pt-1">
                                            <button type="button" @click="editingId = null" class="py-1 px-2.5 bg-slate-100 hover:bg-slate-200 text-slate-700 text-xs font-semibold rounded-lg transition">Cancel</button>
                                            <button type="button" @click="updateCategory(p.id)" class="py-1 px-2.5 bg-brand-500 hover:bg-brand-600 text-white text-xs font-semibold rounded-lg transition">Save</button>
                                        </div>
                                    </div>
                                </div>
                            </template>
                            <div x-show="parents.length === 0" class="text-center py-6 text-slate-400 text-sm">No categories found.</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</x-app-layout>