import {
  Button,
  Checkbox,
  FormControl,
  FormControlLabel,
  InputAdornment,
  Radio,
  RadioGroup,
  TextField,
} from "@mui/material";
import { useContext, useEffect, useState } from "react";
import { Grid } from "../../../../components/grid/Grid";
import { useDispatch } from "react-redux";
import { SPACING } from "../../../../data/spacing";
import { provinceGetPolicyAvicultureCommitService } from "../../services/province-get-policy-aviculture-commit";
import { provinceUpdatePolicyAvicultureCommitService } from "../../services/province-update-policy-aviculture-commit";
import { AppContext } from "../../../../contexts/AppContext";

export const ProvincePolicyAvicultureCommit = ({ approvedState }) => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);
  const [numberValue, setNumberValue] = useState("");
  const [checked, setChecked] = useState(false);
  const [freeSaleKey, setFreeSaleKey] = useState();
  const [selectedValue, setSelectedValue] = useState("byWeight");

  useEffect(() => {
    dispatch(provinceGetPolicyAvicultureCommitService()).then((r) => {
      setChecked(r.payload.data.allow);
      setFreeSaleKey(r.payload.data.key);
      if (r.payload.data.type === "weight") {
        setSelectedValue("byWeight");
        setNumberValue(r.payload.data.weight);
      } else {
        setSelectedValue("byPercent");
        setNumberValue(r.payload.data.percent);
      }
    });
  }, []);

  const handleChange = (event) => {
    setChecked(event.target.checked);
    dispatch(
      provinceUpdatePolicyAvicultureCommitService({
        free_sale_key: freeSaleKey,
        allow: event.target.checked,
        // weight: Number(numberValue),
      })
    ).then((r) => {
      if (r.payload.error) {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: r.payload.error,
          severity: "error",
        });
        setChecked(false);
      } else {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: "عملیات با موفقیت انجام شد.",
          severity: "success",
        });
      }
    });
  };

  const handleChangeNumber = (event) => {
    const newValue = event.target.value;
    if (/^\d*$/.test(newValue) || newValue === "") {
      setNumberValue(newValue);
    }
  };

  const handleRadioChange = (event) => {
    setSelectedValue(event.target.value);
  };

  useEffect(() => {
    if (!approvedState && freeSaleKey) {
      setChecked(false);
      dispatch(
        provinceUpdatePolicyAvicultureCommitService({
          free_sale_key: freeSaleKey,
          allow: false,
          // weight: Number(numberValue),
        })
      );
    }
  }, [approvedState]);

  return (
    <Grid container alignItems="center" gap={SPACING.TINY}>
      <Grid>
        <FormControlLabel
          control={<Checkbox checked={checked} onChange={handleChange} />}
          label="تعهد تحویل مرغ به نرخ دولتی"
        />
      </Grid>
      {checked && (
        <Grid container alignItems="center">
          <Grid>
            <FormControl component="fieldset" disabled={!checked}>
              <RadioGroup
                aria-label="options"
                name="options"
                value={selectedValue}
                onChange={handleRadioChange}
              >
                <FormControlLabel
                  value="byPercent"
                  control={<Radio />}
                  label="بر اساس درصد تحویل"
                />
                <FormControlLabel
                  value="byWeight"
                  control={<Radio />}
                  label="بر اساس وزن قطعه"
                />
              </RadioGroup>
            </FormControl>
          </Grid>
          {selectedValue && (
            <Grid container gap={SPACING.TINY}>
              <Grid>
                <TextField
                  disabled={!checked}
                  type="number"
                  style={{ width: "200px" }}
                  InputProps={{
                    endAdornment: (
                      <InputAdornment position="end">
                        {selectedValue === "byWeight" ? "کیلوگرم" : "درصد"}
                      </InputAdornment>
                    ),
                  }}
                  size="small"
                  value={numberValue}
                  onChange={handleChangeNumber}
                  inputProps={{ inputMode: "numeric", pattern: "[0-9]*" }}
                />
              </Grid>
              <Grid>
                <Button
                  variant="contained"
                  disabled={!checked || !numberValue || Number(numberValue) < 1}
                  onClick={() => {
                    dispatch(
                      provinceUpdatePolicyAvicultureCommitService({
                        free_sale_key: freeSaleKey,
                        allow: checked,
                        weight:
                          selectedValue === "byWeight"
                            ? Number(numberValue)
                            : 0,
                        percent:
                          selectedValue === "byPercent"
                            ? Number(numberValue)
                            : 0,
                        type:
                          selectedValue === "byWeight" ? "weight" : "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",
                        });
                      }
                    });
                  }}
                >
                  ثبت
                </Button>
              </Grid>
            </Grid>
          )}
        </Grid>
      )}
    </Grid>
  );
};
