import React, { useContext, useEffect, useState } from "react";
import { Yup } from "../../../../lib/yup/yup";
import { useFormik } from "formik";
import { Grid } from "../../../../components/grid/Grid";
import {
  Button,
  FormControl,
  FormControlLabel,
  Radio,
  RadioGroup,
  TextField,
  Typography,
} from "@mui/material";
import { CLOSE_MODAL, OPEN_MODAL } from "../../../../lib/redux/slices/appSlice";
import { SPACING } from "../../../../data/spacing";
import { useDispatch, useSelector } from "react-redux";
import { killhouseSubmitRealInventoryService } from "../../services/killhouse-submit-real-inventory";
import { AppContext } from "../../../../contexts/AppContext";
import { provincePolicyGetDropLimitService } from "../../../province/services/province-policy-drop-limit";
import { fetchSlaughterBroadcastAndProducts } from "../../services/handle-fetch-slaughter-products";
import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith";

export const SlaughterSubmitRealInventory = ({ item, updateTable }) => {
  const [value, setValue] = useState("weight");
  const [loss, setLoss] = useState("0");
  const [dropLimits, setDropLimits] = useState({ min: 0, max: 100 });
  const selectedSubUser = useSelector(
    (state) => state.userSlice.selectedSubUser
  );
  const handleChange = (event) => {
    setValue(event.target.value);
  };
  const [inputWarehouse, setInputWarehouse] = useState(
    item?.killer ? "killer" : "self"
  );

  const handleChangeInputWarehouse = (event) => {
    setInputWarehouse(event.target.value);
  };

  const [openNotif] = useContext(AppContext);
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(provincePolicyGetDropLimitService()).then((r) => {
      if (r.payload?.data) {
        setDropLimits({
          min: parseFloat(r.payload.data.killHouseLimitPercentDown),
          max: parseFloat(r.payload.data.killHouseLimitPercentUp),
        });
      }
    });
  }, []);

  const formik = useFormik({
    initialValues: {
      realNumber: item?.acceptedRealQuantity ? item?.acceptedRealQuantity : "",
      realWeight: item?.wareHouseAcceptedRealWeight
        ? item?.wareHouseAcceptedRealWeight
        : 0,
    },
    validationSchema: Yup.object({
      realNumber: Yup.number()
        .typeError("لطفا فیلد را به درستی وارد کنید.!")
        .required("این فیلد اجباری است!")
        .min(0, "مقدار نمی‌تواند منفی باشد"),
      realWeight: Yup.number()
        .typeError("لطفا فیلد را به درستی وارد کنید.!")
        .required("این فیلد اجباری است!")
        .min(0, "مقدار نمی‌تواند منفی باشد"),
    }),
  });

  const formik2 = useFormik({
    initialValues: {
      lossWeight: "",
    },
    validationSchema: Yup.object({
      lossWeight: Yup.number()
        .typeError("لطفا فیلد را به درستی وارد کنید.!")
        .required("این فیلد اجباری است!")
        .min(
          dropLimits.min,
          `درصد افت باید بین ${dropLimits.min} تا ${dropLimits.max} درصد باشد!`
        )
        .max(
          dropLimits.max,
          `درصد افت باید بین ${dropLimits.min} تا ${dropLimits.max} درصد باشد!`
        ),
    }),
  });

  useEffect(() => {
    if (value === "weight") {
      if (item?.acceptedRealWeight && formik.values.realWeight) {
        const difference = item.acceptedRealWeight - formik.values.realWeight;
        const calculatedLoss = (difference / item.acceptedRealWeight) * 100;
        setLoss(calculatedLoss.toFixed(2));
      } else {
        setLoss(0);
      }
    } else {
      if (item?.acceptedRealWeight && formik2.values.lossWeight) {
        const percentage =
          (item.acceptedRealWeight / 100) * formik2.values.lossWeight;
        setLoss((item.acceptedRealWeight - percentage).toFixed(2));
      } else {
        setLoss(0);
      }
    }
  }, [formik.values.realWeight, formik2.values.lossWeight, value, item]);

  const isLossInRange = () => {
    if (value === "weight") {
      return loss >= dropLimits.min && loss <= dropLimits.max;
    } else {
      return formik2.isValid;
    }
  };

  const isFormValid = () => {
    if (value === "weight") {
      return formik.isValid && isLossInRange();
    } else {
      return formik2.isValid;
    }
  };

  const handleSubmit = () => {
    if (!isFormValid()) return;

    const payload =
      value === "weight"
        ? {
            input_type: "input_weight",
            ware_house_accepted_real_quantity: parseInt(
              formik.values.realNumber
            ),
            ware_house_accepted_real_weight: parseInt(formik.values.realWeight),
            kill_house_request_key: item?.key,
            loss_percent: parseFloat(loss),
          }
        : {
            input_type: "loss_weight",
            loss_percent: parseInt(formik2.values.lossWeight),
            kill_house_request_key: item?.key,
          };

    dispatch(
      killhouseSubmitRealInventoryService({
        ...payload,
        ...(item?.killer ? { input_warehouse: inputWarehouse } : {}),
      })
    ).then((r) => {
      if (r.payload.error) {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: r.payload.error,
          severity: "error",
        });
      } else {
        dispatch(CLOSE_MODAL());
        updateTable();
        dispatch(
          fetchSlaughterBroadcastAndProducts({
            role_key: checkPathStartsWith("slaughter")
              ? selectedSubUser?.key
              : "",
          })
        );
        handleAlert();
      }
    });
  };

  const handleAlert = () => {
    dispatch(
      OPEN_MODAL({
        title: "عملیات با موفقیت انجام شد",
        content: (
          <>
            <Grid container gap={SPACING.SMALL} justifyContent="center">
              <Typography variant="body2" color="secondary">
                جهت ویرایش میتوانید حداکثر تا پایان امروز یا قبل از اولین تخصیص
                اقدام کنید.
              </Typography>
              <Button
                variant="outlined"
                onClick={() => {
                  dispatch(CLOSE_MODAL());
                }}
              >
                متوجه شدم
              </Button>
            </Grid>
          </>
        ),
      })
    );
  };

  return (
    <>
      <Grid
        xs={12}
        container
        spacing={SPACING.SMALL}
        alignItems="center"
        justifyContent="center"
      >
        <Grid container xs={12} gap={SPACING.TINY}>
          <Grid container xs={12} gap={SPACING.SMALL} justifyContent="center">
            {item?.killer && (
              <Typography color="primary" variant="body2">
                کشتارکن: {item?.killer?.name}
              </Typography>
            )}
            <Typography color="primary" variant="body2">
              کد بار: {item.barCode}
            </Typography>
            <Typography color="primary" variant="body2">
              حجم بار: {item?.acceptedRealQuantity?.toLocaleString()}
            </Typography>
            <Typography color="primary" variant="body2">
              وزن بار: {item?.acceptedRealWeight?.toLocaleString()}
            </Typography>
          </Grid>
          <FormControl>
            <RadioGroup
              aria-labelledby="demo-radio-buttons-group-label"
              defaultValue="بر اساس وزن ورودی"
              name="radio-buttons-group"
              value={value}
              onChange={handleChange}
              row
            >
              <FormControlLabel
                value="weight"
                control={<Radio />}
                label="بر اساس وزن ورودی"
              />
              <FormControlLabel
                value="loss"
                control={<Radio />}
                label="بر اساس درصد افت"
              />
            </RadioGroup>
          </FormControl>

          {value === "weight" ? (
            <>
              <TextField
                fullWidth
                id="realWeight"
                size="small"
                label="وزن لاشه"
                variant="outlined"
                value={formik.values.realWeight}
                error={
                  formik.touched.realWeight
                    ? Boolean(formik.errors.realWeight)
                    : null
                }
                onChange={formik.handleChange}
                onBlur={formik.handleBlur}
                helperText={
                  formik.touched.realWeight && Boolean(formik.errors.realWeight)
                    ? formik.errors.realWeight
                    : null
                }
              />

              <TextField
                fullWidth
                id="realNumber"
                size="small"
                label="حجم لاشه"
                variant="outlined"
                value={formik.values.realNumber}
                error={
                  formik.touched.realNumber
                    ? Boolean(formik.errors.realNumber)
                    : null
                }
                onChange={formik.handleChange}
                onBlur={formik.handleBlur}
                helperText={
                  formik.touched.realNumber && Boolean(formik.errors.realNumber)
                    ? formik.errors.realNumber
                    : null
                }
              />
            </>
          ) : (
            <TextField
              fullWidth
              id="lossWeight"
              size="small"
              label="درصد افت"
              variant="outlined"
              value={formik2.values.lossWeight}
              error={
                formik2.touched.lossWeight
                  ? Boolean(formik2.errors.lossWeight)
                  : null
              }
              onChange={formik2.handleChange}
              onBlur={formik2.handleBlur}
              helperText={
                formik2.touched.lossWeight && Boolean(formik2.errors.lossWeight)
                  ? formik2.errors.lossWeight
                  : null
              }
            />
          )}
        </Grid>

        {item?.killer && (
          <Grid
            mt={2}
            xs={12}
            container
            justifyContent="start"
            p={1}
            sx={{
              borderStyle: "solid",
              borderWidth: "1px",
              borderColor: "red",
              borderRadius: "15px",
            }}
          >
            <FormControl>
              <RadioGroup
                aria-labelledby="demo-radio-buttons-group-label"
                defaultValue={inputWarehouse}
                name="radio-buttons-group"
                value={inputWarehouse}
                onChange={handleChangeInputWarehouse}
                row
              >
                <FormControlLabel
                  value="self"
                  control={<Radio color="error" />}
                  label="ورود به انبار کشتارگاه"
                />
                <FormControlLabel
                  value="killer"
                  control={<Radio color="error" />}
                  label="ورود به انبار کشتارکن"
                />
              </RadioGroup>
            </FormControl>
          </Grid>
        )}

        <Grid
          container
          xs={12}
          gap={4}
          alignItems="center"
          mt={2}
          justifyContent="space-between"
        >
          <Grid>
            {value === "weight" ? (
              <Grid container gap={2} alignItems="center">
                <Typography variant="body1" color="primary">
                  افت: {loss > 0 ? loss : 0}%
                </Typography>
                {!isLossInRange() && (
                  <Typography variant="body2" color="error">
                    درصد افت باید بین {dropLimits.min} تا {dropLimits.max} درصد
                    باشد!
                  </Typography>
                )}
              </Grid>
            ) : (
              <Typography variant="body1" color="primary">
                وزن: {loss}
              </Typography>
            )}
          </Grid>
          <Grid>
            <Button
              disabled={!isFormValid()}
              size="small"
              variant="outlined"
              onClick={handleSubmit}
            >
              ثبت
            </Button>
          </Grid>
        </Grid>
      </Grid>
    </>
  );
};
