import { Head, Link, router } from '@inertiajs/react';
import { Plus } from 'lucide-react';
import { useState } from 'react';
import type { PaginationState } from '@/components/data-display';
import { DataTable } from '@/components/data-display';
import { DeleteConfirmDialog } from '@/components/dialogs';
import { FilterPopover } from '@/components/data-display';
import { PageHeader } from '@/components/layout';
import { Button } from '@/components/ui/button';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import { useCan } from '@/hooks/use-can';
import { useServerTable } from '@/hooks/use-server-table';
import {
    destroy,
    create as employeeCreate,
    edit as employeeEdit,
    index as employeeIndex,
    toggleActive,
    resetPassword as resetPasswordRoute,
} from '@/routes/admin/hr/employees';
import type { Employee } from './columns';
import { createEmployeeColumns } from './columns';

type Props = {
    employees: {
        data: Employee[];
        current_page: number;
        last_page: number;
        per_page: number;
        total: number;
    };
    filters: {
        employment_status?: string;
        is_active?: string;
        gender?: string;
    };
    canViewAll: boolean;
};

export default function EmployeeIndex({ employees, filters, canViewAll }: Props) {
    const { can } = useCan();
    const [deleting, setDeleting] = useState<Employee | null>(null);
    const [resetPasswordTarget, setResetPasswordTarget] =
        useState<Employee | null>(null);

    const pagination: PaginationState = {
        current_page: employees.current_page,
        last_page: employees.last_page,
        per_page: employees.per_page,
        total: employees.total,
    };

    const {
        search,
        filterOpen,
        setFilterOpen,
        handlePageChange,
        handlePerPageChange,
        handleSearchChange,
        applyFilter,
        clearFilters,
    } = useServerTable({
        route: () => employeeIndex.url(),
        pagination,
        filters,
    });

    function handleDelete() {
        if (!deleting) {
            return;
        }

        router.delete(destroy.url(deleting.id), {
            onSuccess: () => setDeleting(null),
        });
    }

    function handleResetPassword() {
        if (!resetPasswordTarget) {
            return;
        }

        router.post(
            resetPasswordRoute.url(resetPasswordTarget.id),
            {},
            {
                onSuccess: () => setResetPasswordTarget(null),
            },
        );
    }

    const columns = createEmployeeColumns({
        handleEdit: (employee) => {
            router.visit(employeeEdit.url(employee.id));
        },
        handleDeleteClick: (employee) => setDeleting(employee),
        handleResetPassword: (employee) => setResetPasswordTarget(employee),
        toggleActiveUrl: (id) => toggleActive.url(id),
        can,
        canViewAll,
    });

    const filterToolbar = (
        <FilterPopover
            open={filterOpen}
            onOpenChange={setFilterOpen}
            filters={filters}
            hasActiveFilters={Boolean(
                filters.employment_status || filters.is_active,
            )}
            onClear={clearFilters}
        >
            <div className="flex flex-col gap-2">
                <label className="text-xs text-muted-foreground">
                    Status Karyawan
                </label>
                <Select
                    value={filters.employment_status ?? 'all'}
                    onValueChange={(value) =>
                        applyFilter('employment_status', value)
                    }
                >
                    <SelectTrigger className="w-full">
                        <SelectValue placeholder="Semua Status" />
                    </SelectTrigger>
                    <SelectContent>
                        <SelectItem value="all">Semua Status</SelectItem>
                        <SelectItem value="full_time">Full Time</SelectItem>
                        <SelectItem value="part_time">Part Time</SelectItem>
                        <SelectItem value="contract">Kontrak</SelectItem>
                        <SelectItem value="internship">Magang</SelectItem>
                        <SelectItem value="resigned">Keluar</SelectItem>
                    </SelectContent>
                </Select>
            </div>

            <div className="flex flex-col gap-2">
                <label className="text-xs text-muted-foreground">
                    Status Aktif
                </label>
                <Select
                    value={filters.is_active ?? 'all'}
                    onValueChange={(value) => applyFilter('is_active', value)}
                >
                    <SelectTrigger className="w-full">
                        <SelectValue placeholder="Semua" />
                    </SelectTrigger>
                    <SelectContent>
                        <SelectItem value="all">Semua</SelectItem>
                        <SelectItem value="1">Aktif</SelectItem>
                        <SelectItem value="0">Tidak Aktif</SelectItem>
                    </SelectContent>
                </Select>
            </div>

            <div className="flex flex-col gap-2">
                <label className="text-xs text-muted-foreground">
                    Jenis Kelamin
                </label>
                <Select
                    value={filters.gender ?? 'all'}
                    onValueChange={(value) => applyFilter('gender', value)}
                >
                    <SelectTrigger className="w-full">
                        <SelectValue placeholder="Semua" />
                    </SelectTrigger>
                    <SelectContent>
                        <SelectItem value="all">Semua</SelectItem>
                        <SelectItem value="male">Laki-laki</SelectItem>
                        <SelectItem value="female">Perempuan</SelectItem>
                    </SelectContent>
                </Select>
            </div>
        </FilterPopover>
    );

    return (
        <>
            <Head title="Pegawai" />

            <div className="flex h-full flex-1 flex-col gap-6 overflow-x-auto p-4 md:p-6">
                <PageHeader
                    title="Pegawai"
                    actions={
                        can('employees.create') ? (
                            <Button asChild>
                                <Link href={employeeCreate.url()}>
                                    <Plus className="h-4 w-4" />
                                    Tambah
                                </Link>
                            </Button>
                        ) : undefined
                    }
                />

                <DataTable
                    columns={columns}
                    data={employees.data}
                    searchKey="full_name"

                    emptyText="Belum ada data pegawai."
                    pagination={pagination}
                    onPageChange={handlePageChange}
                    onPerPageChange={handlePerPageChange}
                    onSearchChange={handleSearchChange}
                    searchValue={search}
                    toolbar={filterToolbar}
                />

                <DeleteConfirmDialog
                    target={deleting}
                    onOpenChange={(open) => {
                        if (!open) {
                            setDeleting(null);
                        }
                    }}
                    title="Hapus Pegawai"
                    description={(employee) =>
                        `Apakah Anda yakin ingin menghapus pegawai "${employee.user_profile?.full_name}"? Tindakan ini tidak dapat dibatalkan.`
                    }
                    onConfirm={handleDelete}
                />

                <DeleteConfirmDialog
                    target={resetPasswordTarget}
                    onOpenChange={(open) => {
                        if (!open) {
                            setResetPasswordTarget(null);
                        }
                    }}
                    title="Reset Kata Sandi"
                    description={(employee) =>
                        `Apakah Anda yakin ingin mereset kata sandi pegawai "${employee.user_profile?.full_name}" ke kata sandi default?`
                    }
                    confirmLabel="Reset"
                    variant="default"
                    onConfirm={handleResetPassword}
                />
            </div>
        </>
    );
}
