<script setup lang="ts">
import { Head, useForm, router } from '@inertiajs/vue3';
import AdminLayout from '@/Layouts/AdminLayout.vue';
import { 
    Search, Plus, Filter, MoreVertical, 
    Pencil, Trash2, Building, AlertCircle, PlusCircle
} from 'lucide-vue-next';
import { ref, watch } from 'vue';
import Modal from '@/Components/Common/Modal.vue';
import ConfirmationModal from '@/Components/Common/ConfirmationModal.vue';
import admin from '@/routes/admin';
import { debounce } from 'lodash';

const props = defineProps<{
    departments: {
        data: any[];
        links: any[];
        meta: any;
    };
    filters: {
        search?: string;
    };
}>();

const search = ref(props.filters.search || '');
const showCreateModal = ref(false);
const showEditModal = ref(false);
const showDeleteModal = ref(false);
const editingDepartment = ref<any>(null);
const deletingDepartment = ref<any>(null);
const processingDelete = ref(false);

const form = useForm({
    name: '',
    description: '',
    status: true as boolean | number,
});

watch(search, debounce((value: string) => {
    router.get(admin.departments.index.url(), { search: value }, {
        preserveState: true,
        preserveScroll: true,
        replace: true,
    });
}, 300));

const openCreateModal = () => {
    form.reset();
    showCreateModal.value = true;
};

const createDepartment = () => {
    form.post(admin.departments.store.url(), {
        preserveScroll: true,
        onSuccess: () => {
            showCreateModal.value = false;
            form.reset();
        },
    });
};

const openEditModal = (department: any) => {
    editingDepartment.value = department;
    form.name = department.name;
    form.description = department.description;
    form.status = !!department.status;
    showEditModal.value = true;
};

const updateDepartment = () => {
    if (!editingDepartment.value) return;
    
    form.put(admin.departments.update.url(editingDepartment.value.id), {
        preserveScroll: true,
        onSuccess: () => {
            showEditModal.value = false;
            form.reset();
            editingDepartment.value = null;
        },
    });
};

const openDeleteModal = (department: any) => {
    deletingDepartment.value = department;
    showDeleteModal.value = true;
};

const handleDelete = () => {
    if (!deletingDepartment.value) return;
    
    processingDelete.value = true;
    router.delete(admin.departments.destroy.url(deletingDepartment.value.id), {
        preserveScroll: true,
        onSuccess: () => {
            showDeleteModal.value = false;
            deletingDepartment.value = null;
        },
        onFinish: () => {
            processingDelete.value = false;
        }
    });
};
</script>

