@extends('admin.layouts.app')

@section('title', admin_trans('languages'))
@section('page-title', admin_trans('languages'))

@section('content')

<div class="space-y-6">
    
    <!-- Search Bar + Add Button -->
    <div class="card">
        <div class="flex items-center gap-3">
            <form method="GET" action="{{ route('admin.languages.index') }}" id="search-form" class="flex-1">
                <x-search-input 
                    name="search"
                    :value="request('search')"
                    :placeholder="admin_trans('search')"
                    oninput="clearTimeout(window.searchTimeout); window.searchTimeout = setTimeout(() => this.form.submit(), 500)"
                    class="w-full"
                />
            </form>
            
            <x-button 
                variant="primary" 
                icon="plus"
                @click="$dispatch('open-modal', 'create-language-modal')"
            >
                {{ admin_trans('add_language') }}
            </x-button>
        </div>
    </div>

    <!-- Languages Table Card -->
    <div class="card">
        
        @if($languages->isEmpty())
            @if(request('search'))
                <!-- No Search Results -->
                <x-empty-state 
                    icon="search-x"
                    :title="admin_trans('no_results_found')"
                    :description="admin_trans('try_different_search')"
                >
                    <x-button 
                        variant="outline"
                        icon="x"
                        onclick="window.location.href='{{ route('admin.languages.index') }}'"
                    >
                        {{ admin_trans('clear') }}
                    </x-button>
                </x-empty-state>
            @else
                <!-- No Languages Yet -->
                <x-empty-state 
                    icon="languages"
                    :title="admin_trans('no_languages_yet')"
                    :description="admin_trans('start_by_adding_first_language')"
                >
                    <x-button 
                        variant="primary"
                        icon="plus"
                        @click="$dispatch('open-modal', 'create-language-modal')"
                    >
                        {{ admin_trans('add_language') }}
                    </x-button>
                </x-empty-state>
            @endif
        @else
<!-- Languages Table -->
<x-enhanced-table 
    :headers="[
        'order' => [
            'text' => admin_trans('order'),
            'align' => 'center',
            'width' => '100px'
        ],
        'code' => [
            'text' => admin_trans('code'),
            'align' => 'center',
            'width' => '80px'
        ],
        'name' => [
            'text' => admin_trans('name'),
            'align' => 'auto'
        ],
        'native_name' => [
            'text' => admin_trans('native_name'),
            'align' => 'auto'
        ],
        'status' => [
            'text' => admin_trans('status'),
            'align' => 'center',
            'width' => '100px'
        ],
        'default' => [
            'text' => admin_trans('default'),
            'align' => 'center',
            'width' => '120px'
        ],
        'actions' => [
            'text' => admin_trans('actions'),
            'align' => 'center',
            'width' => '100px'
        ]
    ]"
    :responsive="true"
>
    @foreach($languages as $language)
    <tr class="language-row hover:bg-primary-light transition-colors" data-id="{{ $language->id }}">
        
        <!-- Order (Drag Handle) -->
        <x-table-cell type="number">
            <div class="flex items-center justify-center gap-2">
                <button class="drag-handle cursor-move p-1 rounded hover:bg-primary-light">
                    <i data-lucide="grip-vertical" class="w-3 h-3 text-tertiary"></i>
                </button>
                <span class="text-sm font-medium text-tertiary">{{ $language->order }}</span>
            </div>
        </x-table-cell>
        
        <!-- Code -->
        <x-table-cell type="badge">
            <x-badge variant="secondary">{{ strtoupper($language->code) }}</x-badge>
        </x-table-cell>
        
        <!-- Name -->
        <x-table-cell type="text">
            <span class="text-sm font-medium text-primary">{{ $language->name }}</span>
        </x-table-cell>
        
        <!-- Native Name -->
        <x-table-cell type="text">
            <span class="text-sm text-secondary">{{ $language->native_name }}</span>
        </x-table-cell>
        
        <!-- Status with Toggle Only -->
        <x-table-cell type="actions">
            <form method="POST" action="{{ route('admin.languages.toggle-status', $language) }}">
                @csrf
                @method('PATCH')
                <x-toggle 
                    name="status_toggle_{{ $language->id }}"
                    :checked="$language->status === 'active'"
                    size="sm"
                    variant="success"
                    onchange="this.form.submit()"
                />
            </form>
        </x-table-cell>

        <!-- Is Default -->
        <x-table-cell type="badge">
            @if($language->is_default)
                <x-badge variant="primary">
                    {{ admin_trans('default') }}
                </x-badge>
            @else
                <form method="POST" action="{{ route('admin.languages.set-default', $language) }}">
                    @csrf
                    @method('PATCH')
                    <button type="submit" class="text-xs text-tertiary hover:text-primary transition-colors">
                        {{ admin_trans('set_default') }}
                    </button>
                </form>
            @endif
        </x-table-cell>
        
        <!-- Actions - Simple Icons -->
        <x-table-cell type="actions">
            <div class="flex items-center justify-center gap-2">
                <!-- Edit Button -->
                <button 
                    class="p-1.5 rounded-lg hover:bg-blue-50 text-blue-600 transition-colors"
                    onclick="editLanguage({{ $language->id }}, '{{ $language->code }}', '{{ $language->name }}', '{{ $language->native_name }}', {{ $language->order }}, '{{ $language->status }}', {{ $language->is_default ? 'true' : 'false' }})"
                    title="{{ admin_trans('edit') }}"
                >
                    <i data-lucide="edit-3" class="w-4 h-4"></i>
                </button>
                
                @if(!$language->is_default)
                    <!-- Delete Button -->
                    <button 
                        class="p-1.5 rounded-lg hover:bg-red-50 text-red-600 transition-colors"
                        onclick="confirmDelete({{ $language->id }}, '{{ $language->name }}')"
                        title="{{ admin_trans('delete') }}"
                    >
                        <i data-lucide="trash-2" class="w-4 h-4"></i>
                    </button>
                @endif
            </div>
        </x-table-cell>
    </tr>
    @endforeach
