import { router } from '@inertiajs/react';
import type { LucideIcon } from 'lucide-react';
import {
    ArrowDown,
    ArrowUp,
    ArrowUpDown,
    ChevronLeft,
    ChevronRight,
    Inbox,
    Search,
    X,
} from 'lucide-react';
import type { ReactNode } from 'react';
import { useEffect, useMemo, useRef, useState } from 'react';
import Pagination from '@/components/member/pagination';
import { Checkbox } from '@/components/ui/checkbox';
import { Input } from '@/components/ui/input';
import { cn } from '@/lib/utils';
import type { Paginated } from '@/types';

export type DataTableColumn<T> = {
    /** Unique key; also the sort key sent to the server in server mode. */
    key: string;
    header: ReactNode;
    /** Cell content. Defaults to `row[key]`. */
    cell?: (row: T) => ReactNode;
    sortable?: boolean;
    /** Value used for client-side sorting. Defaults to `row[key]`. */
    sortValue?: (row: T) => string | number | null | undefined;
    align?: 'left' | 'center' | 'right';
    /** Hide this column below the `sm` breakpoint. */
    hideOnMobile?: boolean;
    className?: string;
    headerClassName?: string;
};

type SortState = { key: string; direction: 'asc' | 'desc' } | null;

type Props<T> = {
    columns: DataTableColumn<T>[];
    getRowId: (row: T) => string | number;
    /**
     * Client mode: pass every row; search, sort and paging happen in the browser.
     */
    data?: T[];
    /**
     * Server mode: pass a Laravel paginator. Search and sort are sent as
     * `?search=`, `?sort=` and `?direction=` query params to the current URL.
     */
    page?: Paginated<T>;
    title?: ReactNode;
    description?: ReactNode;
    /** Buttons or filters shown next to the search box. */
    toolbar?: ReactNode;
    /** Show a search box. In client mode rows are matched on `searchText`. */
    searchable?: boolean;
    searchPlaceholder?: string;
    /** Text a row is searched by (client mode). Defaults to its string/number values. */
    searchText?: (row: T) => string;
    /** Rows per page in client mode. 0 shows everything. */
    pageSize?: number;
    /** Initial sort in client mode; current sort in server mode. */
    defaultSort?: SortState;
    /** Enables checkboxes; receives the selected rows and a reset function. */
    bulkActions?: (selected: T[], clearSelection: () => void) => ReactNode;
    empty?: { icon?: LucideIcon; title: string; description?: string };
    rowClassName?: (row: T) => string | undefined;
    className?: string;
};

const alignClass = {
    left: 'text-left',
    center: 'text-center',
    right: 'text-right',
} as const;

/** Plain text for primitive values; objects and empty values become ''. */
function toText(value: unknown): string {
    return typeof value === 'string' ||
        typeof value === 'number' ||
        typeof value === 'boolean'
        ? String(value)
        : '';
}

function defaultSearchText(row: unknown): string {
    if (row === null || typeof row !== 'object') {
        return toText(row);
    }

    return Object.values(row as Record<string, unknown>)
        .filter(
            (value) => typeof value === 'string' || typeof value === 'number',
        )
        .join(' ');
}

function readKey<T>(row: T, key: string): unknown {
    return (row as Record<string, unknown>)[key];
}

function compare(a: unknown, b: unknown): number {
    if (a === b) {
        return 0;
    }

    if (a === null || a === undefined) {
        return 1;
    }

    if (b === null || b === undefined) {
        return -1;
    }

    if (typeof a === 'number' && typeof b === 'number') {
        return a - b;
    }

    return toText(a).localeCompare(toText(b), undefined, {
        numeric: true,
        sensitivity: 'base',
    });
}

function currentQuery(): URLSearchParams {
    return new URLSearchParams(
        typeof window === 'undefined' ? '' : window.location.search,
    );
}

/**
 * Reusable table: search, sorting, client or server pagination, row
 * selection with bulk actions, empty state and mobile-friendly columns.
 */
