import React, { useContext, useEffect, useState } from "react";
import { Grid } from "../../../../components/grid/Grid";
import {
  Button,
  Checkbox,
  FormControlLabel,
  Radio,
  TextField,
  Typography,
} from "@mui/material";
import { useFormik } from "formik";
import { useDispatch } from "react-redux";
import { provincePolicyGetFreeSaleStatus } from "../../services/province-policy-get-free-sale-state";
import { Yup } from "../../../../lib/yup/yup";
import { provincePolicyEditFreeSaleAllowState } from "../../services/province-policy-edit-free-sale-allow-state";
import { AppContext } from "../../../../contexts/AppContext";

export const ProvincePolicyCouncilAllowFreeSale = () => {
  const [freeSale, setFreeSale] = useState(false);
  const [isLimited, setIsLimited] = useState(false);
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);

  const formik = useFormik({
    initialValues: {
      maxLimit: "",
    },
    validationSchema: Yup.object({
      maxLimit: Yup.number()
        .required("این فیلد اجباری است")
        .max(100, "درصدی بین 1 تا 100 وارد کنید!")
        .min(1, "درصدی بین 1 تا 100 وارد کنید!"),
    }),
  });

  const fetchData = () => {
    dispatch(provincePolicyGetFreeSaleStatus()).then((r) => {
      setFreeSale(r.payload.data.allow);
      if (r.payload.data.limitationStatus) {
        setIsLimited(true);
      }
      formik.setFieldValue("maxLimit", r.payload.data.limitation);
    });
  };

  useEffect(() => {
    fetchData();
  }, []);

  useEffect(() => {
    formik.validateForm();
  }, []);

  return (
    <Grid
      container
      alignItems="center"
      gap={2}
      justifyContent="space-between"
      isPolicy
      sx={{
        width: {
          xs: "100%",
          sm: "48%",
          lg: "24%",
          nxl: "19%",
        },
      }}
    >
      <Grid>
        <Typography variant="body1">حداکثر فروش به خارج استان</Typography>
      </Grid>
      <Grid container xs={12} justifyContent="space-between">
        <FormControlLabel
          control={
            <Radio
              name="item6"
              checked={freeSale}
              onClick={() => {
                setFreeSale(true);
              }}
            />
          }
          label="فعال"
        />
        <FormControlLabel
          control={
            <Radio
              checked={!freeSale}
              onClick={() => {
                dispatch(
                  provincePolicyEditFreeSaleAllowState({
                    allow: false,
                  })
                ).then((r) => {
                  if (r.payload.error) {
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      msg: r.payload.error,
                      severity: "error",
                    });
                  } else {
                    fetchData();
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      msg: "عملیات با موفقیت انجام شد.",
                      severity: "success",
                    });
                  }
                });
              }}
              name="item6"
            />
          }
          label="بدون محدودیت"
        />
      </Grid>
      {freeSale && (
        <>
          <Grid>
            <FormControlLabel
              control={
                <Checkbox
                  checked={isLimited}
                  onChange={() => setIsLimited(!isLimited)}
                  color="primary"
                />
              }
              label="درصد محدودیت جوجه ریزی"
            />
          </Grid>

          {isLimited && (
            <Grid>
              <TextField
                size="small"
                label="درصد محدودیت"
                name="maxLimit"
                value={formik.values.maxLimit}
                onChange={formik.handleChange}
                error={
                  formik.touched.maxLimit && Boolean(formik.errors.maxLimit)
                }
                helperText={formik.touched.maxLimit && formik.errors.maxLimit}
                required
              />
            </Grid>
          )}

          <Grid>
            <Button
              disabled={isLimited ? !formik.isValid : false}
              variant="contained"
              onClick={() => {
                dispatch(
                  provincePolicyEditFreeSaleAllowState({
                    allow: true,
                    limitation_status: isLimited ? true : false,
                    limitation: formik.values.maxLimit,
                  })
                ).then((r) => {
                  if (r.payload.error) {
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      msg: r.payload.error,
                      severity: "error",
                    });
                  } else {
                    fetchData();
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      msg: "عملیات با موفقیت انجام شد.",
                      severity: "success",
                    });
                  }
                });
              }}
            >
              ثبت
            </Button>
          </Grid>
        </>
      )}
    </Grid>
  );
};
