import React, { useContext, useEffect, useState } from "react";
import { Grid } from "../../../../components/grid/Grid";
import {
  Button,
  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 {
  provinceEditHatchingArchivePercent,
  provinceGetHatchingArchivePercent,
} from "../../services/province-hatching-archive-percent";

export const ProvinceHatchingArchivePercent = () => {
  const [isActive, setIsActive] = useState(false);
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);

  const formik = useFormik({
    initialValues: {
      percent: "",
    },
    validationSchema: Yup.object({
      percent: Yup.number()
        .required("این فیلد اجباری است")
        .min(1, "حداقل مقدار باید 1 باشد")
        .max(100, "حداکثر مقدار باید 100 باشد"),
    }),
  });

  const fetchData = () => {
    dispatch(provinceGetHatchingArchivePercent()).then((r) => {
      if (r.payload?.data) {
        setIsActive(r.payload.data.active);
        formik.setFieldValue("percent", r.payload.data.percent);
      }
    });
  };

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

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

  const handleSubmit = (activeStatus) => {
    dispatch(
      provinceEditHatchingArchivePercent({
        percent: activeStatus ? parseInt(formik.values.percent) : 0,
        active: activeStatus,
      })
    ).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",
        });
      }
    });
  };

  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="hatchingArchivePercent"
              checked={isActive}
              onClick={() => {
                setIsActive(true);
              }}
            />
          }
          label="فعال"
        />
        <FormControlLabel
          control={
            <Radio
              checked={!isActive}
              onClick={() => {
                setIsActive(false);
                handleSubmit(false);
              }}
              name="hatchingArchivePercent"
            />
          }
          label="غیر فعال"
        />
      </Grid>
      {isActive && (
        <>
          <Grid>
            <TextField
              size="small"
              label="درصد بایگانی"
              name="percent"
              type="number"
              value={formik.values.percent}
              onChange={formik.handleChange}
              error={formik.touched.percent && Boolean(formik.errors.percent)}
              helperText={formik.touched.percent && formik.errors.percent}
              required
            />
          </Grid>

          <Grid>
            <Button
              fullWidth
              disabled={!formik.isValid}
              variant="contained"
              onClick={() => handleSubmit(true)}
            >
              ثبت
            </Button>
          </Grid>
        </>
      )}
    </Grid>
  );
};
