import { Head, Link, router } from '@inertiajs/react';
import { createColumnHelper } from '@tanstack/react-table';
import type {
    ColumnDef,
    PaginationState,
    SortingState,
} from '@tanstack/react-table';
import { Eye } from 'lucide-react';
import { useEffect, useMemo, useRef, useState } from 'react';
import { DataTable, DataTableColumnHeader } from '@/components/data-table';
import Heading from '@/components/heading';
import { Button } from '@/components/ui/button';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import { formatDate } from '@/lib/utils';
import { dashboard } from '@/routes';
import { show as showEmployee } from '@/routes/admin/employees';
import { index } from '@/routes/admin/hr-archives';
import type { Paginated } from '@/types';

type ArchivedEmployee = {
    id: number;
    code: string;
    full_name: string;
    job_title: string | null;
    department: string | null;
    terminated_at: string | null;
    termination_reason: string | null;
    termination_reason_label: string | null;
};

type Filters = {
    search: string;
    department_id: number | null;
    termination_reason: string;
    sort: string;
    direction: 'asc' | 'desc';
    per_page: number;
};

type DepartmentOption = { id: number; code: string; name: string };
type ReasonOption = { value: string; label: string };

const columnHelper = createColumnHelper<ArchivedEmployee>();

function visitArchives(params: {
    search: string;
    department_id: string;
    termination_reason: string;
    sort: string;
    direction: 'asc' | 'desc';
    page: number;
    per_page: number;
}) {
    router.get(
        index.url(),
        {
            search: params.search || undefined,
            department_id:
                params.department_id && params.department_id !== 'all'
                    ? params.department_id
                    : undefined,
            termination_reason:
                params.termination_reason && params.termination_reason !== 'all'
                    ? params.termination_reason
                    : undefined,
            sort: params.sort,
            direction: params.direction,
            page: params.page > 1 ? params.page : undefined,
            per_page: params.per_page !== 15 ? params.per_page : undefined,
        },
        { preserveState: true, replace: true, preserveScroll: true },
    );
}

