import { Head, router } from '@inertiajs/react';
import { Filter, Plus, X } from 'lucide-react';
import { useCallback, useState } from 'react';
import { ConfirmDialog } from '@/components/confirm-dialog';
import { DataTable } from '@/components/data-table';
import type { PaginationState } from '@/components/data-table';
import { Button } from '@/components/ui/button';
import {
    Popover,
    PopoverContent,
    PopoverTrigger,
} from '@/components/ui/popover';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
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;
    };
};

export default function EmployeeIndex({ employees, filters }: Props) {
    const [deleting, setDeleting] = useState<Employee | null>(null);
    const [resetPasswordTarget, setResetPasswordTarget] =
        useState<Employee | null>(null);
    const [filterOpen, setFilterOpen] = useState(false);
    const [search, setSearch] = useState('');
    const pagination: PaginationState = {
        current_page: employees.current_page,
        last_page: employees.last_page,
        per_page: employees.per_page,
        total: employees.total,
    };

    const hasActiveFilters = filters.employment_status || filters.is_active;

    function applyFilter(key: string, value: string) {
        const newFilters = { ...filters };

        if (value === '' || value === 'all') {
            delete newFilters[key as keyof typeof newFilters];
        } else {
            newFilters[key as keyof typeof newFilters] = value;
        }

        router.get(
            employeeIndex.url(),
            {
                ...newFilters,
                page: 1,
                per_page: pagination.per_page,
                search,
            },
            { preserveState: true, replace: true },
        );
    }

    function clearFilters() {
        router.get(
            employeeIndex.url(),
            {
                page: 1,
                per_page: pagination.per_page,
                search,
            },
            { preserveState: true, replace: true },
        );
        setFilterOpen(false);
    }

    function handlePageChange(page: number) {
        router.get(
            employeeIndex.url(),
            {
                ...filters,
                page,
                per_page: pagination.per_page,
                search,
            },
            { preserveState: true, replace: true },
        );
    }

    function handlePerPageChange(perPage: number) {
        router.get(
            employeeIndex.url(),
            {
                ...filters,
                page: 1,
                per_page: perPage,
                search,
            },
            { preserveState: true, replace: true },
        );
    }

    const handleSearchChange = useCallback(
        (value: string) => {
            setSearch(value);
            router.get(
                employeeIndex.url(),
                {
                    ...filters,
                    page: 1,
                    per_page: pagination.per_page,
                    search: value,
                },
                { preserveState: true, replace: true },
            );
        },
        [pagination.per_page, 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) => {
            window.location.href = employeeEdit.url(employee.id);
        },
        handleDeleteClick: (employee) => setDeleting(employee),
        handleResetPassword: (employee) => setResetPasswordTarget(employee),
        toggleActiveUrl: (id) => toggleActive.url(id),
    });

    const filterToolbar = (
        <Popover open={filterOpen} onOpenChange={setFilterOpen}>
            <PopoverTrigger asChild>
                <Button variant="outline" size="sm">
                    <Filter className="h-4 w-4" />
                    Filter
                    {hasActiveFilters && (
                        <span className="ml-1 flex h-5 w-5 items-center justify-center rounded-full bg-primary text-xs text-primary-foreground">
                            {Object.values(filters).filter(Boolean).length}
                        </span>
                    )}
                </Button>
            </PopoverTrigger>
            <PopoverContent className="w-64" align="end">
                <div className="flex flex-col gap-4">
                    <div className="flex items-center justify-between">
                        <span className="text-sm font-medium">Filter</span>
                        {hasActiveFilters && (
                            <Button
                                variant="ghost"
                                size="sm"
                                className="h-6 px-2 text-xs"
                                onClick={clearFilters}
                            >
                                <X className="mr-1 h-3 w-3" />
                                Hapus Semua
                            </Button>
                        )}
                    </div>

                    <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>
                </div>
            </PopoverContent>
        </Popover>
    );

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

            <div className="flex h-full flex-1 flex-col gap-6 overflow-x-auto p-4 md:p-6">
                <div className="flex items-center justify-between">
                    <div>
                        <h2 className="text-2xl font-semibold tracking-tight">
                            Pegawai
                        </h2>
                    </div>
                    <Button asChild>
                        <a href={employeeCreate.url()}>
                            <Plus className="h-4 w-4" />
                            Tambah
                        </a>
                    </Button>
                </div>

                <DataTable
                    columns={columns}
                    data={employees.data}
                    searchKey="full_name"
                    searchPlaceholder="Cari pegawai..."
                    emptyText="Belum ada data pegawai."
                    pagination={pagination}
                    onPageChange={handlePageChange}
                    onPerPageChange={handlePerPageChange}
                    onSearchChange={handleSearchChange}
                    searchValue={search}
                    toolbar={filterToolbar}
                />

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

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