import React from 'react';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Checkbox } from '@/components/ui/checkbox';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle
} from '@/components/ui/alert-dialog';

const DataTable = ({
  // Data and columns
  data,
  columns,
  idField = 'id', // New prop to specify which field to use as ID

  // Selection
  selectable = false,
  selectedIds = [],
  onSelectIds,

  renderRowActions,

  // Pagination
  onPageChange,

  // Loading state
  loading = false,

  // Delete dialog
  deleteDialogTitle = 'Delete Items',
  deleteDialogDescription = 'Are you sure you want to delete the selected items? This action cannot be undone.',
  onDelete
}) => {
  const [showDeleteDialog, setShowDeleteDialog] = React.useState(false);

  // Get ID from row using the specified idField
  const getRowId = React.useCallback((row) => {
    return row[idField];
  }, [idField]);

  const handleSelectAll = React.useCallback((checked) => {
    if (!onSelectIds) return;
    if (checked) {
      onSelectIds(data.content.map(item => getRowId(item)));
    } else {
      onSelectIds([]);
    }
  }, [data.content, onSelectIds, getRowId]);

  const handleSelectItem = React.useCallback((id, checked) => {
    if (!onSelectIds) return;
    if (checked) {
      onSelectIds([...selectedIds, id]);
    } else {
      onSelectIds(selectedIds.filter(selectedId => selectedId !== id));
    }
  }, [selectedIds, onSelectIds]);

  const handlePageChange = React.useCallback((page) => {
    // Reset selections when changing pages
    if (onSelectIds) {
      onSelectIds([]);
    }
    onPageChange(page);
  }, [onSelectIds, onPageChange]);

  if (loading) {
    return (
        <Card>
          <CardContent className="flex justify-center items-center h-48">
            Loading...
          </CardContent>
        </Card>
    );
  }

  return (
      <div>
        <div className="rounded-md border">
          <Table>
            <TableHeader>
              <TableRow>
                {selectable && (
                    <TableHead className="w-[50px]">
                      <Checkbox
                          checked={selectedIds.length === data.content.length && data.content.length > 0}
                          onCheckedChange={handleSelectAll}
                      />
                    </TableHead>
                )}
                {columns.map((column) => (
                    <TableHead key={column.key}>{column.label}</TableHead>
                ))}
                {renderRowActions && <TableHead className="text-center">Actions</TableHead>}
              </TableRow>
            </TableHeader>
            <TableBody>
              {data.content.map((row) => {
                const rowId = getRowId(row);
                return (
                    <TableRow key={rowId}>
                      {selectable && (
                          <TableCell>
                            <Checkbox
                                checked={selectedIds.includes(rowId)}
                                onCheckedChange={(checked) => handleSelectItem(rowId, checked)}
                            />
                          </TableCell>
                      )}
                      {columns.map((column) => (
                          <TableCell key={`${rowId}-${column.key}`}>
                            {column.render ? column.render(row[column.key], row) : row[column.key]}
                          </TableCell>
                      ))}
                      {renderRowActions && (
                          <TableCell className="text-center">
                            {renderRowActions(row)}
                          </TableCell>
                      )}
                    </TableRow>
                );
              })}
            </TableBody>
          </Table>
        </div>

        {onPageChange && (
            <div className="flex justify-between items-center mt-4">
              <div className="text-sm text-gray-500">
                전체 {data.totalElements} 중 {data.numberOfElements} 표시
              </div>
              <div className="flex items-center gap-2">
                <Button
                    variant="outline"
                    onClick={() => handlePageChange(0)}
                    disabled={data.first}
                    size="sm"
                >
                  {'<<'}
                </Button>
                <Button
                    variant="outline"
                    onClick={() => handlePageChange(data.number - 1)}
                    disabled={data.first}
                    size="sm"
                >
                  이전
                </Button>
                <div className="flex items-center gap-1">
                  {Array.from({ length: data.totalPages }, (_, i) => (
                      <Button
                          key={`page-${i}`}
                          variant={i === data.number ? "default" : "outline"}
                          size="sm"
                          onClick={() => handlePageChange(i)}
                          className="w-8"
                      >
                        {i + 1}
                      </Button>
                  ))}
                </div>
                <Button
                    variant="outline"
                    onClick={() => handlePageChange(data.number + 1)}
                    disabled={data.last}
                    size="sm"
                >
                  다음
                </Button>
                <Button
                    variant="outline"
                    onClick={() => handlePageChange(data.totalPages - 1)}
                    disabled={data.last}
                    size="sm"
                >
                  {'>>'}
                </Button>
              </div>
            </div>
        )}

        {onDelete && (
            <AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
              <AlertDialogContent>
                <AlertDialogHeader>
                  <AlertDialogTitle>{deleteDialogTitle}</AlertDialogTitle>
                  <AlertDialogDescription>
                    {deleteDialogDescription}
                  </AlertDialogDescription>
                </AlertDialogHeader>
                <AlertDialogFooter>
                  <AlertDialogCancel>Cancel</AlertDialogCancel>
                  <AlertDialogAction onClick={() => {
                    onDelete?.();
                    setShowDeleteDialog(false);
                  }}>Delete</AlertDialogAction>
                </AlertDialogFooter>
              </AlertDialogContent>
            </AlertDialog>
        )}
      </div>
  );
};

export default DataTable;
