"use client";

import {
  PurchaseQcResult,
  PurchaseQCInput,
  StockInInput,
} from "@/app/api/po/actions";
import {
  Box,
  Card,
  CardContent,
  Grid,
  Stack,
  TextField,
  Tooltip,
  Typography,
} from "@mui/material";
import { Controller, useFormContext } from "react-hook-form";
import { useTranslation } from "react-i18next";
import StyledDataGrid from "../StyledDataGrid";
import { useCallback, useEffect, useMemo } from "react";
import {
  GridColDef,
  GridRowIdGetter,
  GridRowModel,
  useGridApiContext,
  GridRenderCellParams,
  GridRenderEditCellParams,
  useGridApiRef,
} from "@mui/x-data-grid";
import InputDataGrid from "../InputDataGrid";
import { TableRow } from "../InputDataGrid/InputDataGrid";
import TwoLineCell from "./TwoLineCell";
import QcSelect from "./QcSelect";
import { QcItemWithChecks } from "@/app/api/qc";
import { GridEditInputCell } from "@mui/x-data-grid";
import { StockInLine } from "@/app/api/po";
import { DatePicker, LocalizationProvider } from "@mui/x-date-pickers";
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
import { INPUT_DATE_FORMAT } from "@/app/utils/formatUtil";
import dayjs from "dayjs";
// 修改接口以支持 PickOrder 数据
import { GetPickOrderLineInfo } from "@/app/api/pickOrder/actions";

// change PurchaseQcResult to stock in entry props
interface Props {
  itemDetail: StockInLine | (GetPickOrderLineInfo & { pickOrderCode: string });
  // qc: QcItemWithChecks[];
  disabled: boolean;
}
type EntryError =
  | {
      [field in keyof StockInInput]?: string;
    }
  | undefined;

// type PoQcRow = TableRow<Partial<PurchaseQcResult>, EntryError>;

const StockInFormVer2: React.FC<Props> = ({
  // qc,
  itemDetail,
  disabled,
}) => {
  const {
    t,
    i18n: { language },
  } = useTranslation("purchaseOrder");
  const apiRef = useGridApiRef();
  const {
    register,
    formState: { errors, defaultValues, touchedFields },
    watch,
    control,
    setValue,
    getValues,
    reset,
    resetField,
    setError,
    clearErrors,
  } = useFormContext<StockInInput>();
  // console.log(itemDetail);

  useEffect(() => {
    console.log("triggered");
    // receiptDate default tdy
    setValue("receiptDate", dayjs().add(0, "month").format(INPUT_DATE_FORMAT));
    setValue("status", "received");
  }, [setValue]);

  useEffect(() => {
    console.log(errors);
  }, [errors]);

  const productionDate = watch("productionDate");
  const expiryDate = watch("expiryDate");
  const uom = watch("uom");

  useEffect(() => {
    console.log(uom);
    console.log(productionDate);
    console.log(expiryDate);
    if (expiryDate) clearErrors();
    if (productionDate) clearErrors();
  }, [expiryDate, productionDate, clearErrors]);

  // 检查是否为 PickOrder 数据
  const isPickOrderData = 'pickOrderCode' in itemDetail;

  // 获取 UOM 显示值
  const getUomDisplayValue = () => {
    if (isPickOrderData) {
      // PickOrder 数据
      const pickOrderItem = itemDetail as GetPickOrderLineInfo & { pickOrderCode: string };
      return pickOrderItem.uomDesc || (pickOrderItem as { uomCode?: string }).uomCode || '';
    } else {
      // StockIn 数据
      const stockInItem = itemDetail as StockInLine;
      return uom?.code || stockInItem.uom?.code || '';
    }
  };

  // 获取 Item 显示值
  const getItemDisplayValue = () => {
    if (isPickOrderData) {
      // PickOrder 数据
      const pickOrderItem = itemDetail as GetPickOrderLineInfo & { pickOrderCode: string };
      return pickOrderItem.itemCode || '';
    } else {
      // StockIn 数据
      const stockInItem = itemDetail as StockInLine;
      return stockInItem.itemNo || '';
    }
  };

  // 获取 Item Name 显示值
  const getItemNameDisplayValue = () => {
    if (isPickOrderData) {
      // PickOrder 数据
      const pickOrderItem = itemDetail as GetPickOrderLineInfo & { pickOrderCode: string };
      return pickOrderItem.itemName || '';
    } else {
      // StockIn 数据
      const stockInItem = itemDetail as StockInLine;
      return stockInItem.itemName || '';
    }
  };

  // 获取 Quantity 显示值
  const getQuantityDisplayValue = () => {
    if (isPickOrderData) {
      // PickOrder 数据
      const pickOrderItem = itemDetail as GetPickOrderLineInfo & { pickOrderCode: string };
      return pickOrderItem.requiredQty || 0;
    } else {
      // StockIn 数据
      const stockInItem = itemDetail as StockInLine;
      return stockInItem.acceptedQty || 0;
    }
  };

  return (
    <Grid container spacing={2}>
      <Grid item xs={12}>
        <Typography variant="h6" display="block" marginBlockEnd={1}>
          {t("stock in information")}
        </Typography>
      </Grid>
      <Grid item xs={6}>
        <TextField
          label={t("itemNo")}
          fullWidth
          {...(register as (name: string, opts?: object) => ReturnType<typeof register>)("itemNo", {
            required: "itemNo required!",
          })}
          value={getItemDisplayValue()}
          disabled={true}
        />
      </Grid>
      <Grid item xs={6}>
        <TextField
          label={t("itemName")}
          fullWidth
          {...register("itemName", {
            required: "itemName required!",
          })}
          value={getItemNameDisplayValue()}
          disabled={true}
        />
      </Grid>
      <Grid item xs={6}>
        <Controller
          name="productionDate"
          control={control}
          rules={{
            required: "productionDate required!",
          }}
          render={({ field }) => {
            return (
              <LocalizationProvider
                dateAdapter={AdapterDayjs}
                adapterLocale={`${language}-hk`}
              >
                <DatePicker
                  {...field}
                  sx={{ width: "100%" }}
                  label={t("productionDate")}
                  value={productionDate ? dayjs(productionDate) : undefined}
                  disabled={disabled}
                  onChange={(date) => {
                    console.log(date);
                    if (!date) return;
                    console.log(date.format(INPUT_DATE_FORMAT));
                    setValue("productionDate", date.format(INPUT_DATE_FORMAT));
                    // field.onChange(date);
                  }}
                  inputRef={field.ref}
                  slotProps={{
                    textField: {
                      // required: true,
                      error: Boolean(errors.productionDate?.message),
                      helperText: errors.productionDate?.message,
                    },
                  }}
                />
              </LocalizationProvider>
            );
          }}
        />
      </Grid>
      <Grid item xs={6}>
        <Controller
          name="expiryDate"
          control={control}
          rules={{
            required: "expiryDate required!",
          }}
          render={({ field }) => {
            return (
              <LocalizationProvider
                dateAdapter={AdapterDayjs}
                adapterLocale={`${language}-hk`}
              >
                <DatePicker
                  {...field}
                  sx={{ width: "100%" }}
                  label={t("expiryDate")}
                  value={expiryDate ? dayjs(expiryDate) : undefined}
                  disabled={disabled}
                  onChange={(date) => {
                    console.log(date);
                    if (!date) return;
                    console.log(date.format(INPUT_DATE_FORMAT));
                    setValue("expiryDate", date.format(INPUT_DATE_FORMAT));
                    // field.onChange(date);
                  }}
                  inputRef={field.ref}
                  slotProps={{
                    textField: {
                      // required: true,
                      error: Boolean(errors.expiryDate?.message),
                      helperText: errors.expiryDate?.message,
                    },
                  }}
                />
              </LocalizationProvider>
            );
          }}
        />
      </Grid>
      <Grid item xs={6}>
        <TextField
          label={t("receivedQty")}
          fullWidth
          {...register("receivedQty", {
            required: "receivedQty required!",
          })}
          value={getQuantityDisplayValue()}
          disabled={true}
        />
      </Grid>
      <Grid item xs={6}>
        <TextField
          label={t("uom")}
          fullWidth
          {...register("uom", {
            required: "uom required!",
          })}
          value={getUomDisplayValue()}
          disabled={true}
        />
      </Grid>
      <Grid item xs={6}>
        <TextField
          label={t("acceptedQty")}
          fullWidth
          {...register("acceptedQty", {
            required: "acceptedQty required!",
          })}
          value={getQuantityDisplayValue()}
          disabled={true}
          // disabled={disabled}
          // error={Boolean(errors.acceptedQty)}
          // helperText={errors.acceptedQty?.message}
        />
      </Grid>
      {/* <Grid item xs={4}>
        <TextField
          label={t("acceptedWeight")}
          fullWidth
          // {...register("acceptedWeight", {
          //   required: "acceptedWeight required!",
          // })}
          disabled={disabled}
          error={Boolean(errors.acceptedWeight)}
          helperText={errors.acceptedWeight?.message}
        />
      </Grid> */}
    </Grid>
  );
};
export default StockInFormVer2;
