@extends('layouts.aura-main')

@section('main-content')
<div x-data="{ 
    openModal: {{ $errors->any() ? 'true' : 'false' }}, 
    deleteModal: false,
    errorModal: {{ $errors->any() ? 'true' : 'false' }},
    editMode: false,
    loading: false,
    uploading: false,
    searchQuery: '', 
    filterCategory: 'all',
    
    // Form Data
    groupId: '',
    groupName: '',
    categoryId: '',
    typeCount: 0,
    actionUrl: '',

    setEdit(group) {
        this.editMode = true;
        this.groupId = group.id;
        this.groupName = group.name;
        this.categoryId = group.primary_category_id;
        this.actionUrl = '{{ url('accounting/groups') }}/' + group.id;
        this.openModal = true;
    },

    setCreate() {
        this.editMode = false;
        this.groupId = '';
        this.groupName = '';
        this.categoryId = '';
        this.actionUrl = '{{ route('accounting.groups.store') }}';
        this.openModal = true;
    },

    confirmDelete(group) {
        this.groupId = group.id;
        this.groupName = group.name;
        this.typeCount = group.types_count || 0;
        this.deleteModal = true;
    },

    matchesSearch(name, catId) {
        const query = this.searchQuery.toLowerCase();
        const matchesText = name.toLowerCase().includes(query);
        const matchesCat = this.filterCategory === 'all' || catId == this.filterCategory;
        return matchesText && matchesCat;
    }
}">
    <div class="mb-6 flex flex-col lg:flex-row justify-between items-start lg:items-end gap-4">
        <div>
            <h1 class="text-lg font-bold text-slate-900 leading-tight">Account Groups</h1>
            <p class="text-slate-500 text-[11px] font-medium uppercase tracking-widest text-indigo-600">Sub-categories of your Pillars</p>
        </div>
        
        <div class="flex flex-wrap items-center gap-2 w-full lg:w-auto">
            <div class="flex items-center bg-slate-100 rounded-lg p-1 border border-slate-200">
                <a href="{{ route('accounting.groups.template') }}" 
                   class="text-[10px] font-bold text-slate-600 hover:text-indigo-600 px-3 py-1 transition flex items-center gap-1">
                    <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0L8 8m4-4v12" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path></svg>
                    Template
                </a>
                <div class="w-px h-4 bg-slate-200"></div>
                <form action="{{ route('accounting.groups.import') }}" method="POST" enctype="multipart/form-data" class="inline-flex">
                    @csrf
                    <input type="file" name="file" id="groupFileInput" class="hidden" @change="uploading = true; $el.form.submit()">
                    <button type="button" @click="document.getElementById('groupFileInput').click()" 
                            class="text-[10px] font-bold text-indigo-600 hover:text-indigo-800 px-3 py-1 transition flex items-center gap-2">
                        <span x-show="!uploading" class="flex items-center gap-1">
                            <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path d="M9 11l3-3m0 0l3 3m-3-3v8m0-13a9 9 0 110 18 9 9 0 010-18z" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path></svg>
                            Import
                        </span>
                        <span x-show="uploading" class="animate-spin h-3 w-3 border-2 border-indigo-600 border-t-transparent rounded-full"></span>
                    </button>
                </form>
            </div>

            <select x-model="filterCategory" class="bg-white border border-slate-200 rounded px-3 py-1.5 text-xs outline-none focus:border-indigo-500 shadow-sm font-medium text-slate-600">
                <option value="all">All Pillars</option>
                @foreach($categories as $category)
                    <option value="{{ $category->id }}">{{ $category->name }}</option>
                @endforeach
            </select>

            <div class="relative flex-grow lg:w-40">
                <span class="absolute inset-y-0 left-0 pl-3 flex items-center text-slate-400">
                    <svg class="h-3.5 w-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path></svg>
                </span>
                <input type="text" x-model="searchQuery" placeholder="Search..." class="w-full bg-white border border-slate-200 rounded px-3 py-1.5 pl-9 text-xs outline-none focus:border-indigo-500 transition shadow-sm">
            </div>
            
            <button @click="setCreate()" class="bg-indigo-600 text-white px-4 py-1.5 rounded text-[11px] font-bold shadow-sm hover:bg-indigo-700 transition">
                + Add Group
            </button>
        </div>
    </div>

    <div class="bg-white border border-slate-200 rounded shadow-sm overflow-hidden">
        <table class="w-full text-left border-collapse">
            <thead class="bg-slate-50 border-b border-slate-200 uppercase text-slate-400 text-[10px] font-bold">
                <tr>
                    <th class="px-4 py-2">Group Name</th>
                    <th class="px-4 py-2">Parent Pillar</th>
                    <th class="px-4 py-2 text-right">Actions</th>
                </tr>
            </thead>
            <tbody class="text-xs">
                @forelse($groups as $group)
                <tr x-show="matchesSearch('{{ addslashes($group->name) }}', '{{ $group->primary_category_id }}')" 
                    class="border-b border-slate-100 hover:bg-slate-50/50 transition" x-cloak x-transition.opacity>
                    <td class="px-4 py-2 font-semibold text-slate-700">{{ $group->name }}</td>
                    <td class="px-4 py-2">
                        <span class="px-2 py-0.5 rounded-full bg-slate-100 text-slate-600 font-bold text-[9px] uppercase">
                            {{ $group->category->name ?? $group->primaryCategory->name ?? 'N/A' }}
                        </span>
                    </td>
                    <td class="px-4 py-2 text-right flex justify-end gap-3">
                        <button @click="setEdit({ 
                            id: '{{ $group->id }}', 
                            name: '{{ addslashes($group->name) }}', 
                            primary_category_id: '{{ $group->primary_category_id }}' 
                        })" class="text-indigo-600 hover:underline">Edit</button>
                        
                        <button @click="confirmDelete({ 
                            id: '{{ $group->id }}', 
                            name: '{{ addslashes($group->name) }}', 
                            types_count: {{ $group->types_count ?? 0 }} 
                        })" class="text-red-400 hover:text-red-600">Delete</button>
                    </td>
                </tr>
                @empty
                <tr><td colspan="3" class="px-4 py-12 text-center text-slate-400 italic">No account groups found.</td></tr>
                @endforelse
            </tbody>
        </table>
    </div>

    <div x-show="openModal" class="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/40 backdrop-blur-sm" x-cloak x-transition>
        <div class="bg-white rounded shadow-xl w-full max-w-md p-6 border border-slate-200">
            <h2 class="text-sm font-bold text-slate-900 mb-4" x-text="editMode ? 'Edit Account Group' : 'New Account Group'"></h2>
            <form :action="actionUrl" method="POST" @submit="loading = true">
                @csrf
                <template x-if="editMode"><input type="hidden" name="_method" value="PUT"></template>
                <div class="space-y-4">
                    <div>
                        <label class="block text-[10px] font-bold text-slate-400 uppercase mb-1">Parent Pillar</label>
                        <select name="primary_category_id" x-model="categoryId" class="w-full bg-slate-50 border border-slate-200 rounded px-3 py-2 text-xs outline-none focus:border-indigo-500" required>
                            <option value="">Select a Pillar</option>
                            @foreach($categories as $category)
                                <option value="{{ $category->id }}">{{ $category->name }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div>
                        <label class="block text-[10px] font-bold text-slate-400 uppercase mb-1">Group Name</label>
                        <input type="text" name="name" x-model="groupName" class="w-full bg-slate-50 border border-slate-200 rounded px-3 py-2 text-xs outline-none focus:border-indigo-500" placeholder="e.g. Current Assets" required>
                    </div>
                </div>
                <div class="flex justify-end gap-2 pt-4 mt-6 border-t border-slate-100">
                    <button type="button" @click="openModal = false" class="text-[11px] font-bold text-slate-400 px-4 py-2 hover:text-slate-600">Cancel</button>
                    <button type="submit" :disabled="loading" class="bg-indigo-600 text-white text-[11px] font-bold px-5 py-2 rounded shadow-sm hover:bg-indigo-700 transition">
                        <span x-text="loading ? 'Processing...' : 'Save Group'"></span>
                    </button>
                </div>
            </form>
        </div>
    </div>

    <div x-show="deleteModal" class="fixed inset-0 z-[60] flex items-center justify-center bg-slate-900/60 backdrop-blur-sm" x-cloak x-transition>
        <div class="bg-white rounded-lg shadow-2xl w-full max-w-sm p-6 border border-slate-200 text-center">
            <div :class="typeCount > 0 ? 'bg-amber-50 text-amber-500' : 'bg-red-50 text-red-500'" class="w-12 h-12 rounded-full flex items-center justify-center mx-auto mb-4">
                <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"></path></svg>
            </div>
            <h3 class="text-sm font-bold text-slate-900 mb-2" x-text="typeCount > 0 ? 'Deletion Blocked' : 'Confirm Delete'"></h3>
            <p class="text-slate-500 text-[11px] mb-6 px-4">
                <template x-if="typeCount > 0">
                    <span>The group <strong class="text-slate-900" x-text="groupName"></strong> is linked to <span class="text-indigo-600 font-bold" x-text="typeCount"></span> types. Delete those first.</span>
                </template>
                <template x-if="typeCount == 0">
                    <span>Are you sure you want to delete <strong class="text-slate-900" x-text="groupName"></strong>? This is permanent.</span>
                </template>
            </p>
            <div class="flex flex-col gap-2">
                <template x-if="typeCount == 0">
                    <form :action="'{{ url('accounting/groups') }}/' + groupId" method="POST">
                        @csrf @method('DELETE')
                        <button type="submit" class="w-full bg-red-500 text-white text-[11px] font-bold py-2.5 rounded shadow-sm hover:bg-red-600 transition">Delete Group</button>
                    </form>
                </template>
                <button type="button" @click="deleteModal = false" class="w-full text-slate-400 text-[11px] font-bold py-2 hover:text-slate-600">
                    <span x-text="typeCount > 0 ? 'I Understand' : 'Cancel'"></span>
                </button>
            </div>
        </div>
    </div>

    <div x-show="errorModal" class="fixed inset-0 z-[70] flex items-center justify-center bg-slate-900/60 backdrop-blur-sm" x-cloak x-transition>
        <div class="bg-white rounded-lg shadow-2xl w-full max-w-md p-6 border border-slate-200" @click.away="errorModal = false">
            <div class="w-12 h-12 rounded-full bg-red-50 text-red-500 flex items-center justify-center mx-auto mb-4">
                <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"></path></svg>
            </div>
            <h3 class="text-sm font-bold text-slate-900 text-center mb-2">Import Blocked</h3>
            <div class="max-h-48 overflow-y-auto bg-red-50 rounded border border-red-100 p-3 mb-6">
                <ul class="space-y-2">
                    @foreach($errors->all() as $error)
                        <li class="text-[10px] text-red-600 leading-tight">• {{ $error }}</li>
                    @endforeach
                </ul>
            </div>
            <button type="button" @click="errorModal = false" class="w-full bg-slate-900 text-white text-[11px] font-bold py-2.5 rounded hover:bg-slate-800 transition">Fix and Retry</button>
        </div>
    </div>
</div>
@endsection