"use client";

import {
  StockInInput,
} from "@/app/api/stockIn/actions";
import {
  Box,
  Button,
  Card,
  CardContent,
  Grid,
  InputAdornment,
  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, useState, useMemo } from "react";
import {
  useGridApiRef,
} from "@mui/x-data-grid";
import { StockInLine } from "@/app/api/stockIn";
import { DatePicker, LocalizationProvider } from "@mui/x-date-pickers";
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
import { dayjsToDateString, INPUT_DATE_FORMAT, OUTPUT_DATE_FORMAT } from "@/app/utils/formatUtil";
import dayjs from "dayjs";
import CalculateExpiryDateModal from "./CalculateExpiryDateModal";
// change PurchaseQcResult to stock in entry props
interface Props {
  itemDetail: StockInLine;
  // qc: QcItemWithChecks[];
  disabled: boolean;
  putawayMode?: boolean;
  /** When true, use compact field sizing to match Putaway Detail (上架詳情) section. */
  compactFields?: boolean;
}
type EntryError =
  | {
      [field in keyof StockInInput]?: string;
    }
  | undefined;

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

const textfieldSx = {
  width: "100%",
  "& .MuiInputBase-root": {
    // height: "120", // Scales with root font size
    height: "5rem", // Scales with root font size
  },
  "& .MuiInputBase-input": {
    height: "100%",
    boxSizing: "border-box",
    padding: "0.75rem",
    fontSize: 30,
  },
  "& .MuiInputLabel-root": {
    fontSize: 30,
    transform: "translate(14px, 1.2rem) scale(1)",
    "&.MuiInputLabel-shrink": {
      fontSize: 24,
      transform: "translate(14px, -0.5rem) scale(1)",
    },
    // [theme.breakpoints.down("sm")]: {
    //   fontSize: "1rem",
    //   transform: "translate(14px, 1.5rem) scale(1)",
    //   "&.MuiInputLabel-shrink": {
    //     fontSize: "0.875rem",
    //   },
    // },
  },
};