<template>
    <Head title="Departments" />

    <AdminLayout>
        <div class="space-y-6 animate-fade-in">
            <!-- Header -->
            <div class="flex flex-col md:flex-row justify-between items-start md:items-center gap-6 text-start">
                <div class="text-start">
                    <h2 class="text-2xl font-extrabold tracking-tight text-slate-900 dark:text-white">{{ __('Departments') }}</h2>
                    <p class="text-slate-500 dark:text-slate-400 text-sm mt-1">{{ __('Manage company departments and their structures.') }}</p>
                </div>
                <button @click="openCreateModal" class="bg-brand-600 hover:bg-brand-700 text-white px-6 py-3 rounded-2xl font-bold text-sm shadow-xl shadow-brand-600/20 flex items-center transition-all active:scale-95">
                    <PlusCircle :size="18" class="me-2" /> {{ __('New Department') }}
                </button>
            </div>

            <!-- Filters -->
            <div class="bg-white dark:bg-slate-800 rounded-[2rem] border border-slate-200/60 dark:border-slate-700 shadow-sm overflow-hidden p-4">
                <div class="relative w-full sm:w-64">
                    <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                        <Search :size="16" class="text-slate-400" />
                    </div>
                    <input v-model="search" type="text" :placeholder="__('Search departments...')" class="w-full pl-10 pr-4 py-2 bg-slate-50 dark:bg-slate-900/50 border border-slate-200 dark:border-slate-700/60 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-brand-500/20 text-slate-700 dark:text-slate-200 placeholder:text-slate-400 dark:placeholder:text-slate-500">
                </div>
            </div>

            <!-- Content -->
            <div class="bg-white dark:bg-slate-800 rounded-[2rem] border border-slate-200/60 dark:border-slate-700 shadow-sm overflow-hidden">
                <div class="overflow-x-auto">
                    <table class="w-full text-start border-collapse">
                        <thead>
                            <tr class="bg-slate-50/50 dark:bg-slate-800/20 border-b border-slate-100 dark:border-slate-700/50">
                                <th class="px-6 py-4 text-[10px] font-bold text-slate-400 uppercase tracking-widest text-start">{{ __('Department') }}</th>
                                <th class="px-6 py-4 text-[10px] font-bold text-slate-400 uppercase tracking-widest text-start">{{ __('Description') }}</th>
                                <th class="px-6 py-4 text-[10px] font-bold text-slate-400 uppercase tracking-widest text-start">{{ __('Status') }}</th>
                                <th class="px-6 py-4 text-[10px] font-bold text-slate-400 uppercase tracking-widest text-end">{{ __('Action') }}</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-slate-50 dark:divide-slate-800/50 text-start">
                            <tr v-for="department in departments.data" :key="department.id" class="hover:bg-slate-50/80 dark:hover:bg-slate-800/40 transition-all duration-200 group">
                                <td class="px-6 py-4">
                                    <div class="flex items-center gap-3">
                                        <div class="w-10 h-10 rounded-xl bg-primary-50 dark:bg-primary-900/20 flex items-center justify-center text-primary-600">
                                            <Building :size="18" />
                                        </div>
                                        <span class="font-bold text-slate-900 dark:text-white">{{ department.name }}</span>
                                    </div>
                                </td>
                                <td class="px-6 py-4 text-sm text-slate-500 dark:text-slate-400">
                                    {{ department.description || '-' }}
                                </td>
                                <td class="px-6 py-4 text-sm">
                                    <span v-if="department.status" class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-bold bg-green-50 dark:bg-green-900/20 text-green-700 border border-green-100 dark:border-green-800/30">
                                        {{ __('Active') }}
                                    </span>
                                    <span v-else class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-bold bg-slate-50 dark:bg-slate-800 text-slate-500 border border-slate-100 dark:border-slate-700">
                                        {{ __('Inactive') }}
                                    </span>
                                </td>
                                <td class="px-6 py-4 text-end">
                                    <div class="flex justify-end items-center gap-2">
                                        <button @click="openEditModal(department)" class="w-8 h-8 rounded-xl bg-slate-50 dark:bg-slate-800 text-slate-500 hover:text-brand-600 hover:bg-brand-50 dark:hover:bg-brand-900/20 transition-all flex items-center justify-center">
                                            <Pencil :size="14" />
                                        </button>
                                        <button @click="openDeleteModal(department)" class="w-8 h-8 rounded-xl bg-slate-50 dark:bg-slate-800 text-slate-500 hover:text-rose-500 hover:bg-rose-50 dark:hover:bg-rose-900/20 transition-all flex items-center justify-center">
                                            <Trash2 :size="14" />
                                        </button>
                                    </div>
                                </td>
                            </tr>
                            <tr v-if="departments.data.length === 0">
                                <td colspan="4" class="px-6 py-12 text-center text-slate-400">
                                    <div class="flex flex-col items-center justify-center">
                                        <div class="w-12 h-12 rounded-full bg-slate-50 dark:bg-slate-800 flex items-center justify-center mb-3">
                                            <Building :size="24" class="text-slate-300 dark:text-slate-600" />
                                        </div>
                                        <p class="font-medium text-slate-900 dark:text-white">{{ __('No departments found') }}</p>
                                        <p class="text-xs mt-1">{{ __('Get started by creating a new department.') }}</p>
                                    </div>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
                
                <!-- Pagination -->
                <div v-if="departments.links.length > 3" class="p-6 border-t border-slate-100 dark:border-slate-700 flex justify-end">
                    <div class="flex space-x-1">
                        <Link v-for="(link, key) in departments.links" :key="key" :href="link.url || '#'" v-html="link.label" class="px-3 py-1 text-xs rounded-lg transition-colors border border-transparent" :class="link.active ? 'bg-brand-600 text-white' : 'text-slate-500 hover:bg-slate-100 dark:text-slate-400 dark:hover:bg-slate-700'" :preserve-state="true" />
                    </div>
                </div>
            </div>
        </div>

        <!-- Create/Edit Modal Content -->
        <Modal :show="showCreateModal || showEditModal" :title="showCreateModal ? __('Create New Department') : __('Edit Department')" @close="showCreateModal = false; showEditModal = false">
            <form @submit.prevent="showCreateModal ? createDepartment() : updateDepartment()" class="space-y-6">
                <div class="space-y-1">
                    <label class="text-xs font-bold text-slate-500 uppercase tracking-wider">{{ __('Name') }}</label>
                    <input v-model="form.name" type="text" class="w-full px-4 py-2 text-sm border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800 rounded-xl focus:ring-brand-500 focus:border-brand-500 dark:text-white" :placeholder="__('e.g. Engineering')">
                    <div v-if="form.errors.name" class="text-xs text-red-500">{{ form.errors.name }}</div>
                </div>

                <div class="space-y-1">
                    <label class="text-xs font-bold text-slate-500 uppercase tracking-wider">{{ __('Description') }}</label>
                    <textarea v-model="form.description" class="w-full px-4 py-2 text-sm border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800 rounded-xl focus:ring-brand-500 focus:border-brand-500 dark:text-white" rows="3" :placeholder="__('Write a brief description...')"></textarea>
                    <div v-if="form.errors.description" class="text-xs text-red-500">{{ form.errors.description }}</div>
                </div>

                <div class="flex items-center gap-3">
                    <label class="text-xs font-bold text-slate-500 uppercase tracking-wider">{{ __('Status') }}</label>
                    <label class="relative inline-flex items-center cursor-pointer">
                        <input type="checkbox" v-model="form.status" class="sr-only peer">
                        <div class="w-9 h-5 bg-slate-200 peer-focus:outline-none peer-focus:ring-2 peer-focus:ring-brand-300 dark:peer-focus:ring-brand-800 rounded-full peer dark:bg-slate-700 peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-4 after:w-4 after:transition-all dark:border-gray-600 peer-checked:bg-brand-600"></div>
                    </label>
                    <span class="text-xs text-slate-500">{{ form.status ? __('Active') : __('Inactive') }}</span>
                </div>

                <div class="flex justify-end gap-3 pt-4 border-t border-slate-100 dark:border-slate-700">
                    <button type="button" @click="showCreateModal = false; showEditModal = false" class="px-6 py-2 rounded-xl text-sm font-bold text-slate-500 hover:bg-slate-50 dark:hover:bg-slate-800 transition-all">
                        {{ __('Cancel') }}
                    </button>
                    <button type="submit" :disabled="form.processing" class="bg-brand-600 hover:bg-brand-700 text-white px-6 py-2 rounded-xl font-bold text-sm shadow-lg shadow-brand-600/20 transition-all active:scale-95 disabled:opacity-50">
                        {{ showCreateModal ? __('Create Department') : __('Update Department') }}
                    </button>
                </div>
            </form>
        </Modal>

        <ConfirmationModal 
            :show="showDeleteModal" 
            :title="__('Delete Department?')"
            :message="__('Are you sure you want to delete this department? This action cannot be undone.')"
            :confirmText="__('Yes, Delete Department')"
            :cancelText="__('No, Cancel')"
            type="danger"
            :processing="processingDelete"
            @close="showDeleteModal = false"
            @confirm="handleDelete"
        />
    </AdminLayout>
</template>
