import React, { useContext, useEffect, useState } from "react";
import { Grid } from "../../../../components/grid/Grid";
import { provincePolicyGetTimeRagnge } from "../../services/province-policy-get-time-range";
import { provincePolicyEditTimeRange } from "../../services/province-policy-edit-time-range";
import { useDispatch } from "react-redux";
import {
  Button,
  FormControl,
  FormControlLabel,
  Radio,
  RadioGroup,
  Typography,
} from "@mui/material";
import TimePicker from "../../../../components/date-picker/CustomDatePicker";
import { AppContext } from "../../../../contexts/AppContext";

export const ProvincePolicyTimeRange = () => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);

  const [timeRange, setTimeRange] = useState([
    {
      start: "01:00:00",
      end: "24:00:00",
      name: "poultry_request",
      active: true,
    },
    { start: "01:00:00", end: "24:00:00", name: "kill_request", active: false },
    {
      start: "01:00:00",
      end: "24:00:00",
      name: "province_kill_request",
      active: false,
    },
    {
      start: "01:00:00",
      end: "24:00:00",
      name: "kill_house_request",
      active: false,
    },
    {
      start: "01:00:00",
      end: "24:00:00",
      name: "vet_farm_check_request",
      active: false,
    },
  ]);

  useEffect(() => {
    dispatch(provincePolicyGetTimeRagnge()).then((r) => {
      const apiTimeRange = r.payload.data.timeRange;

      setTimeRange((prevTimeRange) =>
        prevTimeRange.map((item) => {
          const updatedItem = apiTimeRange.find(
            (apiItem) => apiItem.name === item.name
          );
          return updatedItem ? { ...item, ...updatedItem } : item;
        })
      );
    });
  }, []);

  const getRageFaName = (item) => {
    let range = "درخواست کشتار مرغدار";
    switch (item) {
      case "poultry_request":
        range = "درخواست کشتار مرغدار";
        break;
      case "kill_request":
        range = "ثبت اعلام نیاز کشتارگاه";
        break;
      case "province_kill_request":
        range = "تخصیص استان به کشتارگاه";
        break;
      case "kill_house_request":
        range = "ایجاد بار کشتارگاه";
        break;
      case "vet_farm_check_request":
        range = "ثبت کد قرنطینه";
        break;
      default:
        break;
    }
    return range;
  };

  return (
    <Grid
      container
      xs={12}
      justifyContent="center"
      alignItems="start"
      sx={{ background: "#EAEFFF", borderRadius: "15px" }}
    >
      <Grid
        container
        xs={12}
        justifyContent="center"
        alignItems="start"
        gap={2}
        my={2}
      >
        {timeRange?.map((item, i) => (
          <Grid
            key={i}
            container
            xs={12}
            alignItems="center"
            justifyContent="start"
            gap={2}
            isPolicy
            sx={{
              width: {
                xs: "100%",
                sm: "48%",
                lg: "24%",
                nxl: "19%",
              },
            }}
          >
            <Typography sx={{ color: "rgba(0, 0, 0, 0.6)" }}>
              {getRageFaName(item?.name)}
            </Typography>

            <Grid container xs={12} alignItems="end" justifyContent="start">
              <Grid container direction="column">
                <FormControl>
                  <RadioGroup
                    aria-labelledby="demo-controlled-radio-buttons-group"
                    name="controlled-radio-buttons-group"
                    value={item.active}
                    onChange={(e) => {
                      const updatedObjects = timeRange.map((obj, index) =>
                        index === i
                          ? { ...obj, active: e.target.value === "true" }
                          : obj
                      );
                      setTimeRange(updatedObjects);

                      if (e.target.value === "false") {
                        dispatch(
                          provincePolicyEditTimeRange({
                            time_range: updatedObjects,
                          })
                        ).then((r) => {
                          if (r.payload.error) {
                            openNotif({
                              vertical: "top",
                              horizontal: "center",
                              msg: r.payload.error,
                              severity: "error",
                            });
                          } else {
                            openNotif({
                              vertical: "top",
                              horizontal: "center",
                              msg: "عملیات با موفقیت انجام شد.",
                              severity: "success",
                            });
                          }
                        });
                      }
                    }}
                    row
                  >
                    <FormControlLabel
                      value={true}
                      control={<Radio />}
                      label="فعال"
                    />
                    <FormControlLabel
                      value={false}
                      control={<Radio />}
                      label="غیر فعال"
                    />
                  </RadioGroup>
                </FormControl>
              </Grid>
              {timeRange[i].active === true && (
                <Grid
                  container
                  justifyContent="start"
                  alignItems="start"
                  gap={1}
                  mt={1}
                >
                  <Grid>
                    <TimePicker
                      value={item?.start}
                      onChange={(newTime) => {
                        const objects = timeRange;
                        objects[i].start = newTime;
                        setTimeRange(objects);
                      }}
                      label="از"
                    />
                  </Grid>
                  <Grid>
                    <TimePicker
                      value={item?.end}
                      onChange={(newTime) => {
                        const objects = timeRange;
                        objects[i].end = newTime;
                        setTimeRange(objects);
                      }}
                      label="تا"
                    />
                  </Grid>
                </Grid>
              )}

              {timeRange[i].active === true && (
                <Grid container mt={1}>
                  <Button
                    variant="contained"
                    disabled={item?.end < item?.start}
                    onClick={() => {
                      dispatch(
                        provincePolicyEditTimeRange({
                          time_range: timeRange,
                        })
                      ).then((r) => {
                        if (r.payload.error) {
                          openNotif({
                            vertical: "top",
                            horizontal: "center",
                            msg: r.payload.error,
                            severity: "error",
                          });
                        } else {
                          openNotif({
                            vertical: "top",
                            horizontal: "center",
                            msg: "عملیات با موفقیت انجام شد.",
                            severity: "success",
                          });
                        }
                      });
                    }}
                  >
                    ارسال
                  </Button>
                </Grid>
              )}
            </Grid>
          </Grid>
        ))}
      </Grid>
    </Grid>
  );
};
