import React, { useContext, useEffect, useState } from "react";
import { Grid } from "../../../../components/grid/Grid";
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";
import {
  provincePolicyEditTradeTimeRange,
  provincePolicyGetTradeTimeRagnge,
} from "../../services/province-policy-edit-trade-time-range";

const DEFAULT_RANGE = {
  start_time: "01:00:00",
  end_time: "24:00:00",
  allow: false,
};

export const ProvincePolicyTradeTimeRange = () => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);
  const [range, setRange] = useState(DEFAULT_RANGE);

  useEffect(() => {
    dispatch(provincePolicyGetTradeTimeRagnge()).then((r) => {
      const d = r.payload.data;
      setRange({
        start_time: d.startTime,
        end_time: d.endTime,
        allow: d.allow,
      });
    });
  }, [dispatch]);

  const handleActiveChange = (e) => {
    const nextActive = e.target.value === "true";
    const nextRange = { ...range, allow: nextActive };
    setRange(nextRange);

    if (!nextActive) {
      dispatch(provincePolicyEditTradeTimeRange({ allow: false })).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",
          });
        }
      });
    }
  };

  const handleSave = () => {
    dispatch(provincePolicyEditTradeTimeRange(range)).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",
        });
      }
    });
  };

  return (
    <Grid
      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)" }}>
        بازه نمایش معاملات
      </Typography>

      <Grid container xs={12} alignItems="end" justifyContent="start">
        <Grid container direction="column">
          <FormControl>
            <RadioGroup
              aria-labelledby="time-range-active"
              name="time-range-active"
              value={String(range.allow)}
              onChange={handleActiveChange}
              row
            >
              <FormControlLabel value="true" control={<Radio />} label="فعال" />
              <FormControlLabel
                value="false"
                control={<Radio />}
                label="غیر فعال"
              />
            </RadioGroup>
          </FormControl>
        </Grid>

        {range.allow && (
          <Grid
            container
            justifyContent="start"
            alignItems="start"
            gap={1}
            mt={1}
          >
            <Grid>
              <TimePicker
                value={range.start_time}
                onChange={(newTime) =>
                  setRange((prev) => ({ ...prev, start_time: newTime }))
                }
                label="از"
              />
            </Grid>
            <Grid>
              <TimePicker
                value={range.end_time}
                onChange={(newTime) =>
                  setRange((prev) => ({ ...prev, end_time: newTime }))
                }
                label="تا"
              />
            </Grid>
          </Grid>
        )}

        {range.allow && (
          <Grid container mt={1}>
            <Button
              variant="contained"
              disabled={range.end_time < range.start_time}
              onClick={handleSave}
            >
              ارسال
            </Button>
          </Grid>
        )}
      </Grid>
    </Grid>
  );
};
