<script setup lang="ts">
import ConfirmationModal from '@/Components/Common/ConfirmationModal.vue';
import AdminLayout from '@/Layouts/AdminLayout.vue';
import Button from '@/Shared/Button.vue';
import Modal from '@/Shared/Modal.vue';
import { Head, router, useForm } from '@inertiajs/vue3';
import { Plus, Search, Trash2, X } from 'lucide-vue-next';
import { computed, ref } from 'vue';

const props = defineProps<{
    employees: Array<{
        id: number;
        name: string;
        email: string;
        department: string;
        designation: string;
        assignment: null | {
            id: number;
            tax_id: number;
            tax_name: string;
            tax_type: string;
            fixed_amount: string | null;
            fixed_amount_type: 'percentage' | 'fixed' | null;
            effective_from: string;
        };
    }>;
    taxes: Array<{
        id: number;
        name: string;
        type: 'fixed' | 'slab';
        fixed_amount: string | null;
        fixed_amount_type: 'percentage' | 'fixed' | null;
    }>;
}>();

const searchQuery = ref('');

const filteredEmployees = computed(() => {
    const query = searchQuery.value.toLowerCase();
    if (!query) return props.employees;
    return props.employees.filter(
        (emp) => emp.name.toLowerCase().includes(query) || emp.email.toLowerCase().includes(query) || emp.department.toLowerCase().includes(query),
    );
});

// Bulk Assign Modal State
const isBulkModalOpen = ref(false);
const selectedEmployeeIds = ref<number[]>([]);

const toggleAll = (event: any) => {
    if (event.target.checked) {
        selectedEmployeeIds.value = filteredEmployees.value.map((e) => e.id);
    } else {
        selectedEmployeeIds.value = [];
    }
};

const assignForm = useForm({
    employee_ids: [] as number[],
    tax_id: '',
    fixed_amount: '',
    effective_from: new Date().toISOString().split('T')[0],
});

const watchTaxChange = (newTaxId: string) => {
    if (!newTaxId) return;
    const tax = props.taxes.find((t) => t.id === Number(newTaxId));
    if (tax && tax.type === 'fixed' && !assignForm.fixed_amount) {
        assignForm.fixed_amount = tax.fixed_amount ?? '';
    }
};

import { watch } from 'vue';
watch(() => assignForm.tax_id, watchTaxChange);

const selectedTaxType = computed(() => {
    if (!assignForm.tax_id) return null;
    const tax = props.taxes.find((t) => t.id === Number(assignForm.tax_id));
    return tax ? tax.type : null;
});

const submitAssignment = () => {
    assignForm.employee_ids = selectedEmployeeIds.value;
    // Using manual URL as route() is experiencing resolution issues
    assignForm.post('/admin/employee-taxes/bulk', {
        preserveScroll: true,
        onSuccess: () => {
            isBulkModalOpen.value = false;
            selectedEmployeeIds.value = [];
            assignForm.reset();
        },
    });
};

const confirmState = ref({
    show: false,
    id: null as number | null,
});

const removeAssignment = (assignmentId: number) => {
    confirmState.value = { show: true, id: assignmentId };
};

const executeRemove = () => {
    if (confirmState.value.id) {
        router.delete(`/admin/employee-taxes/${confirmState.value.id}`, {
            preserveScroll: true,
            onFinish: () => (confirmState.value.show = false),
        });
    }
};
</script>

