"use client";

import {
  Box,
  Button,
  CircularProgress,
  Paper,
  Stack,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  TextField,
  Typography,
  TablePagination,
} from "@mui/material";
import { useCallback, useMemo } from "react";
import { useTranslation } from "react-i18next";

interface CombinedLotTableProps {
  combinedLotData: any[];
  combinedDataLoading: boolean;
  pickQtyData: Record<string, number>;
  paginationController: {
    pageNum: number;
    pageSize: number;
  };
  onPickQtyChange: (lotKey: string, value: number | string) => void;
  onSubmitPickQty: (lot: any) => void;
  onRejectLot: (lot: any) => void;
  onPageChange: (event: unknown, newPage: number) => void;
  onPageSizeChange: (event: React.ChangeEvent<HTMLInputElement>) => void;
}

//  Simple helper function to check if item is completed
const isItemCompleted = (lot: any) => {
  const actualPickQty = Number(lot.actualPickQty) || 0;
  const requiredQty = Number(lot.requiredQty) || 0;
  
  return lot.stockOutLineStatus === 'completed' || 
         (actualPickQty > 0 && requiredQty > 0 && actualPickQty >= requiredQty);
};

const isItemRejected = (lot: any) => {
  return lot.stockOutLineStatus === 'rejected';
};

const CombinedLotTable: React.FC<CombinedLotTableProps> = ({
  combinedLotData,
  combinedDataLoading,
  pickQtyData,
  paginationController,
  onPickQtyChange,
  onSubmitPickQty,
  onRejectLot,
  onPageChange,
  onPageSizeChange,
}) => {
  const { t } = useTranslation("pickOrder");

  //  Paginated data
  const paginatedLotData = useMemo(() => {
    const startIndex = paginationController.pageNum * paginationController.pageSize;
    const endIndex = startIndex + paginationController.pageSize;
    return combinedLotData.slice(startIndex, endIndex);
  }, [combinedLotData, paginationController]);

  if (combinedDataLoading) {
    return (
      <Box display="flex" justifyContent="center" alignItems="center" minHeight="200px">
        <CircularProgress size={40} />
      </Box>
    );
  }

  return (
    <>
      <TableContainer component={Paper}>
        <Table>
          <TableHead>
            <TableRow>
              <TableCell>{t("Pick Order Code")}</TableCell>
              <TableCell>{t("Item Code")}</TableCell>
              <TableCell>{t("Item Name")}</TableCell>
              <TableCell>{t("Lot No")}</TableCell>
              {/* <TableCell>{t("Expiry Date")}</TableCell> */}
              <TableCell>{t("Location")}</TableCell>
              
              <TableCell align="right">{t("Current Stock")}</TableCell>
              <TableCell align="right">{t("Lot Required Pick Qty")}</TableCell>
              <TableCell align="right">{t("Qty Already Picked")}</TableCell>
              <TableCell align="right">{t("Lot Actual Pick Qty")}</TableCell>
              <TableCell>{t("Stock Unit")}</TableCell>
              <TableCell align="center">{t("Submit")}</TableCell>
              <TableCell align="center">{t("Reject")}</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {paginatedLotData.length === 0 ? (
              <TableRow>
                <TableCell colSpan={13} align="center">
                  <Typography variant="body2" color="text.secondary">
                    {t("No data available")}
                  </Typography>
                </TableCell>
              </TableRow>
            ) : (
              paginatedLotData.map((lot: any) => {
                const lotKey = `${lot.pickOrderLineId}-${lot.lotId}`;
                const currentPickQty = pickQtyData[lotKey] ?? '';
                const isCompleted = isItemCompleted(lot);
                const isRejected = isItemRejected(lot);
                
                //  Green text color for completed items
                const textColor = isCompleted ? 'success.main' : isRejected ? 'error.main' : 'inherit';
                
                return (
                  <TableRow 
                    key={lotKey}
                    sx={{
                      '&:hover': {
                        backgroundColor: 'action.hover',
                      },
                    }}
                  >
                    <TableCell sx={{ color: textColor }}>{lot.pickOrderCode}</TableCell>
                    <TableCell sx={{ color: textColor }}>{lot.itemCode}</TableCell>
                    <TableCell sx={{ color: textColor }}>{lot.itemName}</TableCell>
                    <TableCell sx={{ color: textColor }}>{lot.lotNo}</TableCell>
                    {/* <TableCell sx={{ color: textColor }}>
                      {lot.expiryDate ? dayjs(lot.expiryDate).format(OUTPUT_DATE_FORMAT) : 'N/A'}
                    </TableCell>
                    */}
                    <TableCell sx={{ color: textColor }}>{lot.location}</TableCell>
                    
                    <TableCell align="right" sx={{ color: textColor }}>{lot.availableQty}</TableCell>
                    <TableCell align="right" sx={{ color: textColor }}>{lot.requiredQty}</TableCell>
                    <TableCell align="right" sx={{ color: textColor }}>{lot.actualPickQty || 0}</TableCell>
                    <TableCell align="right">
                      <TextField
                        type="number"
                        value={currentPickQty}
                        onChange={(e) => {
                          onPickQtyChange(lotKey, e.target.value);
                        }}
                        onFocus={(e) => {
                          e.target.select();
                        }}
                        inputProps={{ 
                          min: 0, 
                          max: lot.availableQty,
                          step: 0.01
                        }}
                        disabled={
                          isCompleted || 
                          isRejected ||
                          lot.lotAvailability === 'expired' || 
                          lot.lotAvailability === 'status_unavailable'
                        }
                        sx={{ 
                          width: '80px',
                          '& .MuiInputBase-input': {
                            textAlign: 'right',
                          }
                        }}
                      />
                    </TableCell>
                    <TableCell sx={{ color: textColor }}>{lot.stockUnit}</TableCell>
                    <TableCell align="center">
                      <Button
                        variant="contained"
                        size="small"
                        disabled={isCompleted || isRejected || !currentPickQty || currentPickQty <= 0}
                        onClick={() => onSubmitPickQty(lot)}
                        sx={{
                          backgroundColor: isCompleted ? 'success.main' : 'primary.main',
                          color: 'white',
                          '&:disabled': {
                            backgroundColor: 'grey.300',
                            color: 'grey.500',
                          },
                        }}
                      >
                        {isCompleted ? t("Completed") : t("Submit")}
                      </Button>
                    </TableCell>
                    <TableCell align="center">
                      <Button
                        variant="outlined"
                        size="small"
                        color="error"
                        disabled={isCompleted || isRejected}
                        onClick={() => onRejectLot(lot)}
                        sx={{
                          '&:disabled': {
                            borderColor: 'grey.300',
                            color: 'grey.500',
                          },
                        }}
                      >
                        {t("Reject")}
                      </Button>
                    </TableCell>
                  </TableRow>
                );
              })
            )}
          </TableBody>
        </Table>
      </TableContainer>
      
      <TablePagination
        component="div"
        count={combinedLotData.length}
        page={paginationController.pageNum}
        rowsPerPage={paginationController.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 CombinedLotTable;