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 {
  provincePolicyGetDirectPurchaseBarLimitation,
  provincePolicyEditDirectPurchaseBarLimitation,
} from "../../services/province-policy-direct-purchase-bar-limitation";

const DEFAULT_LIMITATION = {
  id: null,
  key: null,
  active: false,
  start_time: "08:00:00",
  end_time: "18:00:00",
  allowBuying: null,
};

export const ProvincePolicyDirectPurchaseBarLimitation = () => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);
  const [limitation, setLimitation] = useState(DEFAULT_LIMITATION);

  useEffect(() => {
    dispatch(provincePolicyGetDirectPurchaseBarLimitation()).then((r) => {
      if (r.payload?.data) {
        const d = r.payload.data;
        setLimitation({
          id: d.id,
          key: d.key,
          active: d.active,
          start_time: d.startTime,
          end_time: d.endTime,
          allowBuying: d.allowBuying ?? null,
        });
      }
    });
  }, [dispatch]);

  const handleActiveChange = (e) => {
    const nextActive = e.target.value === "true";
    const nextLimitation = { ...limitation, active: nextActive };
    setLimitation(nextLimitation);

    if (!nextActive) {
      dispatch(
        provincePolicyEditDirectPurchaseBarLimitation({
          id: limitation.id,
          data: { active: false },
        })
      ).then((r) => {
        if (r.payload?.error) {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: r.payload.error,
            severity: "error",
          });
        } else if (r.payload?.data) {
          const d = r.payload.data;
          setLimitation((prev) => ({
            ...prev,
            id: d.id ?? prev.id,
            key: d.key ?? prev.key,
            active: d.active ?? prev.active,
            start_time: d.startTime ?? prev.start_time,
            end_time: d.endTime ?? prev.end_time,
            allowBuying: d.allowBuying ?? prev.allowBuying,
          }));
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "عملیات با موفقیت انجام شد.",
            severity: "success",
          });
        }
      });
    }
  };

  const handleAllowBuyingChange = (e) => {
    const value = e.target.value === "بلی";
    setLimitation((prev) => ({ ...prev, allowBuying: value }));
  };

  const handleSave = () => {
    dispatch(
      provincePolicyEditDirectPurchaseBarLimitation({
        id: limitation.id,
        data: {
          active: limitation.active,
          start_time: limitation.start_time,
          end_time: limitation.end_time,
          allow_buying: limitation.allowBuying,
        },
      })
    ).then((r) => {
      if (r.payload?.error) {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: r.payload.error,
          severity: "error",
        });
      } else if (r.payload?.data) {
        const d = r.payload.data;
        setLimitation({
          id: d.id ?? limitation.id,
          key: d.key ?? limitation.key,
          active: d.active ?? limitation.active,
          start_time: d.startTime ?? limitation.start_time,
          end_time: d.endTime ?? limitation.end_time,
          allowBuying: d.allowBuying ?? limitation.allowBuying,
        });
        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: "19%",
          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="limitation-active"
              name="limitation-active"
              value={String(limitation.active)}
              onChange={handleActiveChange}
              row
            >
              <FormControlLabel value="true" control={<Radio />} label="فعال" />
              <FormControlLabel
                value="false"
                control={<Radio />}
                label="غیر فعال"
              />
            </RadioGroup>
          </FormControl>
        </Grid>

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

        {limitation.active && (
          <Grid mt={2} xs={12}>
            <Typography
              sx={{
                color: "rgba(0, 0, 0, 0.6)",
                mb: 1,
                fontSize: 16,
                width: "fit-content",
              }}
              justifyContent="flex-start"
            >
              اجازه خرید دارد؟
            </Typography>
            <FormControl>
              <RadioGroup
                aria-labelledby="allow-buying-radio"
                name="allow-buying-radio"
                value={
                  limitation.allowBuying === true
                    ? "بلی"
                    : limitation.allowBuying === false
                    ? "خیر"
                    : ""
                }
                onChange={handleAllowBuyingChange}
                row
              >
                <FormControlLabel value="بلی" control={<Radio />} label="بلی" />
                <FormControlLabel value="خیر" control={<Radio />} label="خیر" />
              </RadioGroup>
            </FormControl>
          </Grid>
        )}

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