import {
    getCoreRowModel,
    getFilteredRowModel,
    getPaginationRowModel,
    getSortedRowModel,
    type ColumnDef,
    type ColumnFiltersState,
    type RowSelectionState,
    type SortingState,
    type Table as TanstackTable,
    type VisibilityState,
} from '@tanstack/table-core';
import { flexRender, useReactTable } from '@tanstack/react-table';
import { useState, type ReactNode } from 'react';
import { EmptyState } from '@/components/empty-state';
import { DataTableCard } from '@/components/data-table/data-table-card';
import { DataTableColumnVisibilityContext } from '@/components/data-table/data-table-column-visibility-context';
import { DataTablePagination } from '@/components/data-table/data-table-pagination';
import { DataTableToolbar } from '@/components/data-table/data-table-toolbar';
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from '@/components/ui/table';
import { cn } from '@/lib/utils';

type SearchConfig = {
    value: string;
    onChange: (value: string) => void;
    placeholder?: string;
};

type Props<TData, TValue> = {
    columns: ColumnDef<TData, TValue>[];
    data: TData[];
    search?: SearchConfig;
    filters?: ReactNode;
    actions?: ReactNode;
    framed?: boolean;
    globalFilter?: string;
    emptyMessage?: string;
    /** Contenu d'état vide personnalisé (ex. EmptyState). */
    emptyState?: ReactNode;
    /** Rendu carte pour mobile (< md) ; le tableau n'apparaît qu'à partir de md. */
    mobileCard?: (row: TData) => ReactNode;
    /** Contenu sous la barre d'outils (ex. puces de filtres actifs). */
    belowToolbar?: ReactNode;
    enableRowSelection?: boolean;
    pageSize?: number;
    defaultSorting?: SortingState;
    getRowId?: (row: TData) => string;
    getRowClassName?: (row: TData) => string | undefined;
    renderToolbar?: (table: TanstackTable<TData>) => ReactNode;
    wrapTable?: (table: ReactNode) => ReactNode;
    renderBulkActions?: (table: TanstackTable<TData>) => ReactNode;
    className?: string;
};

export function DataTable<TData, TValue>({
    columns,
    data,
    search,
    filters,
    actions,
    framed = true,
    globalFilter,
    emptyMessage = 'Aucun résultat.',
    emptyState,
    mobileCard,
    belowToolbar,
    enableRowSelection = false,
    pageSize = 10,
    defaultSorting = [{ id: 'created_at', desc: true }],
    getRowId,
    getRowClassName,
    renderToolbar,
    wrapTable,
    renderBulkActions,
    className,
}: Props<TData, TValue>) {
    const [sorting, setSorting] = useState<SortingState>(defaultSorting);
    const [columnFilters, setColumnFilters] = useState<ColumnFiltersState>([]);
    const [columnVisibility, setColumnVisibility] = useState<VisibilityState>(
        {},
    );
    const [rowSelection, setRowSelection] = useState<RowSelectionState>({});

    const resolvedGlobalFilter = globalFilter ?? search?.value ?? '';

    const table = useReactTable({
        data,
        columns,
        state: {
            sorting,
            columnFilters,
            columnVisibility,
            globalFilter: resolvedGlobalFilter,
            rowSelection,
        },
        enableRowSelection,
        getRowId,
        onSortingChange: setSorting,
        onColumnFiltersChange: setColumnFilters,
        onColumnVisibilityChange: setColumnVisibility,
        onRowSelectionChange: setRowSelection,
        getCoreRowModel: getCoreRowModel(),
        getPaginationRowModel: getPaginationRowModel(),
        getSortedRowModel: getSortedRowModel(),
        getFilteredRowModel: getFilteredRowModel(),
        initialState: {
            pagination: { pageSize },
        },
    });

    const totalRows = table.getFilteredRowModel().rows.length;
    const currentPageSize = table.getState().pagination.pageSize;
    const needsPagination = totalRows > currentPageSize;

    const isEmpty = !table.getRowModel().rows?.length;

    const tableMarkup = (
        <div className={cn('space-y-0', className)}>
            {mobileCard && !isEmpty && (
                <ul className="divide-y md:hidden">
                    {table.getRowModel().rows.map((row) => (
                        <li
                            key={row.id}
                            className={cn(
                                'p-4',
                                getRowClassName?.(row.original),
                            )}
                        >
                            {mobileCard(row.original)}
                        </li>
                    ))}
                </ul>
            )}
            <div className={cn(mobileCard && !isEmpty && 'hidden md:block')}>
                <Table>
                    {!isEmpty && (
                        <TableHeader className="bg-muted/40">
                            {table.getHeaderGroups().map((headerGroup) => (
                                <TableRow
                                    key={headerGroup.id}
                                    className="hover:bg-transparent"
                                >
                                    {headerGroup.headers.map((header) => (
                                        <TableHead
                                            key={header.id}
                                            className="h-12 px-2 font-medium text-muted-foreground"
                                        >
                                            {header.isPlaceholder
                                                ? null
                                                : flexRender(
                                                      header.column.columnDef
                                                          .header,
                                                      header.getContext(),
                                                  )}
                                        </TableHead>
                                    ))}
                                </TableRow>
                            ))}
                        </TableHeader>
                    )}
                    <TableBody>
                        {table.getRowModel().rows?.length ? (
                            table.getRowModel().rows.map((row) => (
                                <TableRow
                                    key={row.id}
                                    data-state={
                                        row.getIsSelected() && 'selected'
                                    }
                                    className={cn(
                                        'hover:bg-muted/40',
                                        getRowClassName?.(row.original),
                                    )}
                                >
                                    {row.getVisibleCells().map((cell) => (
                                        <TableCell
                                            key={cell.id}
                                            className="px-2 py-3"
                                        >
                                            {flexRender(
                                                cell.column.columnDef.cell,
                                                cell.getContext(),
                                            )}
                                        </TableCell>
                                    ))}
                                </TableRow>
                            ))
                        ) : (
                            <TableRow>
                                <TableCell
                                    colSpan={columns.length}
                                    className="h-28 text-center text-muted-foreground"
                                >
                                    {emptyState ?? (
                                        <EmptyState message={emptyMessage} />
                                    )}
                                </TableCell>
                            </TableRow>
                        )}
                    </TableBody>
                </Table>
            </div>
            <DataTablePagination
                table={table}
                showNavigation={needsPagination}
            />
        </div>
    );

    const toolbar =
        renderToolbar?.(table) ??
        (search || filters || actions ? (
            <DataTableToolbar
                table={table}
                search={search}
                filters={filters}
                actions={actions}
                compact={data.length < 10}
            />
        ) : null);

    const wrapped = wrapTable ? (
        wrapTable(tableMarkup)
    ) : framed ? (
        <DataTableCard>{tableMarkup}</DataTableCard>
    ) : (
        tableMarkup
    );

    return (
        <DataTableColumnVisibilityContext.Provider value={columnVisibility}>
            <div className="flex flex-col gap-4">
                {toolbar}
                {belowToolbar}
                {wrapped}
            </div>
            {renderBulkActions?.(table)}
        </DataTableColumnVisibilityContext.Provider>
    );
}
