<x-layouts::app :title="__('System Settings')">
    <x-slot name="header">
        <flux:heading size="xl">{{ __('System Settings') }}</flux:heading>
    </x-slot>

    <div class="container mx-auto px-4 py-6 space-y-6">
        <flux:card>
            <div class="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
                <div class="space-y-2">
                    <flux:heading size="lg">{{ __('Settings') }}</flux:heading>
                    <flux:text variant="subtle">{{ __('Configure school settings, bank accounts, and import templates from one place.') }}</flux:text>
                </div>
            </div>

            <div class="border-b border-slate-200 mt-6">
                <nav class="-mb-px flex flex-wrap gap-2 sm:gap-4" aria-label="Tabs">
                    <button type="button" data-tab="general" class="settings-tab-button whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm transition-colors duration-200 border-indigo-500 text-indigo-600">
                        <i class="fas fa-sliders-h mr-2"></i> {{ __('General') }}
                    </button>
                    <button type="button" data-tab="bank-details" class="settings-tab-button whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm transition-colors duration-200 border-transparent text-slate-500 hover:text-slate-700 hover:border-slate-300">
                        <i class="fas fa-university mr-2"></i> {{ __('Bank Details') }}
                    </button>
                    <button type="button" data-tab="imports" class="settings-tab-button whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm transition-colors duration-200 border-transparent text-slate-500 hover:text-slate-700 hover:border-slate-300">
                        <i class="fas fa-file-import mr-2"></i> {{ __('Imports') }}
                    </button>
                </nav>
            </div>
        </flux:card>

        <flux:card>
            <div class="p-6">
                <div id="tab-general" class="tab-content">
                    <form action="{{ route('settings.store') }}" method="POST" class="max-w-xl space-y-6">
                        @csrf
                        <div class="space-y-3">
                            <x-input-label for="school_name" :value="__('School Name')" class="font-bold mb-2" />
                            <x-text-input id="school_name" name="school_name" type="text" class="mt-1 block w-full" :value="$settings['school_name'] ?? ''" required />
                            <flux:text variant="subtle">{{ __('Displayed at the top of the dashboard.') }}</flux:text>
                        </div>

                        <div class="space-y-3">
                            <x-input-label for="current_term" :value="__('Current Term')" class="font-bold mb-2" />
                            <select id="current_term" name="current_term" required class="mt-1 block w-full border-slate-300 focus:border-indigo-500 focus:ring-indigo-500 rounded-md shadow-sm transition duration-150 ease-in-out">
                                @foreach(['Term 1', 'Term 2', 'Term 3'] as $t)
                                    <option value="{{ $t }}" {{ ($settings['current_term'] ?? 'Term 1') === $t ? 'selected' : '' }}>{{ $t }}</option>
                                @endforeach
                            </select>
                            <flux:text variant="subtle">{{ __('Pre-selected when recording new payments.') }}</flux:text>
                        </div>

                        <x-primary-button>
                            <i class="fas fa-save mr-2"></i> {{ __('Save') }}
                        </x-primary-button>
                    </form>
                </div>

                <div id="tab-bank-details" class="tab-content hidden">
                    <flux:text variant="subtle" class="mb-6 flex items-center gap-2">
                        <i class="fas fa-info-circle text-indigo-500"></i>
                        {{ __('These accounts are shown to parents when they choose Bank Transfer. Click a row to edit it.') }}
                    </flux:text>

                    <div class="grid grid-cols-1 lg:grid-cols-12 gap-8">
                        <div class="lg:col-span-7 overflow-x-auto">
                            @if($bankAccounts->isEmpty())
                                <flux:card color="yellow" class="border-l-4 border-yellow-400 bg-yellow-50 p-4 mb-4">
                                    <div class="flex items-center gap-3">
                                        <i class="fas fa-exclamation-triangle text-yellow-400"></i>
                                        <flux:text>{{ __('No bank accounts added yet.') }}</flux:text>
                                    </div>
                                </flux:card>
                            @else
                                <table class="min-w-full table-reset divide-y divide-slate-200 border border-slate-100 rounded-lg overflow-hidden" id="bankAccountTable">
                                    <thead class="bg-slate-50">
                                        <tr>
                                            <th class="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">{{ __('Label') }}</th>
                                            <th class="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">{{ __('Bank') }}</th>
                                            <th class="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">{{ __('Account No.') }}</th>
                                            <th class="px-4 py-3 text-center text-xs font-semibold text-slate-500 uppercase tracking-wider">{{ __('Active') }}</th>
                                            <th class="px-4 py-3 text-center text-xs font-semibold text-slate-500 uppercase tracking-wider">{{ __('Actions') }}</th>
                                        </tr>
                                    </thead>
                                    <tbody class="bg-white divide-y divide-slate-200">
                                        @foreach($bankAccounts as $ba)
                                            <tr class="bank-row hover:bg-slate-50 cursor-pointer transition-colors duration-150"
                                                data-id="{{ $ba->id }}"
                                                data-label="{{ $ba->label }}"
                                                data-bank_name="{{ $ba->bank_name }}"
                                                data-account_name="{{ $ba->account_name }}"
                                                data-account_number="{{ $ba->account_number }}"
                                                data-branch="{{ $ba->branch }}"
                                                data-swift_code="{{ $ba->swift_code }}"
                                                data-is_active="{{ $ba->is_active ? '1' : '0' }}"
                                                title="{{ __('Click to edit') }}">
                                                <td class="px-4 py-4 whitespace-nowrap text-sm text-slate-900">{{ $ba->label ?: '—' }}</td>
                                                <td class="px-4 py-4 whitespace-nowrap text-sm text-slate-600">{{ $ba->bank_name }}</td>
                                                <td class="px-4 py-4 whitespace-nowrap text-sm font-mono text-slate-800"><code>{{ $ba->account_number }}</code></td>
                                                <td class="px-4 py-4 whitespace-nowrap text-center">
                                                    @if($ba->is_active)
                                                        <flux:badge color="green">{{ __('Yes') }}</flux:badge>
                                                    @else
                                                        <flux:badge color="slate">{{ __('No') }}</flux:badge>
                                                    @endif
                                                </td>
                                                <td class="px-4 py-4 whitespace-nowrap text-center text-sm font-medium">
                                                    <form action="{{ route('bank-accounts.destroy', $ba) }}" method="POST" onclick="event.stopPropagation()" class="inline-block">
                                                        @csrf @method('DELETE')
                                                        <button class="text-red-600 hover:text-red-900 confirm-delete p-2 transition-colors duration-150" type="button" title="{{ __('Delete') }}">
                                                            <i class="fas fa-trash-alt"></i>
                                                        </button>
                                                    </form>
                                                </td>
                                            </tr>
                                        @endforeach
                                    </tbody>
                                </table>
                            @endif
                        </div>

                        <div class="lg:col-span-5">
                            <flux:card class="p-6">
                                <flux:heading size="lg" class="mb-6" id="bankFormTitle">
                                    <i class="fas fa-plus-circle text-green-500 mr-2"></i> {{ __('Add Bank Account') }}
                                </flux:heading>

                                <form id="bankAccountForm" action="{{ route('bank-accounts.store') }}" method="POST" class="space-y-4">
                                    @csrf
                                    <div id="bankMethodField"></div>

                                    <div>
                                        <x-input-label for="ba_label" :value="__('Label (optional)')" class="text-xs font-bold uppercase tracking-wider text-slate-500" />
                                        <x-text-input id="ba_label" name="label" type="text" class="mt-1 block w-full" placeholder="e.g. Main Account" />
                                    </div>
                                    <div>
                                        <x-input-label for="ba_bank_name" :value="__('Bank Name *')" class="text-xs font-bold uppercase tracking-wider text-slate-500" />
                                        <x-text-input id="ba_bank_name" name="bank_name" type="text" class="mt-1 block w-full" placeholder="e.g. Bank of Kigali" required />
                                    </div>
                                    <div>
                                        <x-input-label for="ba_account_name" :value="__('Account Name *')" class="text-xs font-bold uppercase tracking-wider text-slate-500" />
                                        <x-text-input id="ba_account_name" name="account_name" type="text" class="mt-1 block w-full" placeholder="School legal name" required />
                                    </div>
                                    <div>
                                        <x-input-label for="ba_account_number" :value="__('Account Number *')" class="text-xs font-bold uppercase tracking-wider text-slate-500" />
                                        <x-text-input id="ba_account_number" name="account_number" type="text" class="mt-1 block w-full" placeholder="000000000" required />
                                    </div>
                                    <div class="grid grid-cols-2 gap-4">
                                        <div>
                                            <x-input-label for="ba_branch" :value="__('Branch / Code')" class="text-xs font-bold uppercase tracking-wider text-slate-500" />
                                            <x-text-input id="ba_branch" name="branch" type="text" class="mt-1 block w-full" placeholder="e.g. Kigali City" />
                                        </div>
                                        <div>
                                            <x-input-label for="ba_swift_code" :value="__('SWIFT / BIC')" class="text-xs font-bold uppercase tracking-wider text-slate-500" />
                                            <x-text-input id="ba_swift_code" name="swift_code" type="text" class="mt-1 block w-full" placeholder="BKIGRWRW" />
                                        </div>
                                    </div>
                                    <div class="flex items-center gap-3 mt-4">
                                        <input type="checkbox" id="ba_is_active" name="is_active" value="1" checked class="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-slate-300 rounded">
                                        <label for="ba_is_active" class="ml-2 block text-sm text-slate-700">{{ __('Active (shown to parents)') }}</label>
                                    </div>
                                    <div class="flex flex-wrap gap-3 pt-4 border-t border-slate-200 mt-6">
                                        <x-primary-button id="bankSubmitBtn">
                                            <i class="fas fa-save mr-2"></i> {{ __('Save') }}
                                        </x-primary-button>
                                        <button type="button" class="inline-flex items-center px-4 py-2 bg-white border border-slate-300 rounded-md font-semibold text-xs text-slate-700 uppercase tracking-widest shadow-sm hover:bg-slate-50 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 disabled:opacity-25 transition ease-in-out duration-150" id="bankCancelBtn" style="display:none;" onclick="resetBankForm()">
                                            <i class="fas fa-times mr-2"></i> {{ __('Cancel') }}
                                        </button>
                                    </div>
                                </form>
                            </flux:card>
                        </div>
                    </div>
                </div>

                <div id="tab-imports" class="tab-content hidden">
                    <flux:text variant="subtle" class="mb-8 flex items-center gap-2">
                        <i class="fas fa-info-circle text-indigo-500"></i>
                        {{ __('Upload Excel files to import records. Use the sample templates to ensure correct data format.') }}
                    </flux:text>

                    <div class="grid grid-cols-1 md:grid-cols-2 gap-8">
                        @foreach([
                            ['type' => 'students', 'title' => 'Students', 'icon' => 'fa-users', 'color' => 'text-blue-500'],
                            ['type' => 'classes', 'title' => 'Classes', 'icon' => 'fa-graduation-cap', 'color' => 'text-green-500'],
                            ['type' => 'destinations', 'title' => 'Destinations', 'icon' => 'fa-map-marker-alt', 'color' => 'text-red-500'],
                            ['type' => 'banks', 'title' => 'Bank Accounts', 'icon' => 'fa-university', 'color' => 'text-indigo-500']
                        ] as $item)
                            <flux:card class="overflow-hidden hover:shadow-md transition-shadow duration-200">
                                <div class="bg-slate-50 px-6 py-4 border-b border-slate-200">
                                    <h4 class="font-bold text-slate-700 flex items-center gap-2">
                                        <i class="fas {{ $item['icon'] }} {{ $item['color'] }}"></i>
                                        {{ $item['title'] }}
                                    </h4>
                                </div>
                                <div class="p-6">
                                    <form action="{{ route('import') }}" method="POST" enctype="multipart/form-data" class="import-form" data-type="{{ $item['type'] }}">
                                        @csrf
                                        <input type="hidden" name="import_type" value="{{ $item['type'] }}">

                                        <div class="dropzone border-2 border-dashed border-slate-300 rounded-lg p-8 text-center mb-6 bg-slate-50 hover:bg-slate-100 hover:border-indigo-400 cursor-pointer transition-all duration-200" id="dropzone-{{ $item['type'] }}">
                                            <input type="file" name="file" id="file-{{ $item['type'] }}" class="hidden" accept=".xlsx,.xls,.csv">
                                            <div class="dz-message">
                                                <i class="fas fa-cloud-upload-alt text-4xl text-slate-400 mb-3"></i>
                                                <p class="text-slate-600 font-medium">{{ __('Drag & drop Excel file here') }}</p>
                                                <p class="text-slate-400 text-sm">{{ __('or click to browse') }}</p>
                                            </div>
                                        </div>

                                        <div class="flex items-center justify-between gap-4 mt-4">
                                            <a href="{{ route('import.template', $item['type']) }}" class="inline-flex items-center text-sm font-medium text-indigo-600 hover:text-indigo-800 transition-colors duration-150">
                                                <i class="fas fa-download mr-2"></i> {{ __('Download Sample') }}
                                            </a>
                                            <x-primary-button>
                                                <i class="fas fa-upload mr-2"></i> {{ __('Import') }}
                                            </x-primary-button>
                                        </div>
                                    </form>
                                </div>
                            </flux:card>
                        @endforeach
                    </div>
                </div>
            </div>
        </flux:card>
    </div>

    <x-slot name="scripts">
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            const tabButtons = document.querySelectorAll('.settings-tab-button');
            const tabContents = document.querySelectorAll('.tab-content');
            const validTabs = ['general', 'bank-details', 'imports'];

            function setActiveTab(tab) {
                tabButtons.forEach(btn => {
                    if (btn.dataset.tab === tab) {
                        btn.classList.remove('text-slate-500', 'border-transparent', 'hover:text-slate-700', 'hover:border-slate-300');
                        btn.classList.add('text-indigo-600', 'border-indigo-500');
                    } else {
                        btn.classList.remove('text-indigo-600', 'border-indigo-500');
                        btn.classList.add('text-slate-500', 'border-transparent', 'hover:text-slate-700', 'hover:border-slate-300');
                    }
                });

                tabContents.forEach(content => {
                    content.classList.toggle('hidden', content.id !== 'tab-' + tab);
                });

                if (window.location.hash !== '#' + tab) {
                    history.replaceState(null, '', '#' + tab);
                }
            }

            const initialHash = window.location.hash ? window.location.hash.substring(1) : 'general';
            setActiveTab(validTabs.includes(initialHash) ? initialHash : 'general');

            tabButtons.forEach(button => {
                button.addEventListener('click', () => setActiveTab(button.dataset.tab));
            });

            const storeUrl   = "{{ route('bank-accounts.store') }}";
            const updateBase = "{{ url('/bank-accounts') }}/";

            function resetBankForm() {
                document.getElementById('bankAccountForm').action        = storeUrl;
                document.getElementById('bankMethodField').innerHTML     = '';
                document.getElementById('bankFormTitle').innerHTML       = '<i class="fas fa-plus-circle text-green-500 mr-2"></i> Add Bank Account';
                document.getElementById('ba_label').value                = '';
                document.getElementById('ba_bank_name').value            = '';
                document.getElementById('ba_account_name').value         = '';
                document.getElementById('ba_account_number').value       = '';
                document.getElementById('ba_branch').value               = '';
                document.getElementById('ba_swift_code').value           = '';
                document.getElementById('ba_is_active').checked          = true;
                document.getElementById('bankCancelBtn').style.display   = 'none';
                document.querySelectorAll('.bank-row').forEach(r => r.classList.remove('bg-indigo-50', 'border-indigo-200'));
            }

            document.querySelectorAll('.bank-row').forEach(row => {
                row.addEventListener('click', function () {
                    const d = this.dataset;
                    document.getElementById('bankAccountForm').action        = updateBase + d.id;
                    document.getElementById('bankMethodField').innerHTML     = '<input type="hidden" name="_method" value="PUT">';
                    document.getElementById('bankFormTitle').innerHTML       = '<i class="fas fa-edit text-orange-500 mr-2"></i> Edit Bank Account';
                    document.getElementById('ba_label').value                = d.label;
                    document.getElementById('ba_bank_name').value            = d.bank_name;
                    document.getElementById('ba_account_name').value         = d.account_name;
                    document.getElementById('ba_account_number').value       = d.account_number;
                    document.getElementById('ba_branch').value               = d.branch;
                    document.getElementById('ba_swift_code').value           = d.swift_code;
                    document.getElementById('ba_is_active').checked          = d.is_active === '1';
                    document.getElementById('bankCancelBtn').style.display   = 'inline-flex';
                    document.querySelectorAll('.bank-row').forEach(r => r.classList.remove('bg-indigo-50', 'border-indigo-200'));
                    this.classList.add('bg-indigo-50', 'border-indigo-200');
                    document.getElementById('bankAccountForm').scrollIntoView({ behavior: 'smooth', block: 'nearest' });
                });
            });

            document.querySelectorAll('.dropzone').forEach(dropzone => {
                const type = dropzone.id.replace('dropzone-', '');
                const input = document.getElementById('file-' + type);

                dropzone.addEventListener('click', () => input.click());

                dropzone.addEventListener('dragover', e => {
                    e.preventDefault();
                    dropzone.classList.add('bg-indigo-50', 'border-indigo-400');
                });

                dropzone.addEventListener('dragleave', e => {
                    e.preventDefault();
                    dropzone.classList.remove('bg-indigo-50', 'border-indigo-400');
                });

                dropzone.addEventListener('drop', e => {
                    e.preventDefault();
                    dropzone.classList.remove('bg-indigo-50', 'border-indigo-400');

                    if (e.dataTransfer.files.length) {
                        input.files = e.dataTransfer.files;
                        updateFileName(dropzone, e.dataTransfer.files[0].name);
                    }
                });

                input.addEventListener('change', () => {
                    if (input.files.length) {
                        updateFileName(dropzone, input.files[0].name);
                    }
                });
            });

            function updateFileName(dropzone, filename) {
                const msg = dropzone.querySelector('.dz-message');
                msg.innerHTML = '<i class="fas fa-file-excel text-4xl text-green-500 mb-3"></i><p class="text-green-600 font-bold mb-0 text-sm">' + filename + '</p>';
            }
        });
    </script>
    </x-slot>
</x-layouts::app>
