import React, { useContext, useState } from "react";
import { Grid } from "../../../../components/grid/Grid";
import { Button, Radio, RadioGroup, FormControlLabel } from "@mui/material";
import { useDispatch } from "react-redux";
import { AppContext } from "../../../../contexts/AppContext";
import {
  CLOSE_MODAL,
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import TimePicker from "../../../../components/date-picker/CustomDatePicker";
import axios from "axios";

export const ProvinceRestrictionCarcassDistributionEdit = ({
  item,
  fetchData,
}) => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);

  const [formData, setFormData] = useState({
    time: item?.time || "16:00:00",
    allow: item?.allow !== undefined ? item?.allow : true,
  });

  const handleSubmit = async (e) => {
    e.preventDefault();

    dispatch(LOADING_START());
    try {
      await axios.put(`restriction_carcass_distribution/${item?.id}/`, {
        time: formData.time,
        allow: formData.allow,
      });

      dispatch(LOADING_END());
      openNotif({
        vertical: "top",
        horizontal: "center",
        msg: "عملیات با موفقیت انجام شد.",
        severity: "success",
      });
      fetchData();
      dispatch(CLOSE_MODAL());
    } catch (error) {
      dispatch(LOADING_END());
      openNotif({
        vertical: "top",
        horizontal: "center",
        msg: error?.response?.data?.message || "خطا در ویرایش اطلاعات",
        severity: "error",
      });
      console.error("Error updating data:", error);
    }
  };

  return (
    <Grid container xs={12} direction="column" justifyContent="center">
      <form onSubmit={handleSubmit}>
        <Grid container xs={12} gap={2} direction="column">
          <Grid item display="flex" justifyContent="start">
            <RadioGroup
              row
              value={formData.allow ? "allow" : "disallow"}
              onChange={(e) =>
                setFormData((prev) => ({
                  ...prev,
                  allow: e.target.value === "allow",
                }))
              }
            >
              <FormControlLabel
                value="allow"
                control={<Radio />}
                label="فعال"
              />
              <FormControlLabel
                value="disallow"
                control={<Radio />}
                label="غیر فعال"
              />
            </RadioGroup>
          </Grid>

          <Grid item display="flex" alignItems="center" gap={2}>
            <TimePicker
              value={formData.time}
              onChange={(newTime) =>
                setFormData((prev) => ({ ...prev, time: newTime }))
              }
              label="زمان"
            />
          </Grid>

          <Button variant="contained" fullWidth type="submit">
            ویرایش
          </Button>
        </Grid>
      </form>
    </Grid>
  );
};
