"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 StockInFormOld: 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");

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

  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("invoiceNo")}
            fullWidth
            {...register("invoiceNo", {
              // required: "productLotNo required!",
            })}
            disabled={disabled}
            // error={Boolean(errors.productLotNo)}
            // helperText={errors.productLotNo?.message}
          />
        </Grid>
        <Grid item xs={4}>
          <TextField
            label={t("productLotNo")}
            fullWidth
            {...register("productLotNo", {
              // required: "productLotNo required!",
            })}
            disabled={disabled}
            error={Boolean(errors.productLotNo)}
            helperText={errors.productLotNo?.message}
          />
        </Grid>
        <Grid item xs={4}>
          <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={disabled}
                    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={4}>
          <TextField
            label={t("acceptedQty")}
            fullWidth
            {...register("acceptedQty", {
              required: "acceptedQty required!",
            })}
            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 item xs={4}>
          <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={4}>
          <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) => {
                      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>
      <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 StockInFormOld;