</x-enhanced-table>

            <!-- Footer Info & Pagination -->
            <div class="mt-6 flex flex-col sm:flex-row items-center justify-between gap-4 border-t pt-4" style="border-color: var(--color-border);">
                <div class="flex items-center gap-2 text-sm text-tertiary">
                    <i data-lucide="info" class="w-4 h-4"></i>
                    <span>{{ admin_trans('drag_rows_to_reorder') }}</span>
                </div>
                
                @if($languages->hasPages())
                    <x-pagination :paginator="$languages" />
                @endif
            </div>
        @endif

    </div>
</div>

<!-- Create Language Modal -->
<x-modal name="create-language-modal" maxWidth="md">
    <div class="p-6">
        <div class="flex items-center justify-between mb-6">
            <h3 class="text-xl font-bold text-primary">{{ admin_trans('add_language') }}</h3>
            <button @click="$dispatch('close-modal', 'create-language-modal')" 
                    class="p-2 rounded-lg hover:bg-primary-light transition-colors">
                <i data-lucide="x" class="w-5 h-5 text-tertiary"></i>
            </button>
        </div>

        <form method="POST" action="{{ route('admin.languages.store') }}" class="space-y-4">
            @csrf

            <x-input 
                :label="admin_trans('language_code')"
                name="code"
                placeholder="ar, en, fr..."
                :required="true"
                :hint="admin_trans('iso_639_code')"
            />

            <x-input 
                :label="admin_trans('name')"
                name="name"
                placeholder="Arabic, English..."
                :required="true"
            />

            <x-input 
                :label="admin_trans('native_name')"
                name="native_name"
                placeholder="العربية, English..."
                :required="true"
            />

            <x-input 
                :label="admin_trans('order')"
                name="order"
                type="number"
                value="0"
                :hint="admin_trans('display_order')"
            />

            <x-select 
                :label="admin_trans('status')"
                name="status"
                :required="true"
            >
                <option value="draft">{{ admin_trans('draft') }}</option>
                <option value="active" selected>{{ admin_trans('active') }}</option>
            </x-select>

            <div class="flex items-center gap-3">
                <input 
                    type="checkbox" 
                    name="is_default" 
                    id="create_is_default"
                    value="1"
                    class="checkbox"
                >
                <label for="create_is_default" class="text-sm font-medium text-primary cursor-pointer">
                    {{ admin_trans('set_as_default') }}
                </label>
            </div>

            <div class="flex gap-3 justify-end pt-4 border-t" style="border-color: var(--color-border);">
                <x-button 
                    variant="outline" 
                    type="button"
                    @click="$dispatch('close-modal', 'create-language-modal')"
                >
                    {{ admin_trans('cancel') }}
                </x-button>
                <x-button variant="primary" type="submit" icon="check">
                    {{ admin_trans('create') }}
                </x-button>
            </div>
        </form>
    </div>
</x-modal>

