"use client";

import {
  StockInInput,
} from "@/app/api/stockIn/actions";
import {
  Box,
  Card,
  CardContent,
  Grid,
  Stack,
  TextField,
  Tooltip,
  Typography,
  Button,
} from "@mui/material";
import { Controller, useFormContext } from "react-hook-form";
import { useTranslation } from "react-i18next";
import StyledDataGrid from "../StyledDataGrid";
import { useCallback, useEffect, useMemo, useState } 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 { QcItemWithChecks } from "@/app/api/qc";
import { GridEditInputCell } 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 { INPUT_DATE_FORMAT, OUTPUT_DATE_FORMAT } from "@/app/utils/formatUtil";
import dayjs from "dayjs";
import CalculateExpiryDateModal from "./CalculateExpiryDateModal";
import { InputAdornment } from "@mui/material";
import { dayjsToDateString } from "@/app/utils/formatUtil";


// 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 FgStockInForm: 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 [openModal, setOpenModal] = useState<boolean>(false);
  const [openExpDatePicker, setOpenExpDatePicker] = useState<boolean>(false);
  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]);

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

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

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

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 }}
      >
        {putawayMode && (
          <Grid item xs={6}>
            <TextField
              label={t("joCode")}
              fullWidth
              {...register("productLotNo", {
                // required: "productLotNo required!",
              })}
              sx={compactFields ? undefined : textfieldSx}
              disabled={true}
            />
          </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>
        
        {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}>
          {putawayMode ? (
            <TextField
              label={t("stockLotNo")}
              fullWidth
              {...register("lotNo", {
                // required: "productLotNo required!",
              })}
              sx={compactFields ? undefined : textfieldSx}
              disabled={true}
              error={Boolean(errors.productLotNo)}
              helperText={errors.productLotNo?.message}
            />) : (

            <TextField
              label={t("stockLotNo")}
              fullWidth
              {...register("productLotNo", {
                // required: "productLotNo required!",
              })}
              sx={compactFields ? undefined : textfieldSx}
              disabled={true}
              error={Boolean(errors.productLotNo)}
              helperText={errors.productLotNo?.message}
            />)
            }
        </Grid>
        <Grid item xs={6}>
          <Controller
            control={control}
            name="productionDate"
            render={({ field }) => {
              return (
                <LocalizationProvider
                  dateAdapter={AdapterDayjs}
                  adapterLocale={`${language}-hk`}
                >
                  <DatePicker
                    {...field}
                    sx={compactFields ? { width: '100%' } : textfieldSx}
                    label={t("productionDate")}
                    value={productionDate ? dayjs(productionDate) : undefined}
                    format={OUTPUT_DATE_FORMAT}
                    disabled={disabled}
                    onChange={(date) => {
                      if (!date) return;
                      setValue(
                        "productionDate",
                        date.format(INPUT_DATE_FORMAT),
                      );
                    }}
                    inputRef={field.ref}
                    slotProps={{
                      textField: {
                        fullWidth: true,
                        error: Boolean(errors.productionDate?.message),
                        helperText: errors.productionDate?.message,
                      },
                    }}
                  />
                </LocalizationProvider>
              );
            }}
          />
        </Grid>
        {/* {putawayMode || (<>
        {/* {putawayMode || (<>
          <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={compactFields ? undefined : textfieldSx}
                      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!",
              })}
              sx={compactFields ? undefined : textfieldSx}
              disabled={true}
            />
          </Grid></>
        )} */}
        <Grid item xs={6}>
        <Controller
  control={control}
  name="expiryDate"
  render={({ field }) => {
    const expiryDateValue = watch("expiryDate");
    return (
      <LocalizationProvider
        dateAdapter={AdapterDayjs}
        adapterLocale={`${language}-hk`}
      >
        <DatePicker
          {...field}
          sx={compactFields ? { width: '100%' } : textfieldSx}
          label={t("expiryDate")}
          value={expiryDateValue ? dayjs(expiryDateValue) : null} // Use null instead of undefined
          format={OUTPUT_DATE_FORMAT}
          disabled={disabled}
          onChange={(date) => {
            if (!date) {
              setValue("expiryDate", ""); 
              return;
            }
            setValue("expiryDate", date.format(INPUT_DATE_FORMAT));
          }}
          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>
                  ),
                })
              },
              error: Boolean(errors.expiryDate?.message),
              helperText: errors.expiryDate?.message,
              onClick: () => setOpenExpDatePicker(true),
            },
          }}
        />
      </LocalizationProvider>
    );
  }}
/>
        </Grid>
        {/* <Grid item xs={6}>
          {putawayMode ? (
            <TextField
              label={t("acceptedQty")}
              fullWidth
              sx={compactFields ? undefined : textfieldSx}
              disabled={true}
              value={itemDetail.acceptedQty}
              // disabled={true}
              // disabled={disabled}
              // error={Boolean(errors.acceptedQty)}
              // helperText={errors.acceptedQty?.message}
            />
          ) : (
            <TextField
              label={t("receivedQty")}
              fullWidth
              {...register("receivedQty", {
                required: "receivedQty required!",
              })}
              sx={compactFields ? undefined : textfieldSx}
              disabled={true}
            />
          )}
        </Grid> */}
        <Grid item xs={6}>
          <TextField
            label={t("salesUnit")}
            fullWidth
            {...register("uom.udfudesc", {
              required: "uom required!",
            })}
            // value={uom?.code}
            sx={compactFields ? undefined : textfieldSx}
            disabled={true}
          />
        </Grid>
        {putawayMode ? (<>
          <Grid item xs={3}>
            <TextField
              label={t("processedQty")}
              fullWidth
              sx={compactFields ? undefined : textfieldSx}
              disabled={true}
              value={itemDetail.putAwayLines?.reduce((sum, p) => sum + p.qty, 0) ?? 0}
            />
          </Grid>
          <Grid item xs={3}>
            <TextField
              label={t("acceptedQty")}
              fullWidth
              sx={compactFields ? undefined : textfieldSx}
              disabled={true}
              {...register("acceptedQty", {
                required: "acceptedQty required!",
              })}
            />
        </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 FgStockInForm;
