<script setup lang="ts">
import ConfirmationModal from '@/Components/Common/ConfirmationModal.vue';
import AdminLayout from '@/Layouts/AdminLayout.vue';
import { Head, Link, router, useForm } from '@inertiajs/vue3';
import { CheckCircle2, Pencil, Plus, Trash2, XCircle } from 'lucide-vue-next';
import { ref } from 'vue';

const props = defineProps<{
    taxes: Array<{
        id: number;
        name: string;
        type: 'fixed' | 'slab';
        status: 'active' | 'inactive';
        created_at: string;
        fixed_amount: string | null;
        fixed_amount_type: 'percentage' | 'fixed' | null;
    }>;
    taxSetup: {
        is_enabled: boolean;
        active_tax_id: number | null;
    };
}>();

// ─── Tax Setup Form ──────────────────────────────────────────────────────────
const setupForm = useForm({
    is_enabled: props.taxSetup.is_enabled,
    active_tax_id: props.taxSetup.active_tax_id ? String(props.taxSetup.active_tax_id) : '',
});

const saveSetup = () => {
    setupForm.post('/admin/tax-setup', {
        preserveScroll: true,
    });
};

const activePolicies = props.taxes.filter((t) => t.status === 'active');

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

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

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

<template>
    <Head title="Income Taxes" />

    <AdminLayout>
        <div class="space-y-6">
            <!-- Page Header -->
            <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">Income Tax Setup</h2>
                    <p class="text-sm text-slate-500">Configure the global tax policy applied to all employee payrolls.</p>
                </div>
                <Link
                    href="/admin/taxes/create"
                    class="flex items-center rounded-xl bg-indigo-600 px-4 py-2 text-sm font-bold text-white shadow-sm shadow-indigo-100 transition-all hover:bg-indigo-700 active:scale-95 dark:shadow-none"
                >
                    <Plus class="mr-2 h-4 w-4" />
                    New Tax Policy
                </Link>
            </div>

            <!-- Global Tax Setup Card -->
            <div class="rounded-2xl border border-slate-200 bg-white p-6 shadow-sm dark:border-slate-700 dark:bg-slate-900">
                <div class="mb-5 flex items-start justify-between">
                    <div>
                        <h3 class="font-bold text-slate-800 dark:text-white">Global Tax Configuration</h3>
                        <p class="mt-0.5 text-sm text-slate-500">
                            Enable tax and select a policy. This applies to <strong>all employees</strong> during payroll generation. Changing this
                            will <strong>not</strong> affect previously approved payrolls.
                        </p>
                    </div>
                    <div class="flex shrink-0 items-center gap-2">
                        <span
                            class="inline-flex items-center gap-1 rounded-full px-2.5 py-0.5 text-xs font-bold"
                            :class="
                                taxSetup.is_enabled
                                    ? 'bg-emerald-50 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400'
                                    : 'bg-slate-100 text-slate-500 dark:bg-slate-800 dark:text-slate-400'
                            "
                        >
                            <CheckCircle2 v-if="taxSetup.is_enabled" class="h-3 w-3" />
                            <XCircle v-else class="h-3 w-3" />
                            {{ taxSetup.is_enabled ? 'Tax Enabled' : 'Tax Disabled' }}
                        </span>
                    </div>
                </div>

                <form @submit.prevent="saveSetup" class="space-y-4">
                    <!-- Toggle Row -->
                    <div class="flex items-center gap-4 rounded-xl bg-slate-50 px-4 py-3 dark:bg-slate-800">
                        <div class="flex-1">
                            <p class="text-sm font-semibold text-slate-700 dark:text-slate-200">Enable Income Tax Deduction</p>
                            <p class="text-xs text-slate-400">When enabled, tax will be calculated and deducted during payroll generation.</p>
                        </div>
                        <label class="relative inline-flex cursor-pointer items-center">
                            <input type="checkbox" v-model="setupForm.is_enabled" class="peer sr-only" />
                            <div
                                class="peer h-6 w-11 rounded-full bg-slate-200 peer-checked:bg-indigo-600 after:absolute after:top-[2px] after:left-[2px] after:h-5 after:w-5 after:rounded-full after:bg-white after:transition-all after:content-[''] peer-checked:after:translate-x-full dark:bg-slate-700"
                            ></div>
                        </label>
                    </div>

                    <!-- Active Policy Selector -->
                    <div v-if="setupForm.is_enabled">
                        <label class="mb-1.5 block text-sm font-semibold text-slate-700 dark:text-slate-200"> Active Tax Policy </label>
                        <select
                            v-model="setupForm.active_tax_id"
                            class="w-full rounded-xl border border-slate-200 bg-white px-3 py-2.5 text-sm text-slate-700 shadow-sm focus:border-indigo-400 focus:ring-2 focus:ring-indigo-200 focus:outline-none dark:border-slate-700 dark:bg-slate-800 dark:text-white"
                        >
                            <option value="">— Select a policy —</option>
                            <option v-for="tax in activePolicies" :key="tax.id" :value="String(tax.id)">
                                {{ tax.name }} ({{ tax.type === 'slab' ? 'Slab-based' : 'Fixed Amount' }})
                            </option>
                        </select>
                        <p v-if="activePolicies.length === 0" class="mt-1.5 text-xs text-amber-600 dark:text-amber-400">
                            No active policies found. Please create and set a policy to active status first.
                        </p>
                        <p v-if="setupForm.errors.active_tax_id" class="mt-1.5 text-xs text-rose-500">
                            {{ setupForm.errors.active_tax_id }}
                        </p>
                    </div>

                    <div class="flex justify-end">
                        <button
                            type="submit"
                            :disabled="setupForm.processing"
                            class="rounded-xl bg-indigo-600 px-5 py-2 text-sm font-bold text-white shadow-sm transition-all hover:bg-indigo-700 active:scale-95 disabled:opacity-50"
                        >
                            {{ setupForm.processing ? 'Saving…' : 'Save Tax Setup' }}
                        </button>
                    </div>
                </form>
            </div>

            <!-- Tax Policies List -->
            <div>
                <h3 class="mb-3 text-sm font-bold tracking-wider text-slate-500 uppercase">Tax Policies</h3>
                <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="px-6 py-4 text-left text-xs font-bold tracking-wider text-slate-500 uppercase">Tax Name</th>
                                <th class="px-6 py-4 text-left text-xs font-bold tracking-wider text-slate-500 uppercase">Type</th>
                                <th class="px-6 py-4 text-left text-xs font-bold tracking-wider text-slate-500 uppercase">Status</th>
                                <th class="px-6 py-4 text-left text-xs font-bold tracking-wider text-slate-500 uppercase">Active Policy</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 dark:divide-slate-800">
                            <tr
                                v-for="tax in taxes"
                                :key="tax.id"
                                class="group transition-colors hover:bg-slate-50/50 dark:hover:bg-slate-800/50"
                                :class="{ 'bg-indigo-50/40 dark:bg-indigo-900/10': tax.id === taxSetup.active_tax_id && taxSetup.is_enabled }"
                            >
                                <td class="px-6 py-4 font-bold text-slate-700 dark:text-slate-200">{{ tax.name }}</td>
                                <td class="px-6 py-4">
                                    <div class="flex flex-col">
                                        <span class="text-sm text-slate-600 capitalize dark:text-slate-400">{{ tax.type }}</span>
                                        <span v-if="tax.type === 'fixed' && tax.fixed_amount" class="text-[10px] text-slate-400">
                                            {{
                                                tax.fixed_amount_type === 'percentage'
                                                    ? tax.fixed_amount + '% of salary'
                                                    : Number(tax.fixed_amount).toLocaleString() + ' flat'
                                            }}
                                        </span>
                                    </div>
                                </td>
                                <td class="px-6 py-4">
                                    <span
                                        class="rounded-full px-2.5 py-0.5 text-[10px] font-bold tracking-wider uppercase"
                                        :class="
                                            tax.status === 'active'
                                                ? 'bg-emerald-50 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400'
                                                : 'bg-slate-100 text-slate-500 dark:bg-slate-800'
                                        "
                                    >
                                        {{ tax.status }}
                                    </span>
                                </td>
                                <td class="px-6 py-4">
                                    <span
                                        v-if="tax.id === taxSetup.active_tax_id && taxSetup.is_enabled"
                                        class="inline-flex items-center gap-1 rounded-full bg-indigo-50 px-2.5 py-0.5 text-[10px] font-bold tracking-wider text-indigo-600 uppercase dark:bg-indigo-900/30 dark:text-indigo-400"
                                    >
                                        <CheckCircle2 class="h-3 w-3" /> Currently Active
                                    </span>
                                    <span v-else class="text-sm text-slate-400 italic">—</span>
                                </td>
                                <td class="px-6 py-4 text-right">
                                    <div class="flex items-center justify-end gap-2">
                                        <Link
                                            :href="`/admin/taxes/${tax.id}/edit`"
                                            class="flex h-8 w-8 items-center justify-center rounded-lg text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-800"
                                        >
                                            <Pencil class="h-4 w-4" />
                                        </Link>
                                        <button
                                            class="flex h-8 w-8 items-center justify-center rounded-lg text-rose-500 transition-colors hover:bg-rose-50 hover:text-rose-600 disabled:opacity-50"
                                            @click="deleteTax(tax.id)"
                                            :disabled="tax.id === taxSetup.active_tax_id"
                                            :title="tax.id === taxSetup.active_tax_id ? 'Cannot delete the active tax policy' : 'Delete'"
                                        >
                                            <Trash2 class="h-4 w-4" />
                                        </button>
                                    </div>
                                </td>
                            </tr>
                            <tr v-if="taxes.length === 0">
                                <td colspan="5" class="bg-white px-6 py-12 text-center text-slate-400 italic dark:bg-slate-900">
                                    No tax policies configured yet.
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <ConfirmationModal
            :show="confirmState.show"
            title="Delete Tax Policy"
            message="Are you sure you want to delete this tax? This action cannot be undone."
            confirm-text="Delete"
            type="danger"
            @close="confirmState.show = false"
            @confirm="executeDelete"
        />
    </AdminLayout>
</template>
