import { Grid } from "../../../../components/grid/Grid";
import { SimpleTable } from "../../../../components/simple-table/SimpleTable";
import {
  Button,
  FormControl,
  InputLabel,
  MenuItem,
  Select,
  Typography
} from "@mui/material";
import React, { useEffect, useState } from "react";
import { useFormik } from "formik";
import { Yup } from "../../../../lib/yup/yup";
import { PropTypes } from "prop-types";
import { SPACING } from "../../../../data/spacing";
import { ImageUpload } from "../../../../components/image-upload/ImageUpload";
import { fixBase64 } from "../../../../utils/toBase64";
import { useDispatch, useSelector } from "react-redux";
import { slaughterEnterBarWeight } from "../../../slaughter-house/services/slaughter-enter-bar-weight";
import { DRAWER } from "../../../../lib/redux/slices/appSlice";
import { useContext } from "react";
import { AppContext } from "../../../../contexts/AppContext";
import { slaughterUpdateBarWeight } from "../../../slaughter-house/services/slaughter-update-bar-weight";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { NumberInput } from "../../../../components/number-format-custom/NumberFormatCustom";
import { resizeImage } from "../../../../utils/resizeImage";
import { slaughterGetExlusiveKillers } from "../../services/slaughterGetExlusiveKillers";
import { isValidIndexWeight } from "../../../../utils/isValidIndexWeight";
import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith";

export const SlaughterEnterBarItem = ({
  data,
  reqKey,
  // checkKey,
  isRejected,
  item,
  realNumber,
  updateTable
}) => {
  const [openNotif] = useContext(AppContext);

  const [weightWithBarImages, setWeightWithBarImages] = React.useState([]);
  const [weightWithBarImg, setWeightWithBarImg] = React.useState(null);
  const { weightRange } = useSelector((state) => state.provinceSlice);
  const selectedSubUser = useSelector(
    (state) => state.userSlice.selectedSubUser
  );
  const weightWithBarImgHandler = (imageList) => {
    setWeightWithBarImages(imageList);
    formik.setFieldValue("weightWithBarImg", "");
    setWeightWithBarImg(null);

    if (imageList[0]) {
      const file = imageList[0]?.file;
      resizeImage(file, (resizedDataUrl) => {
        const optimizedBase64 = fixBase64(resizedDataUrl);
        setWeightWithBarImg(optimizedBase64);
        formik.setFieldValue("weightWithBarImg", optimizedBase64);
      });
    } else {
      formik.setFieldValue("weightWithBarImg", "");
    }
  };
  const [barWeight, setBarWeight] = useState(0);

  const dispatch = useDispatch();

  let numFirstWeight = 0;

  const formik = useFormik({
    initialValues: {
      weightWithoutBar: "",
      weightWithBar: "",
      weightWithBarImg: "",
      loadRealNumber: item.acceptedRealQuantity
        ? item.acceptedRealQuantity
        : realNumber,
      exploitedCarcass: 0
    },
    validationSchema: Yup.object({
      weightWithoutBar: Yup.number()
        // .test(
        //   "weightWithoutBar",
        //   "وزن بدون بار نباید بزرگتر از وزن با بار باشد!",
        //   (val, context) => {
        //     return (
        //       context.originalValue && context.originalValue < numLastWeight
        //     );
        //   }
        // )
        .min(0, "عدد منفی وارد نکنید!")
        .required("این فیلد اجباری است!")
        .typeError("لطفا عدد وارد کنید!"),
      weightWithBar: Yup.number()
        .test(
          "len",
          "وزن با بار باید بیشتر از وزن بدون بار باشد!",
          (val, context) => {
            return (
              context.originalValue && context.originalValue > numFirstWeight
            );
          }
        )
        .required("این فیلد اجباری است!")
        .typeError("لطفا وزن را وارد کنید!"),
      weightWithBarImg: Yup.string().required("این فیلد اجباری است!"),
      loadRealNumber: Yup.number()
        .required("این فیلد اجباری است!")
        .typeError("لطفا عدد وارد کنید!"),
      exploitedCarcass: Yup.number()
        .required("این فیلد اجباری است!")
        .typeError("لطفا عدد وارد کنید!")
    })
  });

  numFirstWeight = Number(formik.values.weightWithoutBar);

  useEffect(() => {
    formik.validateForm();
  }, []);

  useEffect(() => {
    // fill the form if req is rejected
    if (isRejected || item) {
      formik.setFieldValue(
        "weightWithoutBar",
        item.assignmentInfo?.carWeightWithoutLoad
      );
      formik.setFieldValue(
        "weightWithBar",
        item.assignmentInfo?.carWeightWithLoad
      );
    }
  }, []);

  useEffect(() => {
    const numFirstWeight = Number(formik.values.weightWithoutBar);
    const numLastWeight = Number(formik.values.weightWithBar);
    if (numLastWeight) {
      if (numFirstWeight < numLastWeight) {
        setBarWeight(numLastWeight - numFirstWeight);
      } else {
        setBarWeight(0);
      }
    }
  }, [formik.values.weightWithoutBar, formik.values.weightWithBar]);

  const [exclusiveKillers, setExclusiveKillers] = useState();
  const [selectedOption, setSelectedOption] = useState();

  const shouldShowExclusiveKillerSelect = !(
    item?.killer && item?.type === "public"
  );

  useEffect(() => {
    if (!shouldShowExclusiveKillerSelect) return;
    dispatch(
      slaughterGetExlusiveKillers({
        role_key: checkPathStartsWith("slaughter")
          ? selectedSubUser?.key || ""
          : ""
      })
    ).then((r) => {
      setExclusiveKillers(r.payload.data);
    });
  }, [selectedSubUser?.key, shouldShowExclusiveKillerSelect]);

  const handleOptionChange = (event) => {
    setSelectedOption(event?.target.value);
  };

  const buttonText =
    getRoleFromUrl() !== "KillHouse"
      ? "ثبت اطلاعات بجای کشتارگاه"
      : "ثبت اطلاعات";

  return (
    <Grid container direction={"column"}>
      <Grid>
        <SimpleTable
          columns={[
            "کدبار",
            "مرغداری",
            "تعداد تخصیصی (قطعه)",
            "تعداد تحویلی (قطعه)",
            "وزن تحویلی (کیلوگرم)",
            "میانگین وزن تحویلی هر قطعه (کیلوگرم)",
            "سن",
            "تاریخ کشتار",
            "کشتارکن اختصاصی"
          ]}
          data={data}
        />
      </Grid>
      <Grid
        container
        direction={"column"}
        alignItems={"start"}
        my={SPACING.SMALL}
        gap={SPACING.SMALL}
      >
        <Grid container gap={SPACING.TINY}>
          <Typography variant={"body2"} color={"primary"} fontWeight={"bold"}>
            اطلاعات بار با کدبار {data[0][0]} را وارد کنید.
          </Typography>
          {(isRejected || item.assignmentInfo) && (
            <Typography variant={"body2"} color={"error"} fontWeight={"bold"}>
              توجه: حتما باید اطلاعات جدید دوباره وارد گردد. (سند ماشین و وزن
              ماشین)
            </Typography>
          )}

          {isRejected && (
            <>
              <Typography variant={"body2"} color={"error"} fontWeight={"bold"}>
                ({"اطلاعات بار توسط واحد مالی استان رد شده است."})
              </Typography>
              {/* <Typography variant={"body2"} color={"error"} fontWeight={"bold"}>
                دلیل رد: {item?.barInfo?.message}
              </Typography> */}
            </>
          )}
        </Grid>
        <Grid container direction={"column"} gap={SPACING.SMALL}>
          <Grid container gap={SPACING.SMALL} alignItems={"normal"}>
            <Grid container direction={"column"}>
              <NumberInput
                allowLeadingZeros
                thousandSeparator=","
                id="weightWithoutBar"
                label="وزن ماشین بدون بار باسکول شده"
                variant="outlined"
                value={formik.values.weightWithoutBar}
                error={
                  formik.touched.weightWithoutBar
                    ? Boolean(formik.errors.weightWithoutBar)
                    : null
                }
                onChange={formik.handleChange}
                onBlur={formik.handleBlur}
                helperText={
                  formik.touched.weightWithoutBar &&
                  Boolean(formik.errors.weightWithoutBar)
                    ? formik.errors.weightWithoutBar
                    : null
                }
              />
              <ImageUpload
                onChange={weightWithBarImgHandler}
                images={weightWithBarImages}
                maxNumber={1}
                title={"بارگذاری سند"}
              />
              {item.assignmentInfo.imageWithBar && (
                <Grid
                  container
                  direction="column"
                  alignItems="center"
                  mt={SPACING.SMALL}
                >
                  <a href={item.assignmentInfo.imageWithBar}>
                    <img
                      src={item.assignmentInfo.imageWithBar}
                      width="100"
                      height={"100"}
                      alt="killHouseImageWithLoad"
                    />
                  </a>
                  <Typography variant="caption">
                    سند ماشین با بار بارگذاری شده
                  </Typography>
                </Grid>
              )}
            </Grid>
            <Grid container direction={"column"}>
              <NumberInput
                allowLeadingZeros
                thousandSeparator=","
                id="weightWithBar"
                label="وزن ماشین با بار باسکول شده"
                variant="outlined"
                value={formik.values.weightWithBar}
                error={
                  formik.touched.weightWithBar
                    ? Boolean(formik.errors.weightWithBar)
                    : null
                }
                onChange={formik.handleChange}
                onBlur={formik.handleBlur}
                helperText={
                  formik.touched.weightWithBar &&
                  Boolean(formik.errors.weightWithBar)
                    ? formik.errors.weightWithBar
                    : null
                }
              />
            </Grid>

            <Grid container direction={"column"}>
              <NumberInput
                allowLeadingZeros
                thousandSeparator=","
                style={{ width: 130 }}
                id="loadRealNumber"
                label="تعداد واقعی بارگیری"
                variant="outlined"
                value={formik.values.loadRealNumber}
                error={
                  formik.touched.loadRealNumber
                    ? Boolean(formik.errors.loadRealNumber)
                    : null
                }
                onChange={formik.handleChange}
                onBlur={formik.handleBlur}
                helperText={
                  formik.touched.loadRealNumber &&
                  Boolean(formik.errors.loadRealNumber)
                    ? formik.errors.loadRealNumber
                    : null
                }
              />
            </Grid>

            <Grid container direction={"column"}>
              <NumberInput
                disabled={true}
                allowLeadingZeros
                thousandSeparator=","
                style={{ width: 150 }}
                id="exploitedCarcass"
                label="لاشه استحصالی"
                variant="outlined"
                value={formik.values.exploitedCarcass}
                error={
                  formik.touched.exploitedCarcass
                    ? Boolean(formik.errors.exploitedCarcass)
                    : null
                }
                onChange={formik.handleChange}
                onBlur={formik.handleBlur}
                helperText={
                  formik.touched.exploitedCarcass &&
                  Boolean(formik.errors.exploitedCarcass)
                    ? formik.errors.exploitedCarcass
                    : null
                }
              />
            </Grid>

            <Grid container direction={"column"}>
              <Typography
                color={(prop) => prop.palette.grey["A700"]}
                variant={"caption"}
              >
                وزن بار وارد شده
              </Typography>
              <Typography variant={"button"}>{barWeight} کیلوگرم </Typography>
            </Grid>
            {shouldShowExclusiveKillerSelect &&
              exclusiveKillers?.length > 1 && (
                <Grid
                  container
                  direction={"column"}
                  gap={1}
                  alignItems="center"
                >
                  <FormControl>
                    <InputLabel id="demo-simple-select-label">
                      انتخاب کشتارکن
                    </InputLabel>

                    <Select
                      label="کشتارکن"
                      // disabled={disableSelect}
                      // label="Select Option"
                      value={selectedOption}
                      onChange={handleOptionChange}
                    >
                      {exclusiveKillers?.map((item, i) => {
                        return (
                          <MenuItem key={i} value={item?.key}>
                            {item?.name}
                          </MenuItem>
                        );
                      })}
                    </Select>
                  </FormControl>
                  <Grid>
                    <Typography sx={{ fontSize: "12px" }} color="red">
                      ویرایش کشتارکن اختصاصی (اختیاری)
                    </Typography>
                  </Grid>
                </Grid>
              )}
            <Grid container direction={"column"} alignItems="center">
              <Button
                variant={"contained"}
                disabled={!formik.isValid}
                onClick={() => {
                  const thenCallback = (r) => {
                    if (r.payload.error) {
                      openNotif({
                        vertical: "top",
                        horizontal: "center",
                        msg: r.payload.error,
                        severity: "error"
                      });
                    } else {
                      // reset form values
                      formik.setFieldValue("weightWithBar", "");
                      formik.setFieldValue("weightWithoutBar", "");
                      setWeightWithBarImg(null);
                      setWeightWithBarImages([]);
                      openNotif({
                        vertical: "top",
                        horizontal: "center",
                        msg: "عملیات با موفقیت انجام شد.",
                        severity: "success"
                      });

                      dispatch(
                        DRAWER({
                          right: false,
                          top: false,
                          bottom: false,
                          content: null,
                          size: null
                        })
                      );

                      updateTable(1);
                    }
                  };
                  if (
                    (item?.killhouseUser?.maximumLoadVolumeReduction !== 0 &&
                      formik.values.loadRealNumber <
                        item?.acceptedRealQuantity *
                          (1 -
                            item?.killhouseUser?.maximumLoadVolumeReduction /
                              100)) ||
                    (item?.killhouseUser?.maximumLoadVolumeIncrease !== 0 &&
                      formik.values.loadRealNumber >
                        item?.acceptedRealQuantity *
                          (1 +
                            item?.killhouseUser?.maximumLoadVolumeIncrease /
                              100))
                  ) {
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      msg: "حجم وارد شده با مجوز حداکثر افزایش/کاهش ورود اطلاعات بار مطابقت ندارد!",
                      severity: "error"
                    });
                  } else if (
                    getRoleFromUrl() !== "SuperAdmin" &&
                    getRoleFromUrl() !== "AdminX" &&
                    !isValidIndexWeight(
                      weightRange,
                      item?.poultryRequest?.age,
                      parseInt(barWeight) /
                        parseInt(formik.values.loadRealNumber)
                    )
                  ) {
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      msg: "میانگین وزنی با احراز سنی مطابقت ندارد. لطفا با اتحادیه تماس بگیرید.",
                      severity: "error"
                    });
                  } else if (
                    isRejected ||
                    item.assignmentInfo?.assignmentState === true
                  ) {
                    const reqUpdate = {
                      car_weight_with_load: formik.values.weightWithBar,
                      car_weight_without_load: formik.values.weightWithoutBar,
                      car_with_load_image: weightWithBarImg,
                      key: item.assignmentInfo.assignmentKey,
                      real_quantity: formik.values.loadRealNumber,
                      exploited_carcass: formik.values.exploitedCarcass,
                      role: getRoleFromUrl(),
                      ...(shouldShowExclusiveKillerSelect && {
                        killer_key: selectedOption ? selectedOption : null
                      })
                    };
                    dispatch(slaughterUpdateBarWeight(reqUpdate)).then(
                      thenCallback
                    );
                  } else {
                    const req = {
                      car_weight_with_load: formik.values.weightWithBar,
                      car_weight_without_load: formik.values.weightWithoutBar,
                      car_with_load_image: weightWithBarImg,
                      real_quantity: formik.values.loadRealNumber,
                      exploited_carcass: formik.values.exploitedCarcass,
                      kill_house_request_key: reqKey,
                      // kill_house_check_key: checkKey,
                      role: getRoleFromUrl(),
                      ...(shouldShowExclusiveKillerSelect && {
                        killer_key: selectedOption ? selectedOption : null
                      })
                    };

                    if (!req.kill_house_check_key) {
                      delete req.kill_house_check_key;
                    }

                    dispatch(slaughterEnterBarWeight(req)).then(thenCallback);
                  }
                }}
              >
                {buttonText}
              </Button>
            </Grid>
          </Grid>
        </Grid>
      </Grid>
    </Grid>
  );
};

SlaughterEnterBarItem.propTypes = {
  data: PropTypes.array,
  reqKey: PropTypes.string,
  checkKey: PropTypes.string,
  isRejected: PropTypes.bool,
  item: PropTypes.any,
  realNumber: PropTypes.any
};
