import { Head, router } from '@inertiajs/react';
import { createColumnHelper } from '@tanstack/react-table';
import type { ColumnDef, PaginationState, SortingState } from '@tanstack/react-table';
import { Pencil, Plus, Trash2 } from 'lucide-react';
import { useEffect, useMemo, useRef, useState } from 'react';
import CostCenterController from '@/actions/App/Http/Controllers/Admin/CostCenterController';
import { ConfirmDialog } from '@/components/confirm-dialog';
import { DataTable, DataTableColumnHeader } from '@/components/data-table';
import Heading from '@/components/heading';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { formatDate } from '@/lib/utils';
import { dashboard } from '@/routes';
import { index } from '@/routes/admin/cost-centers';
import type { Paginated } from '@/types';
import { CostCenterFormModal } from './cost-center-form-modal';
import type { CostCenterFormValues } from './cost-center-form-modal';

type AdminCostCenter = CostCenterFormValues & {
    department: { id: number; code: string; name: string } | null;
    created_at: string | null;
};

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

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

const columnHelper = createColumnHelper<AdminCostCenter>();

function visitCostCenters(params: {
    search: string;
    sort: string;
    direction: 'asc' | 'desc';
    page: number;
    per_page: number;
}) {
    router.get(
        index.url(),
        {
            search: params.search || 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 CostCentersIndex({
    costCenters,
    filters,
    departments,
    can,
}: {
    costCenters: Paginated<AdminCostCenter>;
    filters: Filters;
    departments: DepartmentOption[];
    can: { create: boolean; update: boolean; delete: boolean };
}) {
    const isFirstSearchEffect = useRef(true);
    const [isLoading, setIsLoading] = useState(false);
    const [search, setSearch] = useState(filters.search);
    const [sorting, setSorting] = useState<SortingState>([
        { id: filters.sort, desc: filters.direction === 'desc' },
    ]);
    const [pagination, setPagination] = useState<PaginationState>({
        pageIndex: costCenters.current_page - 1,
        pageSize: costCenters.per_page,
    });
    const [modalOpen, setModalOpen] = useState(false);
    const [editing, setEditing] = useState<CostCenterFormValues | null>(null);

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

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

    useEffect(() => {
        setSearch(filters.search);
        setSorting([{ id: filters.sort, desc: filters.direction === 'desc' }]);
        setPagination({
            pageIndex: costCenters.current_page - 1,
            pageSize: costCenters.per_page,
        });
    }, [filters, costCenters.current_page, costCenters.per_page]);

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

        const timeout = window.setTimeout(() => {
            const sort = sorting[0];
            visitCostCenters({
                search,
                sort: sort?.id ?? 'code',
                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]);

    const columns = useMemo(() => {
        const cols: ColumnDef<AdminCostCenter, any>[] = [
            columnHelper.accessor('code', {
                header: ({ column }) => (
                    <DataTableColumnHeader column={column} title="Code" />
                ),
                cell: (info) => (
                    <span className="font-mono text-sm">{info.getValue()}</span>
                ),
            }),
            columnHelper.accessor('name', {
                header: ({ column }) => (
                    <DataTableColumnHeader column={column} title="Nom" />
                ),
            }),
            columnHelper.accessor('department', {
                header: ({ column }) => (
                    <DataTableColumnHeader column={column} title="Service" />
                ),
                cell: (info) => info.getValue()?.name ?? '—',
            }),
            columnHelper.accessor('is_active', {
                header: ({ column }) => (
                    <DataTableColumnHeader column={column} title="Statut" />
                ),
                cell: (info) =>
                    info.getValue() ? (
                        <Badge variant="secondary">Actif</Badge>
                    ) : (
                        <Badge variant="outline">Inactif</Badge>
                    ),
            }),
            columnHelper.accessor('created_at', {
                header: ({ column }) => (
                    <DataTableColumnHeader column={column} title="Créé le" />
                ),
                cell: (info) => formatDate(info.getValue()),
            }),
        ];

        if (can.update || can.delete) {
            cols.push(
                columnHelper.display({
                    id: 'actions',
                    header: () => <span className="sr-only">Actions</span>,
                    cell: ({ row }) => (
                        <div className="flex justify-end gap-1">
                            {can.update && (
                                <Button
                                    type="button"
                                    variant="ghost"
                                    size="icon"
                                    onClick={() => {
                                        setEditing(row.original);
                                        setModalOpen(true);
                                    }}
                                >
                                    <Pencil />
                                </Button>
                            )}
                            {can.delete && (
                                <ConfirmDialog
                                    trigger={
                                        <Button
                                            type="button"
                                            variant="ghost"
                                            size="icon"
                                        >
                                            <Trash2 />
                                        </Button>
                                    }
                                    title="Supprimer ce centre de coût ?"
                                    description="Impossible s'il est utilisé par des écritures comptables."
                                    confirmLabel="Supprimer"
                                    onConfirm={() =>
                                        router.delete(
                                            CostCenterController.destroy.url(
                                                row.original.id,
                                            ),
                                            { preserveScroll: true },
                                        )
                                    }
                                />
                            )}
                        </div>
                    ),
                }),
            );
        }

        return cols;
    }, [can.update, can.delete]);

    return (
        <>
            <Head title="Analytique — Centres de coûts" />
            <div className="flex h-full flex-1 flex-col gap-6 p-4 md:p-6">
                <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
                    <Heading
                        title="Analytique"
                        description="Centres de coûts pour la ventilation des écritures comptables"
                    />
                    {can.create && (
                        <Button
                            type="button"
                            onClick={() => {
                                setEditing(null);
                                setModalOpen(true);
                            }}
                        >
                            <Plus />
                            Nouveau
                        </Button>
                    )}
                </div>

                <DataTable
                    id="admin-cost-centers"
                    columns={columns}
                    data={costCenters.data}
                    getRowId={(row) => String(row.id)}
                    isLoading={isLoading}
                    searchValue={search}
                    onSearchChange={setSearch}
                    searchPlaceholder="Rechercher…"
                    emptyMessage="Aucun centre de coût."
                    sorting={sorting}
                    onSortingChange={(updater) => {
                        const next =
                            typeof updater === 'function'
                                ? updater(sorting)
                                : updater;
                        setSorting(next);
                        const sort = next[0];
                        visitCostCenters({
                            search,
                            sort: sort?.id ?? 'code',
                            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;
                        setPagination(next);
                        const sort = sorting[0];
                        visitCostCenters({
                            search,
                            sort: sort?.id ?? 'code',
                            direction: sort?.desc === false ? 'asc' : 'desc',
                            page: next.pageIndex + 1,
                            per_page: next.pageSize,
                        });
                    }}
                    manualPagination
                    pageCount={costCenters.last_page}
                />
            </div>

            <CostCenterFormModal
                open={modalOpen}
                onOpenChange={setModalOpen}
                costCenter={editing}
                departments={departments}
            />
        </>
    );
}

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