import React, { useContext, useEffect, useState } from "react";
import { Grid } from "../../../../components/grid/Grid";
import {
  Button,
  FormControl,
  FormControlLabel,
  Radio,
  RadioGroup,
  Typography,
} from "@mui/material";
import { Yup } from "../../../../lib/yup/yup";
import { useFormik } from "formik";
import { useDispatch } from "react-redux";
import { AppContext } from "../../../../contexts/AppContext";
import {
  getAutomaticDirectBuyingPermissionState,
  provinceAutomaticDirectBuyingPermission,
} from "../../services/province-automatic-direct-buying-permission";
import TimePicker from "../../../../components/date-picker/CustomDatePicker";

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

  const [value, setValue] = useState("inactive");
  const [data, setData] = useState();

  useEffect(() => {
    dispatch(getAutomaticDirectBuyingPermissionState()).then((r) => {
      setData(r.payload.data);
      if (r.payload.data?.allow) {
        setValue("active");
      }
    });
  }, []);

  const formik = useFormik({
    initialValues: {
      hour: "",
      hour2: "",
      minute: "",
      minute2: "",
    },
    validationSchema: Yup.object({
      hour: Yup.string().required("این فیلد اجباری است"),
      hour2: Yup.string().required("این فیلد اجباری است"),
    }),
  });

  useEffect(() => {
    formik.validateForm();
  }, []);

  useEffect(() => {
    if (data?.allow) {
      formik.setFieldValue("hour", data?.startTime);
      formik.setFieldValue("hour2", data?.endTime);
      formik.validateForm();
    }
  }, [data]);

  const handleChangeRadioButton = (event) => {
    setValue(event.target.value);
  };

  return (
    <Grid
      container
      xs={12}
      alignItems="center"
      justifyContent="start"
      isPolicy
      gap={2}
      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="demo-controlled-radio-buttons-group"
              name="controlled-radio-buttons-group"
              value={value}
              onChange={handleChangeRadioButton}
              row
            >
              <FormControlLabel
                value="active"
                control={<Radio />}
                label="فعال"
              />
              <FormControlLabel
                onClick={() => {
                  dispatch(
                    provinceAutomaticDirectBuyingPermission({
                      allow: false,
                    })
                  ).then((r) => {
                    if (r.error) {
                      openNotif({
                        vertical: "top",
                        horizontal: "center",
                        msg: "مشکلی پیش آمده است!",
                        severity: "error",
                      });
                    } else {
                      openNotif({
                        vertical: "top",
                        horizontal: "center",
                        msg: "عملیات با موفقیت انجام شد.",
                        severity: "success",
                      });
                    }
                  });
                }}
                value="inactive"
                control={<Radio />}
                label="غیر فعال"
              />
            </RadioGroup>
          </FormControl>
        </Grid>
        {value === "active" && (
          <Grid
            container
            justifyContent="start"
            alignItems="start"
            gap={1}
            mt={1}
          >
            <Grid>
              <TimePicker
                value={formik.values.hour}
                onChange={(newTime) => {
                  formik.setFieldValue("hour", newTime);
                }}
                label="از"
              />
            </Grid>
            <Grid>
              <TimePicker
                value={formik.values.hour2}
                onChange={(newTime) => {
                  formik.setFieldValue("hour2", newTime);
                }}
                label="تا"
              />
            </Grid>
          </Grid>
        )}
      </Grid>
      {value === "active" && (
        <Grid container>
          <Button
            variant="contained"
            disabled={
              !formik.isValid || formik.values.hour > formik.values.hour2
            }
            onClick={() => {
              dispatch(
                provinceAutomaticDirectBuyingPermission({
                  allow: true,
                  start_time: formik.values.hour,
                  end_time: formik.values.hour2,
                })
              ).then((r) => {
                if (r.error) {
                  openNotif({
                    vertical: "top",
                    horizontal: "center",
                    msg: "مشکلی پیش آمده است!",
                    severity: "error",
                  });
                } else {
                  openNotif({
                    vertical: "top",
                    horizontal: "center",
                    msg: "عملیات با موفقیت انجام شد.",
                    severity: "success",
                  });
                }
              });
            }}
          >
            ارسال
          </Button>
        </Grid>
      )}
    </Grid>
  );
};
