import { FormControlLabel, Radio, Typography } from "@mui/material";
import { useContext, useEffect, useState } from "react";
import { useDispatch } from "react-redux";
import axios from "axios";
import { Grid } from "../../../../components/grid/Grid";
import {
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { AppContext } from "../../../../contexts/AppContext";

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

  useEffect(() => {
    const fetchData = async () => {
      try {
        dispatch(LOADING_START());
        const response = await axios.get(
          "/allow_register_code_for_kill_house_free_sale_bar_information"
        );
        if (response.data) {
          setIsActive(response.data.active);
          setDataId(response.data.id);
        }
        dispatch(LOADING_END());
      } catch (error) {
        console.error("Error fetching data:", error);
        dispatch(LOADING_END());
      }
    };

    fetchData();
  }, [dispatch]);

  // Update value
  const handleUpdate = async (newValue) => {
    if (dataId === null) return;

    try {
      dispatch(LOADING_START());
      await axios.put(
        `/allow_register_code_for_kill_house_free_sale_bar_information/${dataId}/`,
        {
          active: newValue,
        }
      );
      setIsActive(newValue);
      openNotif({
        vertical: "top",
        horizontal: "center",
        msg: "تغییرات با موفقیت ثبت شد",
        severity: "success",
      });
      dispatch(LOADING_END());
    } catch (error) {
      console.error("Error updating data:", error);
      openNotif({
        vertical: "top",
        horizontal: "center",
        msg: "خطا در ثبت تغییرات",
        severity: "error",
      });
      dispatch(LOADING_END());
    }
  };

  return (
    <Grid
      container
      alignItems="center"
      isPolicy
      gap={2}
      sx={{
        width: {
          xs: "100%",
          sm: "48%",
          lg: "24%",
          nxl: "19%",
        },
      }}
    >
      <Typography variant="body1">اجباری بودن کد احراز کشتارگاه</Typography>
      <Grid xs={12} container justifyContent="space-between">
        <FormControlLabel
          control={
            <Radio
              name="slaughterhouse-verification"
              checked={isActive === true}
              onClick={() => handleUpdate(true)}
            />
          }
          label="فعال"
        />
        <FormControlLabel
          control={
            <Radio
              name="slaughterhouse-verification"
              checked={isActive === false}
              onClick={() => handleUpdate(false)}
            />
          }
          label="غیر فعال"
        />
      </Grid>
    </Grid>
  );
};
