"use client";
// 修改为 PickOrder 相关的导入
import { GetPickOrderLineInfo } from "@/app/api/pickOrder/actions";
import { QcItemWithChecks } from "@/app/api/qc";
import { PurchaseQcResult } from "@/app/api/po/actions";
import {
  Box,
  Button,
  Grid,
  Modal,
  ModalProps,
  Stack,
  Typography,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
} from "@mui/material";
import { Dispatch, SetStateAction, useCallback, useEffect, useState } from "react";
import { FormProvider, SubmitHandler, useForm } from "react-hook-form";
import { useTranslation } from "react-i18next";
import { dummyQCData, QcData } from "../PoDetail/dummyQcTemplate";
import { submitDialogWithWarning } from "../Swal/CustomAlerts";

const style = {
  position: "absolute",
  top: "50%",
  left: "50%",
  transform: "translate(-50%, -50%)",
  bgcolor: "background.paper",
  pt: 5,
  px: 5,
  pb: 10,
  display: "block",
  width: { xs: "60%", sm: "60%", md: "60%" },
};

// 修改接口定义
interface CommonProps extends Omit<ModalProps, "children"> {
  itemDetail: GetPickOrderLineInfo & { 
    pickOrderCode: string;
    qcResult?: PurchaseQcResult[] 
  };
  setItemDetail: Dispatch<
    SetStateAction<
      | (GetPickOrderLineInfo & {
          pickOrderCode: string;
          warehouseId?: number;
        })
      | undefined
    >
  >;
  qc?: QcItemWithChecks[];
  warehouse?: any[];
}

interface Props extends CommonProps {
  itemDetail: GetPickOrderLineInfo & { 
    pickOrderCode: string;
    qcResult?: PurchaseQcResult[] 
  };
}