const StockInForm: React.FC<Props> = ({
  // qc,
  itemDetail,
  disabled,
  putawayMode = false,
  compactFields = false,
}) => {
  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");

  const [openModal, setOpenModal] = useState<boolean>(false);
  const [openExpDatePicker, setOpenExpDatePicker] = useState<boolean>(false);

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

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

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

  const handleOpenModal = useCallback(() => {
    setOpenModal(true);
  }, []);

  const handleOnModalClose = useCallback(() => {
    setOpenExpDatePicker(false);
    setOpenModal(false);
  }, []);

  const handleReturnExpiryDate = useCallback((result: dayjs.Dayjs) => {
    if (result) {
      setValue("expiryDate", dayjsToDateString(result));
    }
  }, []);

  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={compactFields ? 1 : 2}
        sx={{ mt: 0.5 }}
      >
        <Grid item xs={6}>
          <TextField
            label={t("dnNo")}
            fullWidth
            {...register("dnNo", {
              // required: "productLotNo required!",
            })}
            sx={compactFields ? undefined : textfieldSx}
            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!",
            })}
            sx={compactFields ? undefined : textfieldSx}
            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!",
            })}
            sx={compactFields ? undefined : textfieldSx}
            disabled={true}
            // error={Boolean(errors.productLotNo)}
            // helperText={errors.productLotNo?.message}
          />
        </Grid>
        {putawayMode || (
          <>
          <Grid item xs={6}>
            <Controller
              control={control}
              name="receiptDate"
              rules={{ required: true }}
              render={({ field }) => {
                return (
                  <LocalizationProvider
                    dateAdapter={AdapterDayjs}
                    adapterLocale={`${language}-hk`}
                  >
                    <DatePicker
                      {...field}
                      sx={compactFields ? { width: '100%' } : textfieldSx}
                      label={t("receiptDate")}
                      value={dayjs(watch("receiptDate"))}
                      format={OUTPUT_DATE_FORMAT}
                      disabled={true}
                      onChange={(date) => {
                        if (!date) return;
                        //  setValue("receiptDate", date.format(INPUT_DATE_FORMAT));
                        field.onChange(date);
                      }}
                      inputRef={field.ref}
                      slotProps={{
                        textField: {
                          fullWidth: true,
                          // 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!",
              })}
              sx={compactFields ? undefined : textfieldSx}
              disabled={true}
            />
          </Grid>
          </>
        )}
        <Grid item xs={6}>
          {putawayMode ? (
            <TextField
              label={t("stockLotNo")}
              fullWidth
              {...register("lotNo", {
                // required: "productLotNo required!",
              })}
              sx={compactFields ? undefined : textfieldSx}
              disabled={disabled}
              error={Boolean(errors.productLotNo)}
              helperText={errors.productLotNo?.message}
            />) : (

          <TextField
            label={t("productLotNo")}
            fullWidth
            {...register("productLotNo", {
              // required: "productLotNo required!",
            })}
            sx={compactFields ? undefined : textfieldSx}
            disabled={disabled}
            error={Boolean(errors.productLotNo)}
            helperText={errors.productLotNo?.message}
          />)}
        </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={compactFields ? { width: '100%' } : textfieldSx}
                    label={t("expiryDate")}
                    value={expiryDate ? dayjs(expiryDate) : undefined}
                    format={OUTPUT_DATE_FORMAT}
                    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}
                    open={openExpDatePicker && !openModal}
                    onOpen={() => setOpenExpDatePicker(true)}
                    onClose={() => setOpenExpDatePicker(false)}
                    slotProps={{
                      textField: {
                        fullWidth: true,
                        InputProps: {
                          ...(!disabled && {endAdornment: (
                            <InputAdornment position="end">
                              <Button
                                type="button"
                                variant="contained"
                                color="primary"
                                size="small"
                                sx={{
                                  fontSize: compactFields ? '0.875rem' : '24px',
                                  whiteSpace: 'nowrap',
                                  flexShrink: 0,
                                }}
                                onClick={handleOpenModal}
                              >
                                {t("Calculate Expiry Date")}
                              </Button>
                            </InputAdornment>
                          ),})
                        },
                        // required: true,
                        error: Boolean(errors.expiryDate?.message),
                        helperText: errors.expiryDate?.message,
                        onClick: () => setOpenExpDatePicker(true),
                      },
                    }}
                  />
                </LocalizationProvider>
              );
            }}
          />
        </Grid>
        {putawayMode || (<>
          <Grid item xs={3}>
            <TextField
              label={t("receivedQty")}
              fullWidth
              {...register("receivedQty", {
                required: "receivedQty required!",
              })}
              sx={compactFields ? undefined : textfieldSx}
              disabled={true}
            />
          </Grid>
          <Grid item xs={3}>
            <TextField
              label={t("qty")}
              fullWidth
              {...register("qty", {
                required: "qty required!",
              })}
              sx={compactFields ? undefined : textfieldSx}
              disabled={true}
            />
          </Grid></>
        )}
        {putawayMode ? (
          <>
            <Grid item xs={6}>
              <TextField
                label={"本批次庫存收貨數量"}
                fullWidth
                sx={compactFields ? undefined : textfieldSx}
                disabled={true}
                value={`${itemDetail.acceptedQty ?? 0} (${itemDetail.stockUomDesc ?? ""})`}
              />
            </Grid>
            <Grid item xs={6}>
              <TextField
                label={"本批次採購收貨數量"}
                fullWidth
                sx={compactFields ? undefined : textfieldSx}
                disabled={true}
                value={`${itemDetail.purchaseAcceptedQty ?? 0} (${itemDetail.purchaseUomDesc ?? ""})`}
              />
            </Grid>
            <Grid item xs={6}>
              <TextField
                label={"已上架數量"}
                fullWidth
                sx={compactFields ? undefined : textfieldSx}
                disabled={true}
                value={`${itemDetail.putAwayLines?.reduce((sum, p) => sum + (p.stockQty ?? 0), 0) ?? 0} (${itemDetail.stockUomDesc ?? ""})`}
              />
            </Grid>
          </>
        ) : (
          <Grid item xs={6}>
            <TextField
              label={t("acceptedQty")}
              fullWidth
              sx={compactFields ? undefined : textfieldSx}
              disabled={true}
              {...register("acceptedQty", {
                required: "acceptedQty required!",
              })}
            />
          </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>
    
    <CalculateExpiryDateModal
      open={openModal}
      onClose={handleOnModalClose}
      onSubmit={handleReturnExpiryDate}
      textfieldSx={compactFields ? undefined : textfieldSx}
    />
    </>
  );
};
export default StockInForm;
