import { Fragment, type FormEvent, type ReactNode } from 'react';
import { Button } from './Button';

export type DataTableColumn<T> = {
    align?: 'left' | 'center' | 'right';
    key: string;
    label: string;
    render: (row: T, index: number) => ReactNode;
    width?: string;
};

export type DataTablePagination = {
    currentPage: number;
    from: number | null;
    lastPage: number;
    perPage: number;
    to: number | null;
    total: number;
};

type DataTableProps<T> = {
    columns: DataTableColumn<T>[];
    emptyState: ReactNode;
    onPageChange: (page: number) => void;
    onPerPageChange: (perPage: number) => void;
    onSearch: (event: FormEvent<HTMLFormElement>) => void;
    perPageOptions?: number[];
    pagination: DataTablePagination;
    rows: T[];
    renderExpandedRow?: (row: T, index: number) => ReactNode;
    rowKey?: (row: T, index: number) => string | number;
    search: string;
    searchId?: string;
    searchPlaceholder?: string;
    setSearch: (value: string) => void;
};

export function DataTable<T>({
    columns,
    emptyState,
    onPageChange,
    onPerPageChange,
    onSearch,
    perPageOptions = [10, 25, 50, 100],
    pagination,
    rows,
    renderExpandedRow,
    rowKey = (_, index) => index,
    search,
    searchId = 'data-table-search',
    searchPlaceholder = 'Search...',
    setSearch,
}: DataTableProps<T>) {
    const firstPage = Math.max(
        1,
        Math.min(pagination.currentPage - 2, pagination.lastPage - 4),
    );
    const lastPage = Math.min(pagination.lastPage, firstPage + 4);

    return (
        <>
            <div className="datatable-toolbar">
                <form className="datatable-search" onSubmit={onSearch}>
                    <label className="visually-hidden" htmlFor={searchId}>
                        Search table
                    </label>
                    <input
                        id={searchId}
                        onChange={(event) => setSearch(event.target.value)}
                        placeholder={searchPlaceholder}
                        type="search"
                        value={search}
                    />
                    <Button icon="⌕" type="submit">
                        Search
                    </Button>
                </form>
                <label className="datatable-per-page">
                    <span>Show</span>
                    <select
                        aria-label="Rows per page"
                        onChange={(event) =>
                            onPerPageChange(Number(event.target.value))
                        }
                        value={pagination.perPage}
                    >
                        {perPageOptions.map((option) => (
                            <option key={option} value={option}>
                                {option}
                            </option>
                        ))}
                    </select>
                    <span>entries</span>
                </label>
            </div>
            {rows.length === 0 ? (
                emptyState
            ) : (
                <div className="data-table-wrapper">
                    <table className="data-table">
                        <colgroup>
                            {columns.map((column) => (
                                <col
                                    key={column.key}
                                    style={{
                                        width:
                                            column.key === 'number' ||
                                            column.key === 'no'
                                                ? '4%'
                                                : column.width,
                                    }}
                                />
                            ))}
                        </colgroup>
                        <thead>
                            <tr>
                                {columns.map((column) => (
                                    <th
                                        className={`data-table-align-${column.align ?? (column.key === 'actions' ? 'right' : 'left')}${column.key === 'number' || column.key === 'no' ? ' data-table-number-column' : ''}`}
                                        key={column.key}
                                        scope="col"
                                    >
                                        {column.label}
                                    </th>
                                ))}
                            </tr>
                        </thead>
                        <tbody>
                            {rows.map((row, index) => {
                                const expanded = renderExpandedRow?.(
                                    row,
                                    index,
                                );

                                return (
                                    <Fragment key={rowKey(row, index)}>
                                        <tr>
                                            {columns.map((column) => (
                                                <td
                                                    className={`data-table-align-${column.align ?? (column.key === 'actions' ? 'right' : 'left')}${column.key === 'number' || column.key === 'no' ? ' data-table-number-column' : ''}`}
                                                    key={column.key}
                                                >
                                                    {column.render(row, index)}
                                                </td>
                                            ))}
                                        </tr>
                                        {expanded ? (
                                            <tr className="data-table-expanded-row">
                                                <td colSpan={columns.length}>
                                                    {expanded}
                                                </td>
                                            </tr>
                                        ) : null}
                                    </Fragment>
                                );
                            })}
                        </tbody>
                    </table>
                </div>
            )}
            <div className="datatable-footer">
                <p>
                    Showing {pagination.from ?? 0} to {pagination.to ?? 0} of{' '}
                    {pagination.total} entries
                </p>
                <nav
                    aria-label="Table pagination"
                    className="datatable-pagination"
                >
                    <Button
                        disabled={pagination.currentPage === 1}
                        onClick={() => onPageChange(pagination.currentPage - 1)}
                    >
                        <span aria-hidden="true">←</span> Previous
                    </Button>
                    {Array.from(
                        { length: Math.max(0, lastPage - firstPage + 1) },
                        (_, index) => firstPage + index,
                    ).map((page) => (
                        <Button
                            aria-current={
                                page === pagination.currentPage
                                    ? 'page'
                                    : undefined
                            }
                            className={
                                page === pagination.currentPage ? 'active' : ''
                            }
                            key={page}
                            onClick={() => onPageChange(page)}
                        >
                            <span aria-hidden="true">{page}</span>
                        </Button>
                    ))}
                    <Button
                        disabled={
                            pagination.currentPage === pagination.lastPage
                        }
                        onClick={() => onPageChange(pagination.currentPage + 1)}
                    >
                        Next <span aria-hidden="true">→</span>
                    </Button>
                </nav>
            </div>
        </>
    );
}