export default function DataTable<T>({
    columns,
    getRowId,
    data,
    page,
    title,
    description,
    toolbar,
    searchable = false,
    searchPlaceholder = 'Search',
    searchText,
    pageSize = 10,
    defaultSort = null,
    bulkActions,
    empty = { title: 'Nothing to show yet' },
    rowClassName,
    className,
}: Props<T>) {
    const isServer = page !== undefined;
    const [search, setSearch] = useState(() =>
        isServer ? (currentQuery().get('search') ?? '') : '',
    );
    const [sort, setSort] = useState<SortState>(() => {
        if (!isServer) {
            return defaultSort;
        }

        const query = currentQuery();
        const key = query.get('sort');

        return key
            ? {
                  key,
                  direction: query.get('direction') === 'desc' ? 'desc' : 'asc',
              }
            : defaultSort;
    });
    const [clientPage, setClientPage] = useState(1);
    const [selectedIds, setSelectedIds] = useState<Set<string | number>>(
        () => new Set(),
    );

    const visitServer = (params: Record<string, string | null>) => {
        const query = currentQuery();

        Object.entries(params).forEach(([name, value]) =>
            value ? query.set(name, value) : query.delete(name),
        );
        query.delete('page');

        const queryString = query.toString();

        router.get(
            `${window.location.pathname}${queryString ? `?${queryString}` : ''}`,
            {},
            { preserveState: true, preserveScroll: true, replace: true },
        );
    };

    const isFirstSearch = useRef(true);

    useEffect(() => {
        if (!isServer) {
            return;
        }

        if (isFirstSearch.current) {
            isFirstSearch.current = false;

            return;
        }

        const timer = window.setTimeout(
            () => visitServer({ search: search.trim() || null }),
            350,
        );

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

    const processed = useMemo(() => {
        if (isServer) {
            return page.data;
        }

        let rows = data ?? [];
        const term = search.trim().toLowerCase();

        if (term) {
            rows = rows.filter((row) =>
                (searchText ? searchText(row) : defaultSearchText(row))
                    .toLowerCase()
                    .includes(term),
            );
        }

        if (sort) {
            const column = columns.find((item) => item.key === sort.key);
            const valueOf = (row: T) =>
                column?.sortValue
                    ? column.sortValue(row)
                    : readKey(row, sort.key);
            rows = [...rows].sort(
                (a, b) =>
                    compare(valueOf(a), valueOf(b)) *
                    (sort.direction === 'asc' ? 1 : -1),
            );
        }

        return rows;
    }, [isServer, page, data, search, searchText, sort, columns]);

    const pageCount =
        isServer || pageSize === 0
            ? 1
            : Math.max(1, Math.ceil(processed.length / pageSize));
    const safePage = Math.min(clientPage, pageCount);
    const rows =
        isServer || pageSize === 0
            ? processed
            : processed.slice((safePage - 1) * pageSize, safePage * pageSize);
    const total = isServer ? page.total : processed.length;

    const toggleSort = (key: string) => {
        const next: SortState =
            sort?.key !== key
                ? { key, direction: 'asc' }
                : sort.direction === 'asc'
                  ? { key, direction: 'desc' }
                  : null;

        setSort(next);
        setClientPage(1);

        if (isServer) {
            visitServer({
                sort: next?.key ?? null,
                direction: next?.direction ?? null,
            });
        }
    };

    const isSelectable = bulkActions !== undefined;
    const pageIds = rows.map(getRowId);
    const selectedOnPage = pageIds.filter((id) => selectedIds.has(id)).length;
    const allRows = isServer ? page.data : (data ?? []);
    const selectedRows = allRows.filter((row) =>
        selectedIds.has(getRowId(row)),
    );
    const clearSelection = () => setSelectedIds(new Set());

    const togglePage = (isOn: boolean) =>
        setSelectedIds((current) => {
            const next = new Set(current);
            pageIds.forEach((id) => (isOn ? next.add(id) : next.delete(id)));

            return next;
        });

    const toggleRow = (id: string | number, isOn: boolean) =>
        setSelectedIds((current) => {
            const next = new Set(current);

            if (isOn) {
                next.add(id);
            } else {
                next.delete(id);
            }

            return next;
        });

    const EmptyIcon = empty.icon ?? Inbox;
    const columnCount = columns.length + (isSelectable ? 1 : 0);
    const hasHeader = title || description || searchable || toolbar;

    return (
        <section
            className={cn(
                'min-w-0 overflow-hidden rounded-landing-lg border border-surface-200 bg-white shadow-landing-sm',
                className,
            )}
        >
            {hasHeader && (
                <div className="flex flex-wrap items-center justify-between gap-3 border-b border-surface-100 p-4">
                    {(title || description) && (
                        <div className="min-w-0">
                            {title && (
                                <h2 className="font-display text-base font-semibold text-ink">
                                    {title}
                                </h2>
                            )}
                            {description && (
                                <p className="text-xs text-ink-400">
                                    {description}
                                </p>
                            )}
                        </div>
                    )}
                    <div className="flex w-full flex-wrap items-center gap-2 sm:ml-auto sm:w-auto">
                        {searchable && (
                            <div className="relative w-full sm:w-56">
                                <Search className="pointer-events-none absolute top-1/2 left-2.5 size-3.5 -translate-y-1/2 text-ink-400" />
                                <Input
                                    type="search"
                                    value={search}
                                    onChange={(event) => {
                                        setSearch(event.target.value);
                                        setClientPage(1);
                                    }}
                                    placeholder={searchPlaceholder}
                                    aria-label={searchPlaceholder}
                                    className="h-9 pr-8 pl-8 text-sm"
                                />
                                {search && (
                                    <button
                                        type="button"
                                        onClick={() => {
                                            setSearch('');
                                            setClientPage(1);
                                        }}
                                        className="absolute top-1/2 right-2 -translate-y-1/2 rounded-full p-0.5 text-ink-400 hover:text-ink"
                                        aria-label="Clear search"
                                    >
                                        <X className="size-3.5" />
                                    </button>
                                )}
                            </div>
                        )}
                        {toolbar}
                    </div>
                </div>
            )}

            {isSelectable && selectedRows.length > 0 && (
                <div className="flex flex-wrap items-center gap-2 border-b border-surface-100 bg-brand-faint px-4 py-2 text-sm">
                    <span className="font-semibold text-brand">
                        {selectedRows.length} selected
                    </span>
                    <button
                        type="button"
                        onClick={clearSelection}
                        className="text-xs font-semibold text-ink-500 hover:text-ink"
                    >
                        Clear
                    </button>
                    <div className="ml-auto flex flex-wrap items-center gap-2">
                        {bulkActions(selectedRows, clearSelection)}
                    </div>
                </div>
            )}

            <div className="overflow-x-auto">
                <table className="w-full text-sm">
                    <thead className="bg-surface-50 text-xs text-ink-500">
                        <tr>
                            {isSelectable && (
                                <th scope="col" className="w-10 px-4 py-2.5">
                                    <Checkbox
                                        aria-label="Select all rows on this page"
                                        disabled={rows.length === 0}
                                        checked={
                                            rows.length > 0 &&
                                            selectedOnPage === rows.length
                                                ? true
                                                : selectedOnPage > 0
                                                  ? 'indeterminate'
                                                  : false
                                        }
                                        onCheckedChange={(state) =>
                                            togglePage(state === true)
                                        }
                                    />
                                </th>
                            )}
                            {columns.map((column) => {
                                const isSorted = sort?.key === column.key;

                                return (
                                    <th
                                        key={column.key}
                                        scope="col"
                                        aria-sort={
                                            isSorted
                                                ? sort.direction === 'asc'
                                                    ? 'ascending'
                                                    : 'descending'
                                                : undefined
                                        }
                                        className={cn(
                                            'px-4 py-2.5 font-semibold whitespace-nowrap',
                                            alignClass[column.align ?? 'left'],
                                            column.hideOnMobile &&
                                                'hidden sm:table-cell',
                                            column.headerClassName,
                                        )}
                                    >
                                        {column.sortable ? (
                                            <button
                                                type="button"
                                                onClick={() =>
                                                    toggleSort(column.key)
                                                }
                                                className={cn(
                                                    'inline-flex items-center gap-1 rounded hover:text-ink focus-visible:ring-2 focus-visible:ring-highlight focus-visible:outline-none',
                                                    isSorted && 'text-ink',
                                                )}
                                            >
                                                {column.header}
                                                {isSorted ? (
                                                    sort.direction === 'asc' ? (
                                                        <ArrowUp className="size-3" />
                                                    ) : (
                                                        <ArrowDown className="size-3" />
                                                    )
                                                ) : (
                                                    <ArrowUpDown className="size-3 opacity-40" />
                                                )}
                                            </button>
                                        ) : (
                                            column.header
                                        )}
                                    </th>
                                );
                            })}
                        </tr>
                    </thead>
                    <tbody className="divide-y divide-surface-100">
                        {rows.length === 0 ? (
                            <tr>
                                <td
                                    colSpan={columnCount}
                                    className="px-4 py-12"
                                >
                                    <div className="flex flex-col items-center text-center">
                                        <span className="flex size-10 items-center justify-center rounded-full bg-brand-faint text-brand">
                                            <EmptyIcon className="size-4" />
                                        </span>
                                        <p className="mt-3 font-semibold text-ink">
                                            {search
                                                ? `No results for “${search}”`
                                                : empty.title}
                                        </p>
                                        {!search && empty.description && (
                                            <p className="mt-1 max-w-sm text-xs text-ink-400">
                                                {empty.description}
                                            </p>
                                        )}
                                    </div>
                                </td>
                            </tr>
                        ) : (
                            rows.map((row) => {
                                const id = getRowId(row);
                                const isSelected = selectedIds.has(id);

                                return (
                                    <tr
                                        key={id}
                                        data-state={
                                            isSelected ? 'selected' : undefined
                                        }
                                        className={cn(
                                            'transition-colors hover:bg-surface-50 data-[state=selected]:bg-brand-faint/60',
                                            rowClassName?.(row),
                                        )}
                                    >
                                        {isSelectable && (
                                            <td className="w-10 px-4 py-3">
                                                <Checkbox
                                                    aria-label="Select row"
                                                    checked={isSelected}
                                                    onCheckedChange={(state) =>
                                                        toggleRow(
                                                            id,
                                                            state === true,
                                                        )
                                                    }
                                                />
                                            </td>
                                        )}
                                        {columns.map((column) => (
                                            <td
                                                key={column.key}
                                                className={cn(
                                                    'px-4 py-3 text-ink-700',
                                                    alignClass[
                                                        column.align ?? 'left'
                                                    ],
                                                    column.hideOnMobile &&
                                                        'hidden sm:table-cell',
                                                    column.className,
                                                )}
                                            >
                                                {column.cell
                                                    ? column.cell(row)
                                                    : toText(
                                                          readKey(
                                                              row,
                                                              column.key,
                                                          ),
                                                      )}
                                            </td>
                                        ))}
                                    </tr>
                                );
                            })
                        )}
                    </tbody>
                </table>
            </div>

            {total > 0 && (
                <div className="flex flex-wrap items-center justify-between gap-3 border-t border-surface-100 px-4 py-3 text-xs text-ink-500">
                    <span>
                        {isServer || pageSize === 0
                            ? `${total} ${total === 1 ? 'result' : 'results'}`
                            : `${(safePage - 1) * pageSize + 1}–${Math.min(safePage * pageSize, total)} of ${total}`}
                    </span>
                    {isServer ? (
                        <Pagination page={page} />
                    ) : (
                        pageCount > 1 && (
                            <div className="flex items-center gap-1">
                                <button
                                    type="button"
                                    onClick={() =>
                                        setClientPage(Math.max(1, safePage - 1))
                                    }
                                    disabled={safePage === 1}
                                    className="rounded-md p-1.5 hover:bg-surface-100 disabled:opacity-40"
                                    aria-label="Previous page"
                                >
                                    <ChevronLeft className="size-4" />
                                </button>
                                <span className="px-2 tabular-nums">
                                    Page {safePage} of {pageCount}
                                </span>
                                <button
                                    type="button"
                                    onClick={() =>
                                        setClientPage(
                                            Math.min(pageCount, safePage + 1),
                                        )
                                    }
                                    disabled={safePage === pageCount}
                                    className="rounded-md p-1.5 hover:bg-surface-100 disabled:opacity-40"
                                    aria-label="Next page"
                                >
                                    <ChevronRight className="size-4" />
                                </button>
                            </div>
                        )
                    )}
                </div>
            )}
        </section>
    );
}