<!-- Edit Language Modal -->
<x-modal name="edit-language-modal" maxWidth="md">
    <div class="p-6">
        <div class="flex items-center justify-between mb-6">
            <h3 class="text-xl font-bold text-primary">{{ admin_trans('edit_language') }}</h3>
            <button @click="$dispatch('close-modal', 'edit-language-modal')" 
                    class="p-2 rounded-lg hover:bg-primary-light transition-colors">
                <i data-lucide="x" class="w-5 h-5 text-tertiary"></i>
            </button>
        </div>

        <form id="edit-language-form" method="POST" class="space-y-4">
            @csrf
            @method('PUT')

            <x-input 
                :label="admin_trans('language_code')"
                name="code"
                id="edit_code"
                :required="true"
            />

            <x-input 
                :label="admin_trans('name')"
                name="name"
                id="edit_name"
                :required="true"
            />

            <x-input 
                :label="admin_trans('native_name')"
                name="native_name"
                id="edit_native_name"
                :required="true"
            />

            <x-input 
                :label="admin_trans('order')"
                name="order"
                type="number"
                id="edit_order"
            />

            <x-select 
                :label="admin_trans('status')"
                name="status"
                id="edit_status"
                :required="true"
            >
                <option value="draft">{{ admin_trans('draft') }}</option>
                <option value="active">{{ admin_trans('active') }}</option>
            </x-select>

            <div class="flex items-center gap-3">
                <input 
                    type="checkbox" 
                    name="is_default" 
                    id="edit_is_default"
                    value="1"
                    class="checkbox"
                >
                <label for="edit_is_default" class="text-sm font-medium text-primary cursor-pointer">
                    {{ admin_trans('set_as_default') }}
                </label>
            </div>

            <div class="flex gap-3 justify-end pt-4 border-t" style="border-color: var(--color-border);">
                <x-button 
                    variant="outline" 
                    type="button"
                    @click="$dispatch('close-modal', 'edit-language-modal')"
                >
                    {{ admin_trans('cancel') }}
                </x-button>
                <x-button variant="primary" type="submit" icon="check">
                    {{ admin_trans('update') }}
                </x-button>
            </div>
        </form>
    </div>
</x-modal>

<!-- Delete Confirmation Modal -->
<form id="delete-language-form" method="POST">
    @csrf
    @method('DELETE')
</form>

<x-confirm-modal 
    name="delete-language-modal"
    :title="admin_trans('confirm_delete')"
    message=""
    :confirmText="admin_trans('yes_delete')"
    :cancelText="admin_trans('cancel')"
    confirmVariant="danger"
    icon="trash-2"
    iconColor="danger"
    x-data="{ message: '' }"
/>

@endsection

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.0/Sortable.min.js"></script>
<script>
// Edit Language Function
function editLanguage(id, code, name, nativeName, order, status, isDefault) {
    const form = document.getElementById('edit-language-form');
    form.action = `/admin/languages/${id}`;
    
    document.getElementById('edit_code').value = code;
    document.getElementById('edit_name').value = name;
    document.getElementById('edit_native_name').value = nativeName;
    document.getElementById('edit_order').value = order;
    document.getElementById('edit_status').value = status;
    document.getElementById('edit_is_default').checked = isDefault;
    
    window.dispatchEvent(new CustomEvent('open-modal', { detail: 'edit-language-modal' }));
}

// Confirm Delete Function
function confirmDelete(id, name) {
    const form = document.getElementById('delete-language-form');
    form.action = `/admin/languages/${id}`;
    
    // Submit form on confirm
    window.addEventListener('confirm-action', function handler(e) {
        if (e.detail === 'delete-language-modal') {
            form.submit();
            window.removeEventListener('confirm-action', handler);
        }
    });
    
    window.dispatchEvent(new CustomEvent('open-modal', { detail: 'delete-language-modal' }));
}

// Sortable.js for Drag & Drop
document.addEventListener('DOMContentLoaded', function() {
    const tbody = document.querySelector('.language-row')?.parentElement;
    
    if (tbody) {
        new Sortable(tbody, {
            handle: '.drag-handle',
            animation: 150,
            ghostClass: 'opacity-50',
            onEnd: updateOrder
        });
    }
});

// Update Order via AJAX
function updateOrder() {
    const rows = document.querySelectorAll('.language-row');
    const orders = Array.from(rows).map(row => row.dataset.id);
    
    fetch('/admin/languages/update-order', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
        },
        body: JSON.stringify({ orders })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            toast.success('{{ admin_trans('order_updated_successfully') }}');
            setTimeout(() => location.reload(), 1000);
        }
    })
    .catch(() => {
        toast.error('{{ admin_trans('error_updating_order') }}');
    });
}
</script>
@endpush