"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";
// change PurchaseQcResult to stock in entry props
interface Props {
  itemDetail: StockInLine;
  // 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");

    //// TODO : Add Checking ////
  // Check if dates are input
    // if (data.productionDate === undefined || data.productionDate == null) {
    //   validationErrors.push("請輸入生產日期！");
    // }
    // if (data.expiryDate === undefined || data.expiryDate == null) {
    //   validationErrors.push("請輸入到期日！");
    // }

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

  useEffect(() => {
    console.log("%c StockInForm itemDetail update: ", "color: brown", itemDetail);
  }, [itemDetail]);

  return (
    <Grid container justifyContent="flex-start" alignItems="flex-start">
      {/* <Grid item xs={12}>
        <Typography variant="h6" display="block" marginBlockEnd={1}>
          {t("Stock In Detail")}
        </Typography>
      </Grid> */}
      <Grid
        container
        justifyContent="flex-start"
        alignItems="flex-start"
        spacing={2}
        sx={{ mt: 0.5 }}
      >
        <Grid item xs={6}>
          <TextField
            label={t("dnNo")}
            fullWidth
            {...register("dnNo", {
              // required: "productLotNo required!",
            })}
            disabled={disabled}
            // error={Boolean(errors.productLotNo)}
            // helperText={errors.productLotNo?.message}
          />
        </Grid>
        <Grid item xs={6}>
          <TextField
            label={t("itemName")}
            fullWidth
            {...register("itemName", {
              // required: "productLotNo required!",
            })}
            disabled={true}
            // error={Boolean(errors.productLotNo)}
            // helperText={errors.productLotNo?.message}
          />
        </Grid>
        <Grid item xs={6}>
          <TextField
            label={t("PO No.")}
            fullWidth
            {...register("poCode", {
              // required: "productLotNo required!",
            })}
            disabled={true}
            // error={Boolean(errors.productLotNo)}
            // helperText={errors.productLotNo?.message}
          />
        </Grid>
        <Grid item xs={6}>
          <Controller
            control={control}
            name="receiptDate"
            rules={{ required: true }}
            render={({ field }) => {
              return (
                <LocalizationProvider
                  dateAdapter={AdapterDayjs}
                  adapterLocale={`${language}-hk`}
                >
                  <DatePicker
                    {...field}
                    sx={{ width: "100%" }}
                    label={t("receiptDate")}
                    value={dayjs(watch("receiptDate"))}
                    disabled={true}
                    onChange={(date) => {
                      if (!date) return;
                      //  setValue("receiptDate", date.format(INPUT_DATE_FORMAT));
                      field.onChange(date);
                    }}
                    inputRef={field.ref}
                    slotProps={{
                      textField: {
                        // required: true,
                        error: Boolean(errors.receiptDate?.message),
                        helperText: errors.receiptDate?.message,
                      },
                    }}
                  />
                </LocalizationProvider>
              );
            }}
          />
        </Grid>
        <Grid item xs={6}>
        <TextField
            label={t("Supplier")}
            fullWidth
            {...register("supplier", {
              // required: "productLotNo required!",
            })}
            disabled={true}
          />
        </Grid>
        <Grid item xs={6}>
          <TextField
            label={t("productLotNo")}
            fullWidth
            {...register("productLotNo", {
              // required: "productLotNo required!",
            })}
            disabled={disabled}
            error={Boolean(errors.productLotNo)}
            helperText={errors.productLotNo?.message}
          />
        </Grid>
        <Grid item xs={6}>
          <Controller
            control={control}
            name="productionDate"
            // rules={{ required: !Boolean(expiryDate) }}
            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) => {
                      if (!date) return;
                      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}>
          <TextField
            label={t("qty")}
            fullWidth
            {...register("qty", {
              required: "qty required!",
            })}
            disabled={true}
          />
        </Grid>
        <Grid item xs={6}>
          <Controller
            control={control}
            name="expiryDate"
            // rules={{ required: !Boolean(productionDate) }}
            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) => {
                      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!",
            })}
            disabled={true}
          />
        </Grid>
        <Grid item xs={6}>
          <TextField
            label={t("uom")}
            fullWidth
            {...register("uom.code", {
              required: "uom required!",
            })}
            // value={uom?.code}
            disabled={true}
          />
        </Grid>
        <Grid item xs={6}>
          <TextField
            label={t("acceptedQty")}
            fullWidth
            disabled={true}
            {...register("acceptedQty", {
              required: "acceptedQty required!",
            })}
            // 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>
      <Grid
        container
        justifyContent="flex-start"
        alignItems="flex-start"
        spacing={2}
        sx={{ mt: 0.5 }}
      >
        {/* <Grid item xs={12}>
          <InputDataGrid<PurchaseQCInput, PurchaseQcResult, EntryError>
            apiRef={apiRef}
            checkboxSelection={false}
            _formKey={"qcCheck"}
            columns={columns}
            validateRow={validationTest}
          />
        </Grid> */}
      </Grid>
    </Grid>
  );
};
export default StockInFormVer2;