<template>
    <Head title="Tax Assignments" />

    <AdminLayout>
        <div class="space-y-6">
            <div class="flex flex-col justify-between gap-4 sm:flex-row sm:items-center">
                <div>
                    <h2 class="text-2xl font-semibold tracking-tight text-slate-800 dark:text-white">Employee Tax Assignments</h2>
                    <p class="text-sm text-slate-500">Assign tax policies to employees individually or in bulk.</p>
                </div>

                <Button :disabled="selectedEmployeeIds.length === 0" @click="isBulkModalOpen = true" class="shadow-lg shadow-indigo-500/20">
                    <Plus class="mr-2 h-4 w-4" />
                    Assign Tax ({{ selectedEmployeeIds.length }})
                </Button>
            </div>

            <!-- Filters -->
            <div class="flex max-w-sm items-center gap-2">
                <div class="group relative w-full">
                    <Search class="absolute top-3 left-3 h-4 w-4 text-slate-400 transition-colors group-focus-within:text-indigo-500" />
                    <input
                        v-model="searchQuery"
                        placeholder="Search employees..."
                        class="h-10 w-full rounded-xl border border-slate-200 bg-white pr-4 pl-10 text-sm transition-all outline-none focus:border-indigo-500 focus:ring-2 focus:ring-indigo-500/20 dark:border-slate-700 dark:bg-slate-900"
                    />
                </div>
            </div>

            <!-- Table -->
            <div class="overflow-hidden rounded-xl border border-slate-200 bg-white shadow-sm dark:border-slate-700 dark:bg-slate-900">
                <table class="w-full">
                    <thead>
                        <tr class="border-b border-slate-100 bg-slate-50/50 dark:border-slate-800 dark:bg-slate-800/50">
                            <th class="w-12 px-6 py-4 text-center">
                                <input
                                    type="checkbox"
                                    class="h-4 w-4 rounded border-slate-300 text-indigo-600 focus:ring-indigo-500"
                                    :checked="selectedEmployeeIds.length === filteredEmployees.length && filteredEmployees.length > 0"
                                    @change="toggleAll"
                                />
                            </th>
                            <th class="px-6 py-4 text-left text-xs font-bold tracking-wider text-slate-500 uppercase">Employee</th>
                            <th class="px-6 py-4 text-left text-xs font-bold tracking-wider text-slate-500 uppercase">Department</th>
                            <th class="px-6 py-4 text-left text-xs font-bold tracking-wider text-slate-500 uppercase">Current Tax</th>
                            <th class="px-6 py-4 text-left text-xs font-bold tracking-wider text-slate-500 uppercase">Details</th>
                            <th class="px-6 py-4 text-right text-xs font-bold tracking-wider text-slate-500 uppercase">Actions</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-100 text-sm dark:divide-slate-800">
                        <tr
                            v-for="employee in filteredEmployees"
                            :key="employee.id"
                            class="group transition-colors hover:bg-slate-50/50 dark:hover:bg-slate-800/50"
                            :class="{ 'bg-indigo-50/30 dark:bg-indigo-900/10': selectedEmployeeIds.includes(employee.id) }"
                        >
                            <td class="px-6 py-4 text-center">
                                <input
                                    type="checkbox"
                                    class="h-4 w-4 rounded border-slate-300 text-indigo-600 focus:ring-indigo-500"
                                    :value="employee.id"
                                    v-model="selectedEmployeeIds"
                                />
                            </td>
                            <td class="px-6 py-4">
                                <div class="flex items-center gap-3 text-sm">
                                    <div
                                        class="flex h-9 w-9 items-center justify-center rounded-full bg-indigo-100 text-xs font-bold text-indigo-700 uppercase dark:bg-indigo-900/50 dark:text-indigo-300"
                                    >
                                        {{ employee.name.substring(0, 2) }}
                                    </div>
                                    <div>
                                        <p class="font-bold text-slate-700 dark:text-slate-200">{{ employee.name }}</p>
                                        <p class="text-xs text-slate-400">{{ employee.email }}</p>
                                    </div>
                                </div>
                            </td>
                            <td class="px-6 py-4">
                                <p class="font-medium text-slate-700 dark:text-slate-200">{{ employee.department }}</p>
                                <p class="text-xs text-slate-400">{{ employee.designation }}</p>
                            </td>
                            <td class="px-6 py-4">
                                <div v-if="employee.assignment">
                                    <p class="font-bold text-slate-700 dark:text-slate-200">{{ employee.assignment.tax_name }}</p>
                                    <span
                                        class="mt-1 inline-block rounded-full bg-indigo-50 px-2 py-0.5 text-[10px] font-bold tracking-wider text-indigo-600 uppercase"
                                    >
                                        {{ employee.assignment.tax_type }}
                                    </span>
                                </div>
                                <span v-else class="text-xs text-slate-400 italic">None Assigned</span>
                            </td>
                            <td class="px-6 py-4">
                                <div v-if="employee.assignment" class="space-y-0.5 text-xs">
                                    <p v-if="employee.assignment.tax_type === 'fixed'" class="font-medium text-slate-600 dark:text-slate-400">
                                        {{
                                            employee.assignment.fixed_amount_type === 'percentage'
                                                ? employee.assignment.fixed_amount + '%'
                                                : Number(employee.assignment.fixed_amount).toLocaleString() + ' /mo'
                                        }}
                                    </p>
                                    <p class="text-slate-400">Since {{ employee.assignment.effective_from }}</p>
                                </div>
                            </td>
                            <td class="px-6 py-4 text-right leading-none">
                                <div class="flex items-center justify-end gap-1 opacity-0 transition-opacity group-hover:opacity-100">
                                    <button
                                        v-if="employee.assignment"
                                        type="button"
                                        class="flex h-8 w-8 items-center justify-center rounded-lg text-rose-500 transition-colors outline-none hover:bg-rose-50 hover:text-rose-600"
                                        @click="removeAssignment(employee.assignment.id)"
                                        title="Deactivate Assignment"
                                    >
                                        <Trash2 class="h-4 w-4" />
                                    </button>
                                </div>
                            </td>
                        </tr>
                        <tr v-if="filteredEmployees.length === 0">
                            <td colspan="6" class="bg-white px-6 py-12 text-center text-slate-400 italic dark:bg-slate-900">No employees found.</td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Bulk Assign Modal -->
        <Modal :show="isBulkModalOpen" @close="isBulkModalOpen = false" max-width="md">
            <template #default>
                <div class="space-y-4">
                    <div class="mb-4 flex items-center justify-between border-b border-slate-100 pb-4">
                        <h3 class="text-lg font-bold text-slate-800">Assign Tax Policy</h3>
                        <button @click="isBulkModalOpen = false" class="text-slate-400 hover:text-slate-600">
                            <X class="h-5 w-5" />
                        </button>
                    </div>

                    <p class="mb-6 text-sm text-slate-500">
                        Applying a new tax policy will deactivate any existing active assignment for these
                        <span class="font-bold text-indigo-600">{{ selectedEmployeeIds.length }}</span> employees.
                    </p>

                    <form @submit.prevent="submitAssignment" class="space-y-5">
                        <div class="space-y-2">
                            <label class="text-sm font-bold text-slate-700">Tax Policy</label>
                            <select
                                v-model="assignForm.tax_id"
                                class="h-11 w-full rounded-xl border border-slate-200 bg-white px-3 text-sm outline-none focus:border-indigo-500 focus:ring-2 focus:ring-indigo-500/20"
                            >
                                <option value="" disabled>Select a tax policy</option>
                                <option v-for="tax in taxes" :key="tax.id" :value="tax.id">
                                    {{ tax.name }} ({{ tax.type === 'fixed' ? 'Fixed Amount' : 'Progressive Slab' }})
                                </option>
                            </select>
                            <p v-if="assignForm.errors.tax_id" class="text-xs text-rose-500">{{ assignForm.errors.tax_id }}</p>
                        </div>

                        <div v-if="selectedTaxType === 'fixed'" class="animate-in slide-in-from-top-2 space-y-2 duration-200">
                            <label class="text-sm font-bold text-slate-700">Fixed Amount per Month</label>
                            <input
                                type="number"
                                v-model="assignForm.fixed_amount"
                                min="0"
                                step="0.01"
                                placeholder="0.00"
                                class="h-11 w-full rounded-xl border border-slate-200 bg-white px-3 text-sm outline-none focus:border-indigo-500 focus:ring-2 focus:ring-indigo-500/20"
                            />
                            <p v-if="assignForm.errors.fixed_amount" class="text-xs text-rose-500">{{ assignForm.errors.fixed_amount }}</p>
                        </div>

                        <div class="space-y-2">
                            <label class="text-sm font-bold text-slate-700">Effective From Date</label>
                            <input
                                type="date"
                                v-model="assignForm.effective_from"
                                class="h-11 w-full rounded-xl border border-slate-200 bg-white px-3 text-sm outline-none focus:border-indigo-500 focus:ring-2 focus:ring-indigo-500/20"
                            />
                            <p v-if="assignForm.errors.effective_from" class="text-xs text-rose-500">{{ assignForm.errors.effective_from }}</p>
                        </div>
                    </form>
                </div>
            </template>
            <template #footer>
                <div class="flex w-full items-center gap-3 sm:w-auto">
                    <button
                        type="button"
                        @click="isBulkModalOpen = false"
                        class="rounded-xl border border-slate-200 px-4 py-2 text-sm font-medium text-slate-600 transition-colors hover:bg-slate-50"
                    >
                        Cancel
                    </button>
                    <Button
                        @click="submitAssignment"
                        class="w-full shadow-lg shadow-indigo-500/20 sm:w-auto"
                        :processing="assignForm.processing"
                        :disabled="!assignForm.tax_id"
                    >
                        Confirm Assignment
                    </Button>
                </div>
            </template>
        </Modal>

        <ConfirmationModal
            :show="confirmState.show"
            title="Remove Assignment"
            message="Are you sure you want to deactivate this tax assignment for the employee?"
            confirm-text="Remove"
            type="danger"
            @close="confirmState.show = false"
            @confirm="executeRemove"
        />
    </AdminLayout>
</template>
