import React, { useContext } from "react";
import { useFormik } from "formik";
import * as yup from "yup";
import { TextField, Box, Button } from "@mui/material";
import { provinceManageTradesEditPercents } from "../../services/province-manage-trades-edit-percents";
import { useDispatch } from "react-redux";
import { AppContext } from "../../../../contexts/AppContext";
import { CLOSE_MODAL } from "../../../../lib/redux/slices/appSlice";
import { Grid } from "../../../../components/grid/Grid";

const validationSchema = yup
  .object({
    percentInsideProvince: yup
      .number()
      .typeError("باید عدد وارد کنید")
      .min(0, "نمی‌تواند کمتر از 0 باشد")
      .max(100, "نمی‌تواند بیشتر از 100 باشد")
      .required("الزامی"),
    percentOutsideProvince: yup
      .number()
      .typeError("باید عدد وارد کنید")
      .min(0, "نمی‌تواند کمتر از 0 باشد")
      .max(100, "نمی‌تواند بیشتر از 100 باشد")
      .required("الزامی"),
    percentSegmentation: yup
      .number()
      .typeError("باید عدد وارد کنید")
      .min(0, "نمی‌تواند کمتر از 0 باشد")
      .max(100, "نمی‌تواند بیشتر از 100 باشد")
      .required("الزامی"),
  })
  .test(
    "total-percentage",
    "مجموع درصدها نمی‌تواند بیشتر از 100 باشد",
    function (values) {
      const {
        percentInsideProvince,
        percentOutsideProvince,
        percentSegmentation,
      } = values;
      const total =
        (percentInsideProvince || 0) +
        (percentOutsideProvince || 0) +
        (percentSegmentation || 0);
      return total <= 100;
    }
  );

export const ProvinceManageDistributionsSubmitPercents = ({
  item,
  updateTable,
  type,
}) => {
  const [openNotif] = useContext(AppContext);
  const dispatch = useDispatch();
  const formik = useFormik({
    initialValues: {
      percentInsideProvince:
        type === "gov"
          ? item?.inProvinceGovernmentalSellingPercent
          : item?.inProvinceFreeSellingPercent || 0,
      percentOutsideProvince:
        type === "gov"
          ? item?.outProvinceGovernmentalSellingPercent
          : item?.outProvinceFreeSellingPercent || 0,
      percentSegmentation:
        type === "gov"
          ? item?.segmentationGovernmentalPercent
          : item?.segmentationFreeSellingPercent || 0,
      percentColdHouse:
        type === "gov"
          ? item?.coldHouseGovernmentalPercent
          : item?.coldHouseFreePercent || 0,
    },
    validationSchema: validationSchema,
    onSubmit: (values) => {
      dispatch(
        provinceManageTradesEditPercents({
          key: item?.key,
          ...(type === "gov"
            ? {
                governmental_selling_permission: true,
                in_province_governmental_selling_percent:
                  values.percentInsideProvince,
                segmentation_governmental_percent: values.percentSegmentation,
                out_province_governmental_selling_percent:
                  values.percentOutsideProvince,
                cold_house_governmental_percent: values.percentColdHouse,
              }
            : {
                free_selling_permission: true,
                in_province_free_selling_percent: values.percentInsideProvince,
                out_province_free_selling_percent:
                  values.percentOutsideProvince,
                segmentation_free_selling_percent: values.percentSegmentation,
                cold_house_free_percent: values.percentColdHouse,
              }),
        })
      ).then((r) => {
        if (r.payload.error) {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: r.payload.error,
            severity: "error",
          });
        } else {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "عملیات با موفقیت انجام شد.",
            severity: "success",
          });
        }
        dispatch(CLOSE_MODAL());
        updateTable();
      });
    },
  });

  const calculateTotal = () => {
    const {
      percentInsideProvince,
      percentOutsideProvince,
      percentSegmentation,
      percentColdHouse,
    } = formik.values;
    return (
      (percentInsideProvince || 0) +
      (percentOutsideProvince || 0) +
      (percentColdHouse || 0) +
      (percentSegmentation || 0)
    );
  };

  const total = calculateTotal();

  return (
    <Box component="form" onSubmit={formik.handleSubmit} sx={{ width: "100%" }}>
      <Grid container spacing={2} alignItems="flex-start">
        <Grid item xs={12} sm={6}>
          <TextField
            fullWidth
            id="percentInsideProvince"
            name="percentInsideProvince"
            label="حداقل توزیع داخل استان"
            type="number"
            value={formik.values.percentInsideProvince}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            error={
              formik.touched.percentInsideProvince &&
              Boolean(formik.errors.percentInsideProvince)
            }
            helperText={
              formik.touched.percentInsideProvince &&
              formik.errors.percentInsideProvince
            }
            inputProps={{ min: 0, max: 100, step: 0.1 }}
            size="small"
          />
        </Grid>

        <Grid item xs={12} sm={6}>
          <TextField
            fullWidth
            id="percentOutsideProvince"
            name="percentOutsideProvince"
            label="حداکثر فروش خارج استان"
            type="number"
            value={formik.values.percentOutsideProvince}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            error={
              formik.touched.percentOutsideProvince &&
              Boolean(formik.errors.percentOutsideProvince)
            }
            helperText={
              formik.touched.percentOutsideProvince &&
              formik.errors.percentOutsideProvince
            }
            inputProps={{ min: 0, max: 100, step: 0.1 }}
            size="small"
          />
        </Grid>

        <Grid item xs={12} sm={6}>
          <TextField
            fullWidth
            id="percentSegmentation"
            name="percentSegmentation"
            label="حداکثر قطعه بندی"
            type="number"
            value={formik.values.percentSegmentation}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            error={
              formik.touched.percentSegmentation &&
              Boolean(formik.errors.percentSegmentation)
            }
            helperText={
              formik.touched.percentSegmentation &&
              formik.errors.percentSegmentation
            }
            inputProps={{ min: 0, max: 100, step: 0.1 }}
            size="small"
          />
        </Grid>

        <Grid item xs={12} sm={6}>
          <TextField
            fullWidth
            id="percentColdHouse"
            name="percentColdHouse"
            label="حداکثر انجماد"
            type="number"
            value={formik.values.percentColdHouse}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            error={
              formik.touched.percentColdHouse &&
              Boolean(formik.errors.percentColdHouse)
            }
            helperText={
              formik.touched.percentColdHouse && formik.errors.percentColdHouse
            }
            inputProps={{ min: 0, max: 100, step: 0.1 }}
            size="small"
          />
        </Grid>

        <Grid container xs={12} justifyContent="center" spacing={1}>
          <Grid xs={6}>
            <Button
              onClick={formik.handleSubmit}
              variant="contained"
              color="primary"
              disabled={!formik.isValid || total > 100}
              fullWidth
            >
              ثبت
            </Button>
          </Grid>
          <Grid xs={6}>
            <Button
              onClick={() => dispatch(CLOSE_MODAL())}
              variant="contained"
              color="error"
              fullWidth
            >
              انصراف
            </Button>
          </Grid>
        </Grid>
      </Grid>
    </Box>
  );
};
