import React, { useCallback } from 'react';
import {
  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 SearchItemWithQty {
  id: number;
  /** Unique search-row key: itemId + uomId */
  rowKey: string;
  label: string;
  qty: number | null;
  uomId?: number;
  uom?: string;
  currentStockBalance?: number;
  uomDesc?: string;
  targetDate?: string | null;
  groupId?: number | null;
}

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

interface SearchResultsTableProps {
  items: SearchItemWithQty[];
  selectedItemIds: (string | number)[];
  groups: Group[];
  onItemSelect: (rowKey: string, checked: boolean) => void;
  onQtyChange: (rowKey: string, qty: number | null) => void;
  onQtyBlur: (rowKey: string) => void;
  onGroupChange: (rowKey: string, groupId: string) => void;
  isItemInCreated: (itemId: number, uomId?: number) => boolean;
  pageNum: number;
  pageSize: number;
  onPageChange: (event: unknown, newPage: number) => void;
  onPageSizeChange: (event: React.ChangeEvent<HTMLInputElement>) => void;
}

/** FP-MTMS Version Checklist | Functions Ref. No. 31 | v1.0.1 | 2026-07-22 */
const SearchResultsTable: React.FC<SearchResultsTableProps> = ({
  items,
  selectedItemIds,
  groups,
  onItemSelect,
  onQtyChange,
  onGroupChange,
  onQtyBlur,
  isItemInCreated,
  pageNum,
  pageSize,
  onPageChange,
  onPageSizeChange,
}) => {
  const { t } = useTranslation("pickOrder");

  const startIndex = (pageNum - 1) * pageSize;
  const endIndex = startIndex + pageSize;
  const paginatedResults = items.slice(startIndex, endIndex);

  const handleQtyChange = useCallback((rowKey: string, value: string) => {
    if (value === "" || /^\d*\.?\d+$/.test(value)) {
      const numValue = value === "" ? null : Number(value);
      onQtyChange(rowKey, 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>
            {paginatedResults.length === 0 ? (
              <TableRow>
                <TableCell colSpan={12} align="center">
                  <Typography variant="body2" color="text.secondary">
                    {t("No data available")}
                  </Typography>
                </TableCell>
              </TableRow>
            ) : (
              paginatedResults.map((item) => {
                const rowKey = item.rowKey || `${item.id}_${item.uomId || 0}`;
                const inCreated = isItemInCreated(item.id, item.uomId);
                return (
                <TableRow key={rowKey}>
                  <TableCell padding="checkbox">
                    <Checkbox
                      checked={selectedItemIds.includes(rowKey) || inCreated}
                      onChange={(e) => onItemSelect(rowKey, e.target.checked)}
                      disabled={inCreated}
                    />
                  </TableCell>
                  <TableCell>
                    <Typography variant="body2">
                      {item.label.split(' - ')[1] || item.label}
                    </Typography>
                    <Typography variant="caption" color="textSecondary">
                      {item.label.split(' - ')[0] || ''}
                    </Typography>
                  </TableCell>
                  <TableCell>
                    <FormControl size="small" sx={{ minWidth: 120 }}>
                      <Select
                        value={item.groupId?.toString() || ""}
                        onChange={(e) => onGroupChange(rowKey, e.target.value)}
                        displayEmpty
                        disabled={inCreated}
                      >
                        <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"}
                      sx={{ fontWeight: item.currentStockBalance && item.currentStockBalance > 0 ? 'bold' : 'normal' }}
                    >
                      {item.currentStockBalance?.toLocaleString()||0}
                    </Typography>
                  </TableCell>
                  <TableCell align="right">
                    <Typography variant="body2">
                      {item.uomDesc || item.uom || "-"}
                    </Typography>
                  </TableCell>
                  <TableCell align="right">
                    <TextField
                      type="number"
                      size="small"
                      value={item.qty || ""}
                      onChange={(e) => handleQtyChange(rowKey, e.target.value)}
                      onBlur={() => onQtyBlur(rowKey)}
                      disabled={inCreated}
                      inputProps={{ 
                        min: 1,
                        max: item.currentStockBalance || 0,
                        step: 1,
                        style: { textAlign: 'center' }
                      }}
                      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 SearchResultsTable;
