"use client";

import {
  Box,
  Checkbox,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  TablePagination,
  Typography,
  Paper,
} from "@mui/material";
import { useMemo, useCallback } from "react";
import { useTranslation } from "react-i18next";
import { GetPickOrderInfoResponse, GetPickOrderLineInfo } from "@/app/api/pickOrder/actions";
import dayjs from "dayjs";

interface PickOrderDetailsTableProps {
  pickOrderDetails: GetPickOrderInfoResponse | null;
  detailLoading: boolean;
  selectedRowId: number | null;
  onRowSelect: (lineId: number) => void;
  onPageChange: (event: unknown, newPage: number) => void;
  onPageSizeChange: (event: React.ChangeEvent<HTMLInputElement>) => void;
  pageNum: number;
  pageSize: number;
}

const PickOrderDetailsTable: React.FC<PickOrderDetailsTableProps> = ({
  pickOrderDetails,
  detailLoading,
  selectedRowId,
  onRowSelect,
  onPageChange,
  onPageSizeChange,
  pageNum,
  pageSize,
}) => {
  const { t } = useTranslation("pickOrder");

  const prepareMainTableData = useMemo(() => {
    if (!pickOrderDetails) return [];
    
    return pickOrderDetails.pickOrders.flatMap((pickOrder) =>
      pickOrder.pickOrderLines.map((line) => {
        const availableQty = line.availableQty ?? 0;
        const balanceToPick = availableQty - line.requiredQty;
        
        //  Handle both string and array date formats from the optimized API
        let formattedTargetDate = 'N/A';
        if (pickOrder.targetDate) {
          if (typeof pickOrder.targetDate === 'string') {
            formattedTargetDate = dayjs(pickOrder.targetDate).format('YYYY-MM-DD');
          } else if (Array.isArray(pickOrder.targetDate)) {
            // Handle array format [2025, 9, 29, 0, 0] from optimized API
            const [year, month, day] = pickOrder.targetDate;
            formattedTargetDate = dayjs(`${year}-${month}-${day}`).format('YYYY-MM-DD');
          }
        }
        
        return {
          ...line,
          pickOrderCode: pickOrder.code,
          targetDate: formattedTargetDate,
          balanceToPick: balanceToPick,
          pickedQty: line.pickedQty, //  This now comes from the optimized API
          availableQty: availableQty,
        };
      })
    );
  }, [pickOrderDetails]);

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

  if (detailLoading) {
    return (
      <Box display="flex" justifyContent="center" alignItems="center" minHeight="200px">
        <Typography variant="body2" color="text.secondary">
          {t("Loading data...")}
        </Typography>
      </Box>
    );
  }

  if (!pickOrderDetails) {
    return (
      <Box display="flex" justifyContent="center" alignItems="center" minHeight="200px">
        <Typography variant="body2" color="text.secondary">
          {t("No data available")}
        </Typography>
      </Box>
    );
  }

  return (
    <>
      <TableContainer component={Paper}>
        <Table>
          <TableHead>
            <TableRow>
              <TableCell>{t("Selected")}</TableCell>
              <TableCell>{t("Pick Order Code")}</TableCell>
              <TableCell>{t("Item Code")}</TableCell>
              <TableCell>{t("Item Name")}</TableCell>
              <TableCell align="right">{t("Order Quantity")}</TableCell>
              <TableCell align="right">{t("Current Stock")}</TableCell>
              <TableCell align="right">{t("Qty Already Picked")}</TableCell>
              <TableCell align="right">{t("Stock Unit")}</TableCell>
              <TableCell align="right">{t("Target Date")}</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {paginatedMainTableData.length === 0 ? (
              <TableRow>
                <TableCell colSpan={9} align="center">
                  <Typography variant="body2" color="text.secondary">
                    {t("No data available")}
                  </Typography>
                </TableCell>
              </TableRow>
            ) : (
              paginatedMainTableData.map((line) => {
                const availableQty = line.availableQty ?? 0;
                const balanceToPick = Math.max(0, availableQty - line.requiredQty);
                const actualPickedQty = line.pickedQty ?? 0;
                
                return (
                  <TableRow
                    key={line.id}
                    sx={{
                      "& > *": { borderBottom: "unset" },
                      color: "black",
                      backgroundColor: selectedRowId === line.id ? "action.selected" : "inherit",
                      cursor: "pointer",
                      "&:hover": {
                        backgroundColor: "action.hover",
                      },
                    }}
                  >
                    <TableCell align="center" sx={{ width: "60px" }}>
                      <Checkbox
                        checked={selectedRowId === line.id}
                        onChange={(e) => {
                          if (e.target.checked) {
                            onRowSelect(line.id);
                          }
                        }}
                        onClick={(e) => e.stopPropagation()}
                      />
                    </TableCell>
                    <TableCell align="left">{line.pickOrderCode}</TableCell>
                    <TableCell align="left">{line.itemCode}</TableCell>
                    <TableCell align="left">{line.itemName}</TableCell>
                    <TableCell align="right">{line.requiredQty}</TableCell>
                    <TableCell align="right" sx={{ 
                      color: availableQty >= line.requiredQty ? 'success.main' : 'error.main',
                    }}>
                      {availableQty.toLocaleString()}
                    </TableCell>
                    <TableCell align="right">{actualPickedQty}</TableCell>
                    <TableCell align="right">{line.uomDesc}</TableCell>
                    <TableCell align="right">{line.targetDate}</TableCell>
                  </TableRow>
                );
              })
            )}
          </TableBody>
        </Table>
      </TableContainer>
      
      <TablePagination
        component="div"
        count={prepareMainTableData.length}
        page={pageNum}
        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 PickOrderDetailsTable;