/**
 * @ai-summary Reusable data grid component with selection and pagination
 * @ai-context Table display with checkbox selection, sorting, and error/loading states
 */

import React from 'react';
import {
  Box,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Checkbox,
  Paper,
  IconButton,
  Typography,
  TableSortLabel,
} from '@mui/material';
import { ChevronLeft, ChevronRight } from '@mui/icons-material';
import { EmptyState } from './EmptyState';
import { ErrorState } from './ErrorState';
import { AdminSkeleton } from './AdminSkeleton';

/**
 * Column definition for data grid
 */
export interface GridColumn<T = any> {
  field: keyof T | string;
  headerName: string;
  sortable?: boolean;
  width?: string | number;
  renderCell?: (row: T) => React.ReactNode;
}

/**
 * Props for AdminDataGrid component
 */
export interface AdminDataGridProps<T = any> {
  rows: T[];
  columns: GridColumn<T>[];
  selectedIds: Set<string>;
  onSelectChange: (id: string) => void;
  onSelectAll?: () => void;
  loading?: boolean;
  error?: Error | null;
  onRetry?: () => void;
  toolbar?: React.ReactNode;
  getRowId?: (row: T) => string;
  emptyMessage?: string;
  page?: number;
  onPageChange?: (page: number) => void;
  totalPages?: number;
}

/**
 * Data grid component with selection, sorting, and pagination
 *
 * @example
 * ```tsx
 * <AdminDataGrid
 *   rows={data}
 *   columns={[
 *     { field: 'name', headerName: 'Name', sortable: true },
 *     { field: 'createdAt', headerName: 'Created', renderCell: (row) => formatDate(row.createdAt) }
 *   ]}
 *   selectedIds={selected}
 *   onSelectChange={toggleItem}
 *   onSelectAll={toggleAll}
 * />
 * ```
 */
export function AdminDataGrid<T extends Record<string, any>>({
  rows,
  columns,
  selectedIds,
  onSelectChange,
  onSelectAll,
  loading = false,
  error = null,
  onRetry,
  toolbar,
  getRowId = (row) => row.id,
  emptyMessage = 'No data available',
  page = 0,
  onPageChange,
  totalPages = 1,
}: AdminDataGridProps<T>): React.ReactElement {
  // Loading state
  if (loading) {
    return (
      <Box>
        {toolbar}
        <AdminSkeleton.SkeletonRow count={5} />
      </Box>
    );
  }

  // Error state
  if (error) {
    return (
      <Box>
        {toolbar}
        <ErrorState error={error} onRetry={onRetry} />
      </Box>
    );
  }

  // Empty state
  if (rows.length === 0) {
    return (
      <Box>
        {toolbar}
        <EmptyState
          title="No Data"
          description={emptyMessage}
          icon={null}
        />
      </Box>
    );
  }

  const allSelected =
    rows.length > 0 && rows.every((row) => selectedIds.has(getRowId(row)));
  const someSelected =
    rows.some((row) => selectedIds.has(getRowId(row))) && !allSelected;

  return (
    <Box>
      {toolbar}

      <TableContainer component={Paper} sx={{ boxShadow: 1 }}>
        <Table>
          <TableHead>
            <TableRow>
              {/* Checkbox column */}
              <TableCell padding="checkbox">
                {onSelectAll && (
                  <Checkbox
                    indeterminate={someSelected}
                    checked={allSelected}
                    onChange={onSelectAll}
                    inputProps={{
                      'aria-label': 'select all',
                    }}
                  />
                )}
              </TableCell>

              {/* Data columns */}
              {columns.map((column) => (
                <TableCell
                  key={String(column.field)}
                  sx={{
                    width: column.width,
                    fontWeight: 600,
                  }}
                >
                  {column.sortable ? (
                    <TableSortLabel>
                      {column.headerName}
                    </TableSortLabel>
                  ) : (
                    column.headerName
                  )}
                </TableCell>
              ))}
            </TableRow>
          </TableHead>

          <TableBody>
            {rows.map((row) => {
              const rowId = getRowId(row);
              const isSelected = selectedIds.has(rowId);

              return (
                <TableRow
                  key={rowId}
                  selected={isSelected}
                  hover
                  sx={{
                    cursor: 'pointer',
                    '&.Mui-selected': {
                      backgroundColor: 'action.selected',
                    },
                  }}
                >
                  {/* Checkbox cell */}
                  <TableCell padding="checkbox">
                    <Checkbox
                      checked={isSelected}
                      onChange={() => onSelectChange(rowId)}
                      inputProps={{
                        'aria-label': `select row ${rowId}`,
                      }}
                      sx={{
                        minWidth: 44,
                        minHeight: 44,
                      }}
                    />
                  </TableCell>

                  {/* Data cells */}
                  {columns.map((column) => (
                    <TableCell key={String(column.field)}>
                      {column.renderCell
                        ? column.renderCell(row)
                        : row[column.field]}
                    </TableCell>
                  ))}
                </TableRow>
              );
            })}
          </TableBody>
        </Table>
      </TableContainer>

      {/* Pagination controls */}
      {onPageChange && totalPages > 1 && (
        <Box
          sx={{
            display: 'flex',
            justifyContent: 'flex-end',
            alignItems: 'center',
            mt: 2,
            gap: 1,
          }}
        >
          <Typography variant="body2" color="text.secondary">
            Page {page + 1} of {totalPages}
          </Typography>
          <IconButton
            onClick={() => onPageChange(page - 1)}
            disabled={page === 0}
            aria-label="previous page"
            sx={{ minWidth: 44, minHeight: 44 }}
          >
            <ChevronLeft />
          </IconButton>
          <IconButton
            onClick={() => onPageChange(page + 1)}
            disabled={page >= totalPages - 1}
            aria-label="next page"
            sx={{ minWidth: 44, minHeight: 44 }}
          >
            <ChevronRight />
          </IconButton>
        </Box>
      )}
    </Box>
  );
}