export default function HrArchivesIndex({
    employees,
    filters,
    departments = [],
    terminationReasons = [],
}: {
    employees: Paginated<ArchivedEmployee>;
    filters: Filters;
    departments?: DepartmentOption[];
    terminationReasons?: ReasonOption[];
}) {
    const isFirstSearchEffect = useRef(true);
    const [isLoading, setIsLoading] = useState(false);
    const [search, setSearch] = useState(filters.search);
    const [departmentId, setDepartmentId] = useState(
        filters.department_id ? String(filters.department_id) : 'all',
    );
    const [terminationReason, setTerminationReason] = useState(
        filters.termination_reason || 'all',
    );
    const [sorting, setSorting] = useState<SortingState>([
        { id: filters.sort, desc: filters.direction === 'desc' },
    ]);
    const [pagination, setPagination] = useState<PaginationState>({
        pageIndex: employees.current_page - 1,
        pageSize: employees.per_page,
    });

    useEffect(() => {
        const removeStart = router.on('start', () => setIsLoading(true));
        const removeFinish = router.on('finish', () => setIsLoading(false));

        return () => {
            removeStart();
            removeFinish();
        };
    }, []);

    useEffect(() => {
        setSearch(filters.search);
        setDepartmentId(
            filters.department_id ? String(filters.department_id) : 'all',
        );
        setTerminationReason(filters.termination_reason || 'all');
        setSorting([{ id: filters.sort, desc: filters.direction === 'desc' }]);
        setPagination({
            pageIndex: employees.current_page - 1,
            pageSize: employees.per_page,
        });
    }, [filters, employees.current_page, employees.per_page]);

    useEffect(() => {
        if (isFirstSearchEffect.current) {
            isFirstSearchEffect.current = false;

            return;
        }

        const timeout = window.setTimeout(() => {
            const sort = sorting[0];
            visitArchives({
                search,
                department_id: departmentId,
                termination_reason: terminationReason,
                sort: sort?.id ?? 'terminated_at',
                direction: sort?.desc === false ? 'asc' : 'desc',
                page: 1,
                per_page: pagination.pageSize,
            });
        }, 300);

        return () => window.clearTimeout(timeout);
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [search, departmentId, terminationReason]);

    const columns = useMemo(
        () =>
            [
                columnHelper.accessor('code', {
                    header: ({ column }) => (
                        <DataTableColumnHeader
                            column={column}
                            title="Matricule"
                        />
                    ),
                }),
                columnHelper.accessor('full_name', {
                    header: ({ column }) => (
                        <DataTableColumnHeader column={column} title="Nom" />
                    ),
                    cell: (info) => (
                        <Link
                            href={showEmployee(info.row.original.id)}
                            className="font-medium hover:underline"
                        >
                            {info.getValue()}
                        </Link>
                    ),
                }),
                columnHelper.accessor('job_title', {
                    header: 'Poste',
                    enableSorting: false,
                    cell: (info) => info.getValue() || '—',
                }),
                columnHelper.accessor('department', {
                    header: 'Service',
                    enableSorting: false,
                    cell: (info) => info.getValue() || '—',
                }),
                columnHelper.accessor('terminated_at', {
                    header: ({ column }) => (
                        <DataTableColumnHeader
                            column={column}
                            title="Départ"
                        />
                    ),
                    cell: (info) =>
                        info.getValue() ? formatDate(info.getValue()) : '—',
                }),
                columnHelper.accessor('termination_reason_label', {
                    header: 'Motif',
                    enableSorting: false,
                    cell: (info) => info.getValue() || '—',
                }),
                columnHelper.display({
                    id: 'actions',
                    header: '',
                    cell: ({ row }) => (
                        <div className="flex justify-end">
                            <Button variant="ghost" size="icon" asChild>
                                <Link href={showEmployee(row.original.id)}>
                                    <Eye />
                                </Link>
                            </Button>
                        </div>
                    ),
                }),
            ] as ColumnDef<ArchivedEmployee>[],
        [],
    );

    return (
        <>
            <Head title="Archives RH" />
            <div className="flex h-full flex-1 flex-col gap-6 p-4 md:p-6">
                <Heading
                    title="Archives RH"
                    description="Consultation des dossiers des collaborateurs partis. Aucune purge automatique."
                />

                <DataTable
                    id="admin-hr-archives"
                    columns={columns}
                    data={employees.data}
                    getRowId={(row) => String(row.id)}
                    isLoading={isLoading}
                    searchValue={search}
                    onSearchChange={setSearch}
                    searchPlaceholder="Rechercher un ancien dossier…"
                    emptyMessage="Aucun dossier archivé."
                    toolbarLeft={
                        <div className="flex flex-wrap gap-2">
                            <Select
                                value={departmentId}
                                onValueChange={setDepartmentId}
                            >
                                <SelectTrigger className="w-[200px]">
                                    <SelectValue placeholder="Service" />
                                </SelectTrigger>
                                <SelectContent>
                                    <SelectItem value="all">
                                        Tous les services
                                    </SelectItem>
                                    {departments.map((department) => (
                                        <SelectItem
                                            key={department.id}
                                            value={String(department.id)}
                                        >
                                            {department.name}
                                        </SelectItem>
                                    ))}
                                </SelectContent>
                            </Select>
                            <Select
                                value={terminationReason}
                                onValueChange={setTerminationReason}
                            >
                                <SelectTrigger className="w-[220px]">
                                    <SelectValue placeholder="Motif" />
                                </SelectTrigger>
                                <SelectContent>
                                    <SelectItem value="all">
                                        Tous les motifs
                                    </SelectItem>
                                    {terminationReasons.map((reason) => (
                                        <SelectItem
                                            key={reason.value}
                                            value={reason.value}
                                        >
                                            {reason.label}
                                        </SelectItem>
                                    ))}
                                </SelectContent>
                            </Select>
                        </div>
                    }
                    sorting={sorting}
                    onSortingChange={(updater) => {
                        const next =
                            typeof updater === 'function'
                                ? updater(sorting)
                                : updater;
                        setSorting(next);
                        const sort = next[0];
                        visitArchives({
                            search,
                            department_id: departmentId,
                            termination_reason: terminationReason,
                            sort: sort?.id ?? 'terminated_at',
                            direction: sort?.desc === false ? 'asc' : 'desc',
                            page: 1,
                            per_page: pagination.pageSize,
                        });
                    }}
                    manualSorting
                    pagination={pagination}
                    onPaginationChange={(updater) => {
                        const next =
                            typeof updater === 'function'
                                ? updater(pagination)
                                : updater;
                        const pageChanged =
                            next.pageIndex !== pagination.pageIndex;
                        const sizeChanged =
                            next.pageSize !== pagination.pageSize;

                        setPagination(next);

                        if (!pageChanged && !sizeChanged) {
                            return;
                        }

                        const sort = sorting[0];
                        visitArchives({
                            search,
                            department_id: departmentId,
                            termination_reason: terminationReason,
                            sort: sort?.id ?? 'terminated_at',
                            direction: sort?.desc === false ? 'asc' : 'desc',
                            page: sizeChanged ? 1 : next.pageIndex + 1,
                            per_page: next.pageSize,
                        });
                    }}
                    manualPagination
                    pageCount={employees.last_page}
                    totalRows={employees.total}
                />
            </div>
        </>
    );
}

HrArchivesIndex.layout = {
    breadcrumbs: [
        { title: 'Tableau de bord', href: dashboard() },
        { title: 'Archives RH', href: index() },
    ],
};
