import {
  Checkbox,
  FormControl,
  FormControlLabel,
  InputLabel,
  MenuItem,
  Select,
} from "@mui/material";
import { useEffect, useState } from "react";
import { useDispatch } from "react-redux";
import { Grid } from "../../../../components/grid/Grid";
import { getHourLimitKillRequestKillhouseService } from "../../../city/services/get-hour-limit-kill-request-killhouse";
import { hourLimitKillRequestKillhouseService } from "../../../city/services/hour-limit-kill-request-killhouse";

export const ProvincePolicyKillhouseHourLimit = () => {
  const dispatch = useDispatch();
  const hours = Array.from({ length: 8 }, (_, i) => i + 8);
  const [isChecked, setIsChecked] = useState(false);
  const [selectedHour, setSelectedHour] = useState("");

  useEffect(() => {
    dispatch(getHourLimitKillRequestKillhouseService()).then((r) => {
      setIsChecked(r.payload.data.active);
      setSelectedHour(r.payload.data.hour);
    });
  }, []);

  useEffect(() => {
    if (isChecked && selectedHour) {
      dispatch(
        hourLimitKillRequestKillhouseService({
          hour: selectedHour,
          active: isChecked,
        })
      );
    }
    if (!isChecked && selectedHour) {
      setSelectedHour(null);
      dispatch(
        hourLimitKillRequestKillhouseService({ hour: 0, active: isChecked })
      );
    }
  }, [selectedHour, isChecked]);

  return (
    <Grid container gap={2}>
      <FormControlLabel
        control={
          <Checkbox
            checked={isChecked}
            onChange={() => setIsChecked(!isChecked)}
          />
        }
        label="محدودیت زمان درخواست کشتار کشتارگاه"
      />
      {isChecked && (
        <FormControl style={{ width: 200 }}>
          <InputLabel id="hour-label">ساعت پایان درخواست</InputLabel>
          <Select
            labelId="hour-label"
            label="ساعت پایان درخواست"
            id="hour-select"
            value={selectedHour}
            onChange={(event) => setSelectedHour(event.target.value)}
          >
            {hours.map((hour) => (
              <MenuItem key={hour} value={hour}>
                {hour}:00
              </MenuItem>
            ))}
          </Select>
        </FormControl>
      )}
    </Grid>
  );
};
