import {
  Button,
  Switch,
  TextField,
  Typography,
  Radio,
  RadioGroup,
  FormControlLabel,
  FormControl,
} from "@mui/material";
import DoneIcon from "@mui/icons-material/Done";
import { useDispatch } from "react-redux";
import { useContext, useState, useEffect } from "react";
import { Grid } from "../../../../components/grid/Grid";
import { AppContext } from "../../../../contexts/AppContext";
import { SPACING } from "../../../../data/spacing";
import { provincePolicyWagesEditKillhouse } from "../../../province/services/province-policy-wages-edit-killhouse";

export const ProvinceManageSellingForceGovernmentalBuy = ({
  item,
  fetchdata,
}) => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);

  const [state, setState] = useState({
    minimumSaleState: item?.quota || false,
    quotaOption: item?.quotaMaxKillLimit
      ? "max_kill_limit"
      : item?.quotaRequest
      ? "request"
      : item?.quotaCustom
      ? "custom"
      : "",
    qoutaCustomQuntity: item?.quotaCustomQuantity || 0,
    percent: item?.governmentalQuota || 0,
  });

  const [errors, setErrors] = useState({
    percent: false,
    qoutaCustomQuntity: false,
  });

  useEffect(() => {
    if (!state.minimumSaleState) {
      setState((prev) => ({
        ...prev,
        quotaOption: "",
        qoutaCustomQuntity: 0,
        percent: 0,
      }));
      setErrors({ percent: false, qoutaCustomQuntity: false });
    }
  }, [state.minimumSaleState]);

  const handleToggle = (key, value) => {
    setState((prev) => ({ ...prev, [key]: value }));
  };

  const handleRadioChange = (event) => {
    const newOption = event.target.value;
    setState((prev) => ({
      ...prev,
      quotaOption: newOption,
      ...(newOption !== "custom" && { qoutaCustomQuntity: 0 }),
      ...(newOption === "custom" && { percent: 0 }),
    }));
    setErrors({ percent: false, qoutaCustomQuntity: false });
  };

  const handleInputChange = (field, value) => {
    setState((prev) => ({ ...prev, [field]: value }));
    setErrors((prev) => ({ ...prev, [field]: false }));
  };

  const validateForm = () => {
    const newErrors = {
      percent: false,
      qoutaCustomQuntity: false,
    };

    if (state.minimumSaleState) {
      if (
        (state.quotaOption === "max_kill_limit" ||
          state.quotaOption === "request") &&
        (!state.percent || state.percent <= 0 || state.percent > 100)
      ) {
        newErrors.percent = true;
      }

      if (
        state.quotaOption === "custom" &&
        (!state.qoutaCustomQuntity || state.qoutaCustomQuntity <= 0)
      ) {
        newErrors.qoutaCustomQuntity = true;
      }
    }

    setErrors(newErrors);
    return !Object.values(newErrors).some((error) => error);
  };

  const handleSubmit = () => {
    if (!validateForm()) {
      openNotif({
        vertical: "top",
        horizontal: "center",
        msg: "لطفاً مقادیر الزامی را به درستی وارد کنید",
        severity: "error",
      });
      return;
    }

    dispatch(
      provincePolicyWagesEditKillhouse({
        kill_house_key: item?.key,
        quota: state.minimumSaleState,
        quota_max_kill_limit: state.quotaOption === "max_kill_limit",
        quota_request: state.quotaOption === "request",
        quota_custom: state.quotaOption === "custom",
        quota_custom_quantity: state.qoutaCustomQuntity,
        governmental_quota: state.percent,
      })
    ).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",
        });
        fetchdata();
      }
    });
  };

  const isFormValid = () => {
    if (!state.minimumSaleState) return true;

    if (
      state.quotaOption === "max_kill_limit" ||
      state.quotaOption === "request"
    ) {
      return state.percent > 0 && state.percent <= 100;
    }

    if (state.quotaOption === "custom") {
      return state.qoutaCustomQuntity > 0;
    }

    return false;
  };

  return (
    <Grid xs={12} container direction="column" gap={SPACING.SMALL}>
      <Grid xs={12} container alignItems="center" gap={1}>
        <Grid item>
          <Switch
            checked={state.minimumSaleState}
            onChange={(e) => {
              handleToggle("minimumSaleState", e.target.checked);

              if (!e.target.checked) {
                dispatch(
                  provincePolicyWagesEditKillhouse({
                    kill_house_key: item?.key,
                    quota: false,
                    quota_max_kill_limit: false,
                    quota_request: false,
                    quota_custom: false,
                    quota_custom_quantity: 0,
                    governmental_quota: 0,
                  })
                ).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",
                    });
                    fetchdata();
                  }
                });
              }
            }}
            inputProps={{
              "aria-label": "in-province-selling-limitation-switch",
            }}
          />
        </Grid>
        <Grid item>
          <Typography>الزام به خرید دولتی</Typography>
        </Grid>
      </Grid>

      {state.minimumSaleState && (
        <Grid xs={12} container direction="column" gap={1}>
          <Grid item>
            <FormControl component="fieldset" fullWidth>
              <RadioGroup
                value={state.quotaOption}
                onChange={handleRadioChange}
              >
                <FormControlLabel
                  value="max_kill_limit"
                  control={<Radio />}
                  label="بر اساس سقف کشتار"
                />
                <FormControlLabel
                  value="request"
                  control={<Radio />}
                  label="بر اساس اعلام نیازها"
                />
                <FormControlLabel
                  value="custom"
                  control={<Radio />}
                  label="بر اساس حجم از سقف کشتار"
                />
              </RadioGroup>
            </FormControl>
          </Grid>

          {(state.quotaOption === "max_kill_limit" ||
            state.quotaOption === "request") && (
            <TextField
              label="درصد خرید دولتی"
              size="small"
              fullWidth
              type="number"
              value={state.percent}
              onChange={(e) =>
                handleInputChange(
                  "percent",
                  Math.max(0, Math.min(100, e.target.value))
                )
              }
              inputProps={{ min: 1, max: 100 }}
              error={errors.percent}
              helperText={errors.percent ? "درصد باید بین ۱ تا ۱۰۰ باشد" : ""}
            />
          )}

          {state.quotaOption === "custom" && (
            <TextField
              label="حجم"
              size="small"
              fullWidth
              type="number"
              value={state.qoutaCustomQuntity}
              onChange={(e) =>
                handleInputChange(
                  "qoutaCustomQuntity",
                  Math.max(0, e.target.value)
                )
              }
              inputProps={{ min: 1 }}
              error={errors.qoutaCustomQuntity}
              helperText={
                errors.qoutaCustomQuntity ? "حجم باید بزرگتر از صفر باشد" : ""
              }
            />
          )}

          <Button
            fullWidth
            variant="contained"
            color="primary"
            onClick={handleSubmit}
            disabled={!isFormValid()}
            startIcon={<DoneIcon />}
          >
            ذخیره تغییرات
          </Button>
        </Grid>
      )}
    </Grid>
  );
};
