import { useContext, useEffect, useState } from "react";
import { Button, TextField } from "@mui/material";
import { Grid } from "../../../../components/grid/Grid";
import { useDispatch, useSelector } from "react-redux";
import { AppContext } from "../../../../contexts/AppContext";
import { useFormik } from "formik";
import { CLOSE_MODAL } from "../../../../lib/redux/slices/appSlice";
import * as Yup from "yup";
import { provinceEditMarketRequestService } from "../../services/trade-panel-edit-market-request";
import { ProvinceMarketRequestService } from "../../services/trade-panel-market-request";
import { paymentGetDeadLines } from "../../services/payment-get-deadlines";
import { useProvinceName } from "../../../../utils/getProvinceName";
import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith";

function TradePanelPurchaseModal({ item, updateTable, isEdit = false }) {
  const [paymentDeadlineDays, setPaymentDeadlineDays] = useState(null);
  const [fullyRendered, setFullyRendered] = useState(false);
  const selectedSubUser = useSelector(
    (state) => state.userSlice.selectedSubUser
  );
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);

  const validationSchema = Yup.object({
    killCapacity: Yup.number()
      .required("این فیلد اجباری است!")
      .typeError("لطفا عدد وارد کنید!")

      .max(
        isEdit ? Infinity : item?.remainQuantity,
        `مقدار وارد شده بیشتر از مانده قابل خرید است`
      ),

    paymentDeadlineDays: Yup.number().when([], {
      is: () => paymentDeadlineDays !== null,
      then: Yup.number()
        .required("این فیلد الزامی است")
        .min(1, "حداقل مقدار باید 1 باشد")
        .max(
          paymentDeadlineDays,
          `حداکثر مقدار باید ${paymentDeadlineDays} باشد`
        ),
      otherwise: Yup.number()
        .required("این فیلد اجباری است!")
        .typeError("لطفا عدد وارد کنید!"),
    }),
  });

  useEffect(() => {
    dispatch(
      paymentGetDeadLines({
        role_key: checkPathStartsWith("province")
          ? selectedSubUser?.key || ""
          : "",
      })
    ).then((r) => {
      setFullyRendered(true);
      const isEnabled = r?.payload?.data?.paymentDeadline;

      const days = r?.payload?.data?.paymentDeadlineDays;

      if (isEnabled === true && days > 0) {
        setPaymentDeadlineDays(days);
      }
    });
  }, [selectedSubUser?.key]);

  const provinceName = useProvinceName();

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

  const formik = useFormik({
    initialValues: {
      killCapacity: item?.killCapacity || "",
      paymentDeadlineDays: item?.paymentDeadlineDays || "",
    },

    validationSchema,
    onSubmit: (values) => {
      const payload = {
        recive_time: "12 - 14",
        kill_capacity: parseInt(values.killCapacity),
        payment_deadline_days: parseInt(values.paymentDeadlineDays),
        ...(isEdit ? { key: item.key } : { poultry_request_key: item.key }),
      };

      const service = isEdit
        ? provinceEditMarketRequestService
        : ProvinceMarketRequestService;

      const remainTime =
        provinceName === "test" || provinceName === "hamedan" ? 30 : 5;

      dispatch(service(payload))
        .then((r) => {
          // Check if there's an error (error message string from service)
          const errorMessage = r?.payload?.error || r?.error;

          if (errorMessage) {
            // Error occurred (e.g., "باقی مانده اعلام نیاز مرغدار کمتر از درخواست شماست!")
            dispatch(CLOSE_MODAL());
            openNotif({
              vertical: "top",
              horizontal: "center",
              msg: errorMessage,
              severity: "error",
            });
          } else {
            openNotif({
              vertical: "top",
              horizontal: "center",
              msg: `عملیات با موفقیت انجام شد. برای نهایی کردن خرید ${remainTime} دقیقه فرصت دارد در غیر اینصورت خرید شما حذف می شود.`,
              severity: "success",
            });
            dispatch(CLOSE_MODAL());
            // Call updateTable after successful submit to refresh all tables
            if (updateTable && typeof updateTable === "function") {
              updateTable();
            }
          }
        })
        .catch((error) => {
          // Handle unexpected errors
          const errorMessage =
            error?.response?.data?.result ||
            error?.message ||
            "مشکلی پیش آمده است!";

          dispatch(CLOSE_MODAL());
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: errorMessage,
            severity: "error",
          });
        });
    },
  });

  return (
    <Grid xs={12} container gap={2}>
      <TextField
        name="killCapacity"
        label="تعداد کشتار"
        variant="outlined"
        type="number"
        fullWidth
        value={formik.values.killCapacity}
        onChange={formik.handleChange}
        onBlur={formik.handleBlur}
        error={
          formik.touched.killCapacity && Boolean(formik.errors.killCapacity)
        }
        helperText={formik.touched.killCapacity && formik.errors.killCapacity}
      />
      <TextField
        name="paymentDeadlineDays"
        label={
          paymentDeadlineDays
            ? `حداکثر مهلت تسویه (حداکثر ${paymentDeadlineDays} روز)`
            : "حداکثر مهلت تسویه (روز)"
        }
        variant="outlined"
        type="number"
        fullWidth
        value={formik.values.paymentDeadlineDays}
        onChange={formik.handleChange}
        onBlur={formik.handleBlur}
        error={
          formik.touched.paymentDeadlineDays &&
          Boolean(formik.errors.paymentDeadlineDays)
        }
        helperText={
          formik.touched.paymentDeadlineDays &&
          formik.errors.paymentDeadlineDays
        }
      />

      <Button
        disabled={!fullyRendered}
        fullWidth
        type="submit"
        variant="contained"
        color="primary"
        onClick={formik?.handleSubmit}
      >
        {isEdit ? "ویرایش" : "ثبت"}
      </Button>
    </Grid>
  );
}

export default TradePanelPurchaseModal;
