import {
  FormControlLabel,
  Button,
  Radio,
  Typography,
  TextField,
} from "@mui/material";
import { useEffect, useState, useContext } from "react";
import { useDispatch } from "react-redux";

import { useFormik } from "formik";

import { Grid } from "../../../../components/grid/Grid";
import { Yup } from "../../../../lib/yup/yup";

import { directEditBuyingVerification } from "../../services/direct-edit-buying-verification";
import { directBuyingVerification } from "../../services/direct-buying-verification";

import { paymentGetDeadLines } from "../../services/payment-get-deadlines";
import { paymentEditDeadLines } from "../../services/payment-edit-deadlines";

import { AppContext } from "../../../../contexts/AppContext";

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

  const [directVerificationBuying, setDirectBuyingVerifivation] =
    useState(false);
  const [paymentDeadLine, setPaymentDeadLine] = useState(false);

  const formik = useFormik({
    initialValues: {
      payment_deadline_days: "",
    },
    validationSchema: Yup.object({
      payment_deadline_days: Yup.number()
        .required("این فیلد اجباری است")
        .min(0, "حداقل مقدار باید 0 باشد")
        .max(100, "حداکثر مقدار باید 100 باشد"),
    }),
  });

  useEffect(() => {
    dispatch(directBuyingVerification()).then((r) => {
      const isMandatory = r.payload.data?.poultryCodeMandatory;
      setDirectBuyingVerifivation(isMandatory);
    });

    dispatch(paymentGetDeadLines()).then((r) => {
      const isPaymentDeadline = r.payload?.data?.paymentDeadline ?? false;
      setPaymentDeadLine(isPaymentDeadline);

      if (isPaymentDeadline && r.payload?.data?.paymentDeadlineDays) {
        formik.setFieldValue(
          "payment_deadline_days",
          r.payload.data.paymentDeadlineDays
        );
      }
    });
  }, []);

  const handleChangeDirectBuyingVerification = (e) => {
    dispatch(directEditBuyingVerification({ poultry_code_mandatory: e })).then(
      () => {
        dispatch(directBuyingVerification()).then((r) => {
          setDirectBuyingVerifivation(r.payload?.data?.poultryCodeMandatory);
        });
      }
    );
  };

  const handleChangePaymentDeadLines = (value) => {
    const isActive = value === true;
    if (!isActive) {
      dispatch(
        paymentEditDeadLines({
          payment_deadline: false,
          payment_deadline_days: 0,
        })
      ).then((r) => {
        if (r.error) {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "مشکلی پیش آمده است!",
            severity: "error",
          });
        } else {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "غیرفعال شد.",
            severity: "success",
          });
        }
      });
    }

    setPaymentDeadLine(isActive);
  };

  const handleSubmitPaymentDeadline = () => {
    dispatch(
      paymentEditDeadLines({
        payment_deadline: true,
        payment_deadline_days: parseInt(formik.values.payment_deadline_days),
      })
    ).then((r) => {
      if (r.error) {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: "مشکلی پیش آمده است!",
          severity: "error",
        });
      } else {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: "تنظیمات با موفقیت ذخیره شد.",

          severity: "success",
        });
      }
    });
  };

  return (
    <>
      <Grid
        container
        alignItems="center"
        isPolicy
        gap={2}
        sx={{
          width: {
            xs: "100%",
            sm: "48%",
            lg: "19%",
          },
        }}
      >
        <Typography variant="body1">ثبت کداحراز خرید مستقیم مرغدار</Typography>
        <Grid xs={12} container justifyContent="space-between">
          <FormControlLabel
            control={
              <Radio
                name="item6"
                checked={directVerificationBuying === true}
                onClick={() => {
                  handleChangeDirectBuyingVerification(true);
                }}
              />
            }
            label="اجباری"
          />
          <FormControlLabel
            control={
              <Radio
                checked={directVerificationBuying === false}
                onClick={() => {
                  handleChangeDirectBuyingVerification(false);
                }}
                name="item6"
              />
            }
            label="اختیاری"
          />
        </Grid>
      </Grid>

      <Grid
        container
        alignItems="center"
        isPolicy
        gap={2}
        sx={{
          width: {
            xs: "100%",
            sm: "48%",
            lg: "24%",
            nxl: "19%",
          },
        }}
      >
        <Typography variant="body1">حداکثر مهلت تسویه با مرغدار</Typography>

        <Grid xs={12} container justifyContent="space-between">
          <FormControlLabel
            control={
              <Radio
                name="item6"
                checked={paymentDeadLine === true}
                onClick={() => handleChangePaymentDeadLines(true)}
              />
            }
            label="فعال"
          />

          <FormControlLabel
            control={
              <Radio
                checked={paymentDeadLine === false}
                onClick={() => handleChangePaymentDeadLines(false)}
                name="item6"
              />
            }
            label="غیر فعال"
          />
        </Grid>

        {paymentDeadLine !== false && (
          <>
            <Grid xs={12}>
              <TextField
                size="small"
                label="تعداد روز"
                name="payment_deadline_days"
                value={formik.values.payment_deadline_days}
                onChange={formik.handleChange}
                error={
                  formik.touched.payment_deadline_days &&
                  Boolean(formik.errors.payment_deadline_days)
                }
                helperText={
                  formik.touched.payment_deadline_days &&
                  formik.errors.payment_deadline_days
                }
                required
                type="number"
                inputProps={{ min: 0, max: 100 }}
              />
            </Grid>
            <Grid container xs={12} md={2}>
              <Button
                variant="contained"
                disabled={
                  !formik.values.payment_deadline_days ||
                  formik.errors.payment_deadline_days
                }
                onClick={handleSubmitPaymentDeadline}
              >
                ارسال
              </Button>
            </Grid>
          </>
        )}
      </Grid>
    </>
  );
};
