import { useState, type ReactNode } from 'react';
import { DataTable, type DataTablePageEvent } from 'primereact/datatable';
import { InputText } from 'primereact/inputtext';
import { PAGINATION } from '@/core/constants/app.constants';
import './BaseCrudTable.scss';

interface Props<T> {
  value: T[];
  loading?: boolean;
  totalRecords?: number;
  dataKey?: string;
  globalFilterFields?: string[];
  paginator?: boolean;
  rowsPerPage?: number;
  emptyMessage?: string;
  selectionMode?: 'single' | 'multiple' | 'checkbox' | 'radiobutton';
  exportFilename?: string;
  toolbarLeft?: ReactNode;
  toolbarRight?: ReactNode;
  onRowSelect?: (row: T) => void;
  onPage?: (event: DataTablePageEvent) => void;
  children: ReactNode;
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
export default function BaseCrudTable<T extends Record<string, any>>({
  value,
  loading = false,
  totalRecords,
  dataKey = 'id',
  globalFilterFields,
  paginator = true,
  rowsPerPage = PAGINATION.defaultPageSize,
  emptyMessage = '데이터가 없습니다.',
  toolbarLeft,
  toolbarRight,
  onRowSelect,
  onPage,
  children,
}: Props<T>) {
  const [globalFilter, setGlobalFilter] = useState('');

  return (
    <div className="crud-table">
      <div className="crud-table__toolbar">
        <div className="crud-table__toolbar-left">{toolbarLeft}</div>
        <div className="crud-table__toolbar-right">
          {toolbarRight}
          {globalFilterFields && globalFilterFields.length > 0 && (
            <span className="p-input-icon-left">
              <i className="pi pi-search" />
              <InputText
                value={globalFilter}
                onChange={(e) => setGlobalFilter(e.target.value)}
                placeholder="검색..."
                size={1}
              />
            </span>
          )}
        </div>
      </div>

      <DataTable
        value={value as any} // eslint-disable-line @typescript-eslint/no-explicit-any
        loading={loading}
        dataKey={dataKey}
        paginator={paginator}
        rows={rowsPerPage}
        rowsPerPageOptions={[...PAGINATION.pageSizeOptions]}
        totalRecords={totalRecords}
        globalFilter={globalFilter}
        globalFilterFields={globalFilterFields}
        removableSort
        stripedRows
        showGridlines
        size="small"
        className="crud-table__datatable"
        onRowSelect={(e) => onRowSelect?.(e.data as T)}
        onPage={onPage}
        emptyMessage={emptyMessage}
      >
        {children}
      </DataTable>
    </div>
  );
}
