import React, { useCallback } from 'react';
import {
  Box,
  Typography,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
  Checkbox,
  TextField,
  TablePagination,
  FormControl,
  Select,
  MenuItem,
} from '@mui/material';
import { useTranslation } from 'react-i18next';
import { OUTPUT_DATE_FORMAT } from '@/app/utils/formatUtil';
import dayjs from 'dayjs';

interface CreatedItem {
  itemId: number;
  itemName: string;
  itemCode: string;
  qty: number;
  uom: string;
  uomId: number;
  uomDesc: string;
  isSelected: boolean;
  currentStockBalance?: number;
  targetDate?: string | null;
  groupId?: number | null;
}

interface Group {
  id: number;
  name: string;
  targetDate: string;
}

interface CreatedItemsTableProps {
  items: CreatedItem[];
  groups: Group[];
  onItemSelect: (itemId: number, checked: boolean) => void;
  onQtyChange: (itemId: number, qty: number) => void;
  onGroupChange: (itemId: number, groupId: string) => void;
  pageNum: number;
  pageSize: number;
  onPageChange: (event: unknown, newPage: number) => void;
  onPageSizeChange: (event: React.ChangeEvent<HTMLInputElement>) => void;
}

const CreatedItemsTable: React.FC<CreatedItemsTableProps> = ({
  items,
  groups,
  onItemSelect,
  onQtyChange,
  onGroupChange,
  pageNum,
  pageSize,
  onPageChange,
  onPageSizeChange,
}) => {
  const { t } = useTranslation("pickOrder");

  // Calculate pagination
  const startIndex = (pageNum - 1) * pageSize;
  const endIndex = startIndex + pageSize;
  const paginatedItems = items.slice(startIndex, endIndex);

  const handleQtyChange = useCallback((itemId: number, value: string) => {
    const numValue = Number(value);
    if (!isNaN(numValue) && numValue >= 1) {
      onQtyChange(itemId, numValue);
    }
  }, [onQtyChange]);

  return (
    <>
      <TableContainer component={Paper}>
        <Table>
          <TableHead>
            <TableRow>
              <TableCell padding="checkbox" sx={{ width: '80px', minWidth: '80px' }}>
                {t("Selected")}
              </TableCell>
              <TableCell>
                {t("Item")}
              </TableCell>
              <TableCell>
                {t("Group")}
              </TableCell>
              <TableCell align="right">
                {t("Current Stock")}
              </TableCell>
              <TableCell align="right">
                {t("Stock Unit")}
              </TableCell>
              <TableCell align="right">
                {t("Order Quantity")}
              </TableCell>
              <TableCell align="right">
                {t("Target Date")}
              </TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {paginatedItems.length === 0 ? (
              <TableRow>
                <TableCell colSpan={12} align="center">
                  <Typography variant="body2" color="text.secondary">
                    {t("No created items")}
                  </Typography>
                </TableCell>
              </TableRow>
            ) : (
              paginatedItems.map((item) => (
                <TableRow key={item.itemId}>
                  <TableCell padding="checkbox">
                    <Checkbox
                      checked={item.isSelected}
                      onChange={(e) => onItemSelect(item.itemId, e.target.checked)}
                    />
                  </TableCell>
                  <TableCell>
                    <Typography variant="body2">{item.itemName}</Typography>
                    <Typography variant="caption" color="textSecondary">
                      {item.itemCode}
                    </Typography>
                  </TableCell>
                  <TableCell>
                    <FormControl size="small" sx={{ minWidth: 120 }}>
                      <Select
                        value={item.groupId?.toString() || ""}
                        onChange={(e) => onGroupChange(item.itemId, e.target.value)}
                        displayEmpty
                      >
                        <MenuItem value="">
                          <em>{t("No Group")}</em>
                        </MenuItem>
                        {groups.map((group) => (
                          <MenuItem key={group.id} value={group.id.toString()}>
                            {group.name}
                          </MenuItem>
                        ))}
                      </Select>
                    </FormControl>
                  </TableCell>
                  <TableCell align="right">
                    <Typography 
                      variant="body2" 
                      color={item.currentStockBalance && item.currentStockBalance > 0 ? "success.main" : "error.main"}
                    >
                      {item.currentStockBalance?.toLocaleString() || 0}
                    </Typography>
                  </TableCell>
                  <TableCell align="right">
                    <Typography variant="body2">{item.uomDesc}</Typography>
                  </TableCell>
                  <TableCell align="right">
                    <TextField
                      type="number"
                      size="small"
                      value={item.qty || ""}
                      onChange={(e) => handleQtyChange(item.itemId, e.target.value)}
                      inputProps={{ 
                        min: 1,
                        step: 1,
                        style: { textAlign: 'right' }
                      }}
                      sx={{ 
                        width: '80px',
                        '& .MuiInputBase-input': {
                          textAlign: 'center',
                          cursor: 'text'
                        }
                      }}
                    />
                  </TableCell>
                  <TableCell align="right">
                    <Typography variant="body2">
                      {item.targetDate ? dayjs(item.targetDate).format(OUTPUT_DATE_FORMAT) : "-"}
                    </Typography>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </TableContainer>
      
      <TablePagination
        component="div"
        count={items.length}
        page={(pageNum - 1)}
        rowsPerPage={pageSize}
        onPageChange={onPageChange}
        onRowsPerPageChange={onPageSizeChange}
        rowsPerPageOptions={[10, 25, 50]}
        labelRowsPerPage={t("Rows per page")}
        labelDisplayedRows={({ from, to, count }) => 
          `${from}-${to} of ${count !== -1 ? count : `more than ${to}`}`
        }
      />
    </>
  );
};

export default CreatedItemsTable;