import React, { useState, useMemo, useContext, useEffect } from "react";
import { Grid } from "../../../../components/grid/Grid";
import {
  TextField,
  FormControl,
  FormLabel,
  RadioGroup,
  FormControlLabel,
  Radio,
  Switch,
  Button,
} from "@mui/material";
import { useFormik } from "formik";
import { Yup } from "../../../../lib/yup/yup";
import { useDispatch } from "react-redux";
import { provinceManageTradesEditPercents } from "../../services/province-manage-trades-edit-percents";
import { AppContext } from "../../../../contexts/AppContext";
import { CLOSE_MODAL } from "../../../../lib/redux/slices/appSlice";

export const ProvinceManageTradesSetPercents = ({ item, updateTable }) => {
  const initialValues = {
    market_capacity_percent: item?.marketCapacityPercent ?? 0,
    market_light_capacity: item?.marketLightCapacity ?? false,
    market_light_capacity_percent: item?.marketLightCapacityPercent ?? 0,
    total_kill_capacity: item?.totalKillCapacity ?? 0,
    total_kill_capacity_percent: item?.totalKillCapacityPercent ?? 0,
  };

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

  const [isAbleToBuy, setIsAbleToBuy] = useState(item?.marketBuying || false);
  const [hasLimit, setHasLimit] = useState(
    item?.marketBuyingLimitation || false
  );
  const [isPercentLimit, setIsPercentLimit] = useState(
    item?.marketBuyingCapacityPercentStatus || false
  );
  const [isLightCapacity, setIsLightCapacity] = useState(
    Boolean(initialValues.market_light_capacity)
  );

  const getValidationSchema = (isAble, isLight) =>
    Yup.object({
      market_capacity_percent:
        isAble && isPercentLimit
          ? Yup.number()
              .required("درصد خرید کل الزامی است")
              .min(0, "حداقل مقدار 0 است")
              .max(100, "حداکثر مقدار 100 است")
              .typeError("فقط عدد مجاز است")
          : Yup.number().notRequired(),
      total_kill_capacity:
        hasLimit && !isPercentLimit
          ? Yup.number()
              .required("سقف کشتار الزامی است!")
              .typeError("فقط عدد مجاز است")
          : Yup.number().notRequired(),
      total_kill_capacity_percent:
        hasLimit && !isPercentLimit
          ? Yup.number()
              .required("درصد از سقف کشتار الزامی است!")
              .typeError("فقط عدد مجاز است")
              .min(0, "حداقل مقدار 0 است")
              .max(100, "حداکثر مقدار 100 است")
          : Yup.number().notRequired(),
      market_light_capacity_percent:
        isAble && isLightCapacity && hasLimit
          ? Yup.number()
              .required("درصد خرید سبک الزامی است")
              .min(0, "حداقل مقدار 0 است")
              .max(100, "حداکثر مقدار 100 است")
              .typeError("فقط عدد مجاز است")
          : Yup.number().notRequired(),
    });

  const validationSchema = useMemo(
    () => getValidationSchema(isAbleToBuy, isLightCapacity),
    [isAbleToBuy, isLightCapacity, hasLimit, isPercentLimit]
  );

  useEffect(() => {
    formik.validateForm();
  }, [isAbleToBuy, isLightCapacity, hasLimit, isPercentLimit]);

  const formik = useFormik({
    initialValues: {
      market_capacity_percent: initialValues.market_capacity_percent ?? "",
      total_kill_capacity: initialValues.total_kill_capacity ?? "",
      total_kill_capacity_percent:
        initialValues.total_kill_capacity_percent ?? "",
      market_light_capacity_percent:
        initialValues.market_light_capacity_percent ?? "",
    },
    validationSchema,
    validateOnBlur: true,
    validateOnChange: true,
    onSubmit: (values, helpers) => {
      const cleaned = {
        key: item?.key,
        market_buying: isAbleToBuy,
        market_buying_limitation: hasLimit,
        // ...(!isPercentLimit ? { max_kill_limit: true } : {}),
        market_buying_capacity_percent_status:
          isAbleToBuy && hasLimit && isPercentLimit ? true : false,
        market_capacity_percent:
          isAbleToBuy && hasLimit && isPercentLimit
            ? Number(values.market_capacity_percent)
            : 0,

        total_kill_capacity_percent:
          isAbleToBuy && hasLimit && !isPercentLimit
            ? values?.total_kill_capacity_percent
            : 0,
        market_light_capacity: isLightCapacity,
        market_light_capacity_percent:
          isLightCapacity && hasLimit
            ? Number(values.market_light_capacity_percent)
            : 0,
      };
      dispatch(provinceManageTradesEditPercents(cleaned)).then((r) => {
        if (r.payload.error) {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: r.payload.error,
            severity: "error",
          });
        } else {
          dispatch(CLOSE_MODAL());
          updateTable();
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "عملیات با موفقیت انجام شد.",
            severity: "success",
          });
        }
      });

      helpers.setSubmitting(false);
    },
  });

  return (
    <Grid container xs={12}>
      <Grid container gap={2} xs={12}>
        <Grid xs={12}>
          <FormControl component="fieldset">
            <FormLabel component="legend">اجازه خرید</FormLabel>
            <RadioGroup
              fullWidth
              row
              name="market_buying"
              value={isAbleToBuy ? "true" : "false"}
              onChange={(e) => setIsAbleToBuy(e.target.value === "true")}
            >
              <FormControlLabel value="true" control={<Radio />} label="دارد" />
              <FormControlLabel
                value="false"
                control={<Radio />}
                label="ندارد"
              />
            </RadioGroup>
          </FormControl>
        </Grid>
        {isAbleToBuy && (
          <Grid container gap={2} xs={12}>
            <Grid xs={12}>
              <FormControl component="fieldset">
                <FormLabel component="legend">محدودیت کشتار</FormLabel>
                <RadioGroup
                  fullWidth
                  row
                  name="market_buying"
                  value={hasLimit ? "true" : "false"}
                  onChange={(e) => setHasLimit(e.target.value === "true")}
                >
                  <FormControlLabel
                    value="true"
                    control={<Radio />}
                    label="دارد"
                  />
                  <FormControlLabel
                    value="false"
                    control={<Radio />}
                    label="ندارد"
                  />
                </RadioGroup>
              </FormControl>
            </Grid>

            {hasLimit && (
              <Grid xs={12}>
                <FormControl component="fieldset">
                  <FormLabel component="legend">نوع محدودیت</FormLabel>

                  <RadioGroup
                    fullWidth
                    row
                    name="market_buying"
                    value={isPercentLimit ? "true" : "false"}
                    onChange={(e) =>
                      setIsPercentLimit(e.target.value === "true")
                    }
                  >
                    <FormControlLabel
                      value="false"
                      control={<Radio />}
                      label="درصد از سقف کشتار"
                    />
                    <FormControlLabel
                      value="true"
                      control={<Radio />}
                      label="درصد از اعلام کشتارها"
                    />
                  </RadioGroup>
                </FormControl>
              </Grid>
            )}

            {hasLimit && isPercentLimit && (
              <Grid item xs={12}>
                <TextField
                  size="small"
                  fullWidth
                  label="درصد از کل کشتار"
                  name="market_capacity_percent"
                  value={formik.values.market_capacity_percent}
                  onChange={formik.handleChange}
                  onBlur={formik.handleBlur}
                  error={
                    formik.touched.market_capacity_percent &&
                    Boolean(formik.errors.market_capacity_percent)
                  }
                  helperText={
                    formik.touched.market_capacity_percent &&
                    formik.errors.market_capacity_percent
                  }
                />
              </Grid>
            )}
            {hasLimit && !isPercentLimit && (
              <Grid item xs={12}>
                <TextField
                  disabled
                  size="small"
                  fullWidth
                  label="سقف کشتار"
                  name="total_kill_capacity"
                  value={formik.values.total_kill_capacity}
                  onChange={formik.handleChange}
                  onBlur={formik.handleBlur}
                  error={
                    formik.touched.total_kill_capacity &&
                    Boolean(formik.errors.total_kill_capacity)
                  }
                  helperText={
                    formik.touched.total_kill_capacity &&
                    formik.errors.total_kill_capacity
                  }
                />
              </Grid>
            )}
            {hasLimit && !isPercentLimit && (
              <Grid item xs={12}>
                <TextField
                  size="small"
                  fullWidth
                  label="درصد از سقف کشتار"
                  name="total_kill_capacity_percent"
                  value={formik.values.total_kill_capacity_percent}
                  onChange={formik.handleChange}
                  onBlur={formik.handleBlur}
                  error={
                    formik.touched.total_kill_capacity_percent &&
                    Boolean(formik.errors.total_kill_capacity_percent)
                  }
                  helperText={
                    formik.touched.total_kill_capacity_percent &&
                    formik.errors.total_kill_capacity_percent
                  }
                />
              </Grid>
            )}

            {hasLimit && (
              <Grid item xs={12}>
                <FormControl component="fieldset">
                  <FormControlLabel
                    control={
                      <Switch
                        checked={isLightCapacity}
                        onChange={(e) => setIsLightCapacity(e.target.checked)}
                        name="market_light_capacity"
                      />
                    }
                    label="اولویت خرید سبک"
                  />
                </FormControl>
              </Grid>
            )}

            {isLightCapacity && hasLimit && (
              <Grid item xs={12}>
                <TextField
                  fullWidth
                  type="number"
                  name="market_light_capacity_percent"
                  label="درصد خرید سبک"
                  value={formik.values.market_light_capacity_percent}
                  onChange={formik.handleChange}
                  onBlur={formik.handleBlur}
                  error={
                    formik.touched.market_light_capacity_percent &&
                    Boolean(formik.errors.market_light_capacity_percent)
                  }
                  helperText={
                    formik.touched.market_light_capacity_percent &&
                    formik.errors.market_light_capacity_percent
                  }
                />
              </Grid>
            )}
          </Grid>
        )}
      </Grid>
      <Grid container xs={12} sx={{ width: "100%" }} mt={2}>
        <Button
          onClick={formik.handleSubmit}
          type="submit"
          variant="contained"
          fullWidth
          disabled={!formik.isValid}
        >
          ثبت
        </Button>
      </Grid>
    </Grid>
  );
};