// 修改组件名称
const PickQcStockInModalVer2: React.FC<Props> = ({
  open,
  onClose,
  itemDetail,
  setItemDetail,
  qc,
  warehouse,
}) => {
  console.log(warehouse);
  // 修改翻译键
  const {
    t,
    i18n: { language },
  } = useTranslation("pickOrder");
  
  const [qcItems, setQcItems] = useState(dummyQCData)
  const formProps = useForm<any>({
    defaultValues: {
      ...itemDetail,
    },
  });
  
  const closeHandler = useCallback<NonNullable<ModalProps["onClose"]>>(
    (...args) => {
      onClose?.(...args);
    },
    [onClose],
  );

  // QC submission handler
  const onSubmitQc = useCallback<SubmitHandler<any>>(
    async (data, event) => {
      console.log("QC Submission:", event!.nativeEvent);
      
      // Get QC data from the shared form context
      const qcAccept = data.qcAccept;
      const acceptQty = data.acceptQty;
      
      // Validate QC data
      const validationErrors : string[] = [];
      // Check if all QC items have results
      const itemsWithoutResult = qcItems.filter(item => item.isPassed === undefined);
      if (itemsWithoutResult.length > 0) {
        validationErrors.push(`${t("QC items without result")}: ${itemsWithoutResult.map(item => item.qcItem).join(', ')}`);
      }

      // Check if failed items have failed quantity
      const failedItemsWithoutQty = qcItems.filter(item => 
        item.isPassed === false && (!item.failedQty || item.failedQty <= 0)
      );
      if (failedItemsWithoutQty.length > 0) {
        validationErrors.push(`${t("Failed items must have failed quantity")}: ${failedItemsWithoutQty.map(item => item.qcItem).join(', ')}`);
      }

      // Check if accept quantity is valid
      if (acceptQty === undefined || acceptQty <= 0) {
        validationErrors.push("Accept quantity must be greater than 0");
      }

      if (validationErrors.length > 0) {
        console.error("QC Validation failed:", validationErrors);
        alert(`未完成品檢: ${validationErrors}`);
        return;
      }

      const qcData = {
        qcAccept: qcAccept,
        acceptQty: acceptQty,
        qcItems: qcItems.map(item => ({
          id: item.id,
          qcItem: item.qcItem,
          qcDescription: item.qcDescription,
          isPassed: item.isPassed,
          failedQty: (item.failedQty && !item.isPassed) || 0,
          remarks: item.remarks || ''
        }))
      };

      console.log("QC Data for submission:", qcData);
      // await submitQcData(qcData);

      if (!qcData.qcItems.every((qc) => qc.isPassed) && qcData.qcAccept) {
        submitDialogWithWarning(() => {
          console.log("QC accepted with failed items");
          onClose();
        }, t, {title:"有不合格檢查項目，確認接受收貨？", confirmButtonText: "Confirm", html: ""});
        return;
      }

      if (qcData.qcAccept) {
        console.log("QC accepted");
        onClose();
      } else {
        console.log("QC rejected");
        onClose();
      }
    },
    [qcItems, onClose, t],
  );

  const handleQcItemChange = useCallback((index: number, field: keyof QcData, value: any) => {
    setQcItems(prev => prev.map((item, i) => 
      i === index ? { ...item, [field]: value } : item
    ));
  }, []);

  return (
    <>
      <FormProvider {...formProps}>
        <Modal open={open} onClose={closeHandler}>
          <Box
            sx={{
              ...style,
              padding: 2,
              maxHeight: "90vh",
              overflowY: "auto",
              marginLeft: 3,
              marginRight: 3,
            }}
          >
            <Grid container justifyContent="flex-start" alignItems="flex-start">
              <Grid item xs={12}>
                <Typography variant="h6" display="block" marginBlockEnd={1}>
                  GroupA - {itemDetail.pickOrderCode}
                </Typography>
                <Typography variant="body2" color="text.secondary" marginBlockEnd={2}>
                  記錄探測溫度的時間,請在1小時內完成出庫,以保障食品安全 監察方法、日闸檢查、嗅覺檢查和使用適當的食物温度計椒鱼食物溫度是否符合指標
                </Typography>
              </Grid>
              
              {/* QC 表格 */}
              <Grid item xs={12}>
                <TableContainer component={Paper}>
                  <Table>
                    <TableHead>
                      <TableRow>
                        <TableCell>QC模板代號</TableCell>
                        <TableCell>檢查項目</TableCell>
                        <TableCell>QC Result</TableCell>
                        <TableCell>Failed Qty</TableCell>
                        <TableCell>Remarks</TableCell>
                      </TableRow>
                    </TableHead>
                    <TableBody>
                      {qcItems.map((item, index) => (
                        <TableRow key={item.id}>
                          <TableCell>{item.id}</TableCell>
                          <TableCell>{item.qcDescription}</TableCell>
                          <TableCell>
                            <select
                              value={item.isPassed === undefined ? '' : item.isPassed ? 'pass' : 'fail'}
                              onChange={(e) => handleQcItemChange(index, 'isPassed', e.target.value === 'pass')}
                            >
                              <option value="">Select</option>
                              <option value="pass">Pass</option>
                              <option value="fail">Fail</option>
                            </select>
                          </TableCell>
                          <TableCell>
                            <input
                              type="number"
                              value={item.failedQty || 0}
                              onChange={(e) => handleQcItemChange(index, 'failedQty', parseInt(e.target.value) || 0)}
                              disabled={item.isPassed !== false}
                            />
                          </TableCell>
                          <TableCell>
                            <input
                              type="text"
                              value={item.remarks || ''}
                              onChange={(e) => handleQcItemChange(index, 'remarks', e.target.value)}
                            />
                          </TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                </TableContainer>
              </Grid>
              
              {/* 按钮 */}
              <Grid item xs={12} sx={{ mt: 2 }}>
                <Stack direction="row" justifyContent="flex-end" gap={1}>
                  <Button
                    variant="contained"
                    color="success"
                    onClick={formProps.handleSubmit(onSubmitQc)}
                  >
                    QC Accept
                  </Button>
                  <Button
                    variant="contained"
                    color="warning"
                    onClick={() => {
                      console.log("Sort to accept");
                      onClose();
                    }}
                  >
                    Sort to Accept
                  </Button>
                  <Button
                    variant="contained"
                    color="error"
                    onClick={() => {
                      console.log("Reject and pick another lot");
                      onClose();
                    }}
                  >
                    Reject and Pick Another Lot
                  </Button>
                </Stack>
              </Grid>
            </Grid>
          </Box>
        </Modal>
      </FormProvider>
    </>
  );
};

export default PickQcStockInModalVer2;