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 { Yup } from "../../../../lib/yup/yup";
import { AppContext } from "../../../../contexts/AppContext";
import { provincePolicyGetExportAllowStatus } from "../../services/province-policy-get-export-allow-state";
import { provincePolicyEditExportAllowState } from "../../services/province-policy-edit-export-allow-state";

export const ProvincePolicyCouncilAllowExport = () => {
  const [exportStatus, setExportStatus] = 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(provincePolicyGetExportAllowStatus()).then((r) => {
      setExportStatus(r.payload.data.allow);
      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}>
        <FormControlLabel
          control={
            <Radio
              name="item6"
              checked={exportStatus}
              onClick={() => {
                setExportStatus(true);
              }}
            />
          }
          label="فعال"
        />
        <FormControlLabel
          control={
            <Radio
              checked={!exportStatus}
              onClick={() => {
                dispatch(
                  provincePolicyEditExportAllowState({
                    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>
      {exportStatus && (
        <>
          <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(
                  provincePolicyEditExportAllowState({
                    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>
  );
};
