import { useContext, useEffect, useState } from "react";
import { AppContext } from "../../../../contexts/AppContext";
import { useDispatch } from "react-redux";
import { useFormik } from "formik";
import { Yup } from "../../../../lib/yup/yup";
import { Grid } from "../../../../components/grid/Grid";
import { Autocomplete, IconButton, TextField, Typography } from "@mui/material";
import { SPACING } from "../../../../data/spacing";
import SearchIcon from "@mui/icons-material/Search";
import { extractProvinceFromAddress } from "../../../../utils/address";
import { provinceGetNationalDocumentsService } from "../../../province/services/province-get-national-documents";
import {
  slaughterEditBuyerDataService,
  slaughterSubmitBuyerDataService,
} from "../../../slaughter-house/services/slaughter-house-submit-buyer";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";

export const validationSchemaForSlaughterAddBuyer = (isEdit, isRealPerson) =>
  Yup.object({
    mobile: Yup.string()
      .required("این فیلد اجباری است!")
      .min(11, "شماره موبایل باید 11 رقم باشد")
      .max(11, "شماره موبایل باید 11 رقم باشد")
      .matches(/^09\d{9}$/, "شماره موبایل باید با 09 شروع شود و 11 رقم باشد"),
    firstName: Yup.string()
      .required("این فیلد اجباری است!")
      .typeError("لطفا فیلد را به درستی وارد کنید!"),
    lastName: Yup.string()
      .required("این فیلد اجباری است!")
      .typeError("لطفا فیلد را به درستی وارد کنید!"),
    unit_name: Yup.string()
      .required("این فیلد اجباری است!")
      .typeError("لطفا فیلد را به درستی وارد کنید!"),
    province: Yup.string()
      .required("این فیلد اجباری است!")
      .typeError("لطفا فیلد را به درستی وارد کنید!"),
    city: Yup.string()
      .required("این فیلد اجباری است!")
      .typeError("لطفا فیلد را به درستی وارد کنید!"),
    nationalId:
      isRealPerson === false && isEdit
        ? Yup.string().nullable()
        : Yup.string()
            .required("این فیلد اجباری است!")
            .matches(/^\d{10,11}$/, "شناسه باید 10 یا 11 رقم و فقط عدد باشد"),
  });

export const handleSubmitForSlaughterAddBuyer = (
  formik,
  dispatch,
  isEdit,
  tableData,
  updateTable,
  openNotif,
  DRAWER,
  selectedSubUser,
  isRealPerson,
  buyerType
) => {
  if (isEdit) {
    const submitData = {
      mobile: formik.values.mobile,
      first_name: formik.values.firstName,
      last_name: formik.values.lastName,
      city: formik.values.city,
      province: formik.values.province,
      national_id: formik.values.nationalId,
      unit_name: formik.values.unit_name,
      role_key: selectedSubUser?.key || "",
      buyer_type: tableData?.buyerType,
      buyer_key: tableData?.key,
      role: getRoleFromUrl(),
    };

    dispatch(slaughterEditBuyerDataService(submitData)).then((r) => {
      updateTable();
      if (r.payload.error) {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: r.payload.error,
          severity: "error",
        });
      } else {
        dispatch(DRAWER({ right: false, bottom: false, content: null }));

        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: "عملیات با موفقیت انجام شد.",
          severity: "success",
        });
      }
    });
  } else {
    const submitData = {
      role: getRoleFromUrl(),
      mobile: formik.values.mobile,
      first_name: formik.values.firstName,
      last_name: formik.values.lastName,
      city: formik.values.city,
      province: formik.values.province,
      unit_name: formik.values.unit_name,
      national_id: !isRealPerson ? null : formik.values.nationalId,
      role_key: selectedSubUser?.key,
      ...(!isRealPerson && {
        isRealPerson: false,
        info_value: formik.values.nationalId,
      }),
      ...(buyerType && {
        buyer_type: buyerType,
      }),
    };

    // if (IS_STEWARD) {
    //   submitData.name = formik.values.unitName;
    //   delete submitData.unit_name;
    // }
    dispatch(slaughterSubmitBuyerDataService(submitData)).then((r) => {
      updateTable();
      if (r.payload.error) {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: r.payload.error,
          severity: "error",
        });
      } else {
        dispatch(DRAWER({ right: false, bottom: false, content: null }));

        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: "عملیات با موفقیت انجام شد.",
          severity: "success",
        });
      }
    });
  }
};

export const handleSetFormDataFromTableDataForSlaughterAddBuyer = (
  tableData,
  formik
) => {
  const formData = {
    mobile: tableData.mobile || "",
    firstName: tableData.firstName || "",
    lastName: tableData.lastName || "",
    province: tableData.province || "",
    city: tableData.city || "",
    nationalId: tableData.nationalId || "",
    unit_name: tableData?.unitName || "",
  };

  formik.setValues(formData);

  setTimeout(() => {
    formik.validateForm();
  }, 1);
};

export const handleSetFormDataFromUserDataForSlaughterAddBuyer = (
  userData,
  formik
) => {
  if (userData) {
    const formData = {
      mobile: userData.mobile || "",
      firstName: userData.firstName || "",
      lastName: userData.lastName || "",
      province: userData.province || "",
      city: userData.city || "",
      nationalId: userData.nationalId || "",
      unit_name: userData?.unitName || "",
    };

    formik.setValues(formData);

    setTimeout(() => {
      formik.validateForm();
    }, 1);
  }
};

export const InquiryForSlaughterAddBuyer = ({
  notFound,
  setNotFound,
  setUserData,
  formik,
  isEdit,
  isRealPerson,
  provinceData,
}) => {
  const [inquiryInProgress, setInquiryInProgress] = useState(false);

  const [openNotif] = useContext(AppContext);
  const dispatch = useDispatch();

  const formik2 = useFormik({
    initialValues: {
      personType: isRealPerson ? "real" : "legal", // real | legal
      nationalCode: "",
    },
    validationSchema: Yup.object({
      personType: Yup.string().oneOf(["real", "legal"]).required(),
      nationalCode:
        isEdit && isRealPerson
          ? Yup.string().nullable()
          : Yup.string()
              .required("این فیلد اجباری است!")
              .when("personType", {
                is: "real",
                then: (schema) =>
                  schema
                    .length(10, "کد ملی باید 10 رقم باشد")
                    .matches(/^\d{10}$/, "کد ملی باید فقط شامل اعداد باشد"),
                otherwise: (schema) =>
                  schema
                    .length(11, "شناسه ملی حقوقی باید 11 رقم باشد")
                    .matches(
                      /^\d{11}$/,
                      "شناسه ملی حقوقی باید فقط شامل اعداد باشد"
                    ),
              }),
    }),
    validateOnMount: isEdit ? false : true,
  });

  const handleInquiry = async () => {
    if (!formik2.isValid || inquiryInProgress) {
      return;
    }

    const nationalCode = formik2.values.nationalCode;

    setInquiryInProgress(true);
    setNotFound(false);
    setUserData(null);

    let personData = null;
    let selectedGuild = null;

    try {
      if (!isRealPerson) {
        const url = `https://pay.rasadyar.com/national-documents?info=${encodeURIComponent(
          nationalCode
        )}&type=unit`;
        const res = await fetch(url);
        const json = await res.json();

        if (json?.status && json?.data) {
          const d = json.data;
          const extractedProvince = extractProvinceFromAddress(
            d.address || "",
            provinceData
          );
          const aggregatedUserData = {
            mobile: d.mobile,
            firstName: d.name || "",
            lastName: d.name || "",
            unitName: d.unitName || "",
            province: d.state || extractedProvince || "",
            city: d.city || "",
            nationalId: d.nationalCode || nationalCode,
          };
          setUserData(aggregatedUserData);
          handleSetFormDataFromUserDataForSlaughterAddBuyer(
            aggregatedUserData,
            formik
          );

          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "اطلاعات حقوقی با موفقیت دریافت شد.",
            severity: "success",
          });
        } else {
          setNotFound(true);
          formik.setFieldValue("nationalId", nationalCode);
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "اطلاعات حقوقی برای این شناسه یافت نشد، لطفا اطلاعات را به صورت دستی ثبت کنید.",
            severity: "warning",
          });
        }
        return;
      } else {
        const personResponse = await dispatch(
          provinceGetNationalDocumentsService({
            info: nationalCode,
            type: "person",
          })
        );

        if (personResponse.payload?.error) {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: personResponse.payload.error,
            severity: "error",
          });
        } else if (
          personResponse.payload?.data?.status &&
          personResponse.payload?.data?.data
        ) {
          personData = personResponse.payload.data.data;
        } else {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "اطلاعات فردی یافت نشد.",
            severity: "warning",
          });
        }

        const guildResponse = await dispatch(
          provinceGetNationalDocumentsService({
            info: nationalCode,
            type: "guild",
          })
        );

        if (guildResponse.payload?.error) {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: guildResponse.payload.error,
            severity: "error",
          });
        } else if (
          guildResponse.payload?.data?.status &&
          guildResponse.payload?.data?.data
        ) {
          const guildData = guildResponse.payload.data.data;
          const guildArray = Array.isArray(guildData) ? guildData : [guildData];
          if (guildArray.length > 0) {
            const activeGuildIndex = guildArray.findIndex(
              (g) => g.licenseStatus === "فعال/صادر شده"
            );
            selectedGuild =
              guildArray[activeGuildIndex !== -1 ? activeGuildIndex : 0];
          } else {
            openNotif({
              vertical: "top",
              horizontal: "center",
              msg: "اطلاعات صنفی برای این کد ملی یافت نشد.",
              severity: "warning",
            });
          }
        } else {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "اطلاعات صنفی برای این کد ملی یافت نشد.",
            severity: "warning",
          });
        }

        if (!personData && !selectedGuild) {
          setNotFound(true);
          formik.setFieldValue("nationalId", nationalCode);
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "اطلاعاتی برای این کد ملی یافت نشد، لطفا اطلاعات را به صورت دستی ثبت کنید.",
            severity: "warning",
          });
          return;
        }

        const layerTwo = selectedGuild?.layerTwo || {};
        const aggregatedUserData = {
          mobile:
            layerTwo.mobilenumber ||
            personData?.mobile ||
            layerTwo.phonenumber ||
            "",
          firstName: personData?.firstName || "",
          lastName: personData?.lastName || "",
          unitName:
            selectedGuild?.title ||
            layerTwo.corporationName ||
            layerTwo.unionName ||
            "",
          province: selectedGuild?.state || "",
          city: selectedGuild?.city || "",
          nationalId:
            personData?.nationalId ||
            layerTwo.nationalcode ||
            selectedGuild?.nationalId ||
            nationalCode,
        };
        setUserData(aggregatedUserData);
        handleSetFormDataFromUserDataForSlaughterAddBuyer(
          aggregatedUserData,
          formik
        );

        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: "اطلاعات با موفقیت دریافت شد.",
          severity: "success",
        });
      }
    } finally {
      setInquiryInProgress(false);
    }
  };

  useEffect(() => {
    if (notFound) {
      formik.setFieldValue("mobile", formik2.values.mobile);
    }
  }, [notFound]);

  return (
    <Grid container xs={12}>
      <Typography mt={2}>
        {"استعلام "}
        {!isRealPerson ? "شناسه ملی حقوقی" : "کد ملی"}
      </Typography>
      <Grid mt={SPACING.SMALL} display="flex" width={1}>
        <TextField
          fullWidth
          id="nationalCode"
          name="nationalCode"
          label={!isRealPerson ? "شناسه ملی حقوقی" : "کد ملی"}
          variant="outlined"
          value={formik2.values.nationalCode}
          error={Boolean(
            formik2.touched.nationalCode && formik2.errors.nationalCode
          )}
          onChange={formik2.handleChange}
          onBlur={formik2.handleBlur}
          helperText={
            formik2.touched.nationalCode && formik2.errors.nationalCode
          }
          inputProps={{
            maxLength: !isRealPerson ? 11 : 10,
          }}
        />
        <IconButton
          disabled={!formik2.isValid || inquiryInProgress}
          aria-label="search"
          color="primary"
          onClick={handleInquiry}
        >
          <SearchIcon />
        </IconButton>
      </Grid>
    </Grid>
  );
};

export const SlaughterAddBuyerForm = ({
  formik,
  provinceData,
  cityData,
  notFound,
  isRealPerson,
}) => {
  return (
    <Grid
      container
      justifyContent="space-between"
      alignItems="start"
      xs={12}
      direction="column"
      gap={2}
    >
      <TextField
        fullWidth
        id="nationalId"
        name="nationalId"
        label={!isRealPerson ? "شناسه ملی حقوقی" : "کد ملی"}
        disabled={true}
        variant="outlined"
        value={formik.values.nationalId}
        onChange={formik.handleChange}
        onBlur={formik.handleBlur}
        helperText={formik.touched.nationalId && formik.errors.nationalId}
      />
      <TextField
        fullWidth
        id="mobile"
        label="شماره موبایل"
        variant="outlined"
        value={formik.values.mobile}
        onChange={formik.handleChange}
        onBlur={formik.handleBlur}
        error={Boolean(formik.errors.mobile)}
        helperText={formik.errors.mobile}
      />
      <TextField
        fullWidth
        id="firstName"
        label="نام"
        variant="outlined"
        value={formik.values.firstName}
        onChange={formik.handleChange}
        onBlur={formik.handleBlur}
        helperText={formik.touched.firstName && formik.errors.firstName}
        error={Boolean(formik.errors.firstName)}
      />
      <TextField
        fullWidth
        id="lastName"
        label="نام خانوادگی"
        variant="outlined"
        value={formik.values.lastName}
        onChange={formik.handleChange}
        onBlur={formik.handleBlur}
        helperText={formik.touched.lastName && formik.errors.lastName}
        error={Boolean(formik.errors.lastName)}
      />
      <TextField
        fullWidth
        id="unit_name"
        label="نام واحد"
        variant="outlined"
        value={formik.values.unit_name}
        onChange={formik.handleChange}
        onBlur={formik.handleBlur}
        helperText={formik.touched.unit_name && formik.errors.unit_name}
        error={Boolean(formik.errors.unit_name)}
      />

      <Autocomplete
        style={{ width: "100%" }}
        disablePortal
        id="province"
        options={
          provinceData
            ? provinceData.map((i) => ({ id: i.name, label: i.name }))
            : []
        }
        isOptionEqualToValue={(option, value) => option.id === value.id}
        onChange={(e, value) => {
          formik.setFieldValue("province", value ? value.id : "");
          formik.setFieldValue("city", "");
        }}
        value={
          formik.values.province
            ? {
                id: formik.values.province,
                label: formik.values.province,
              }
            : null
        }
        renderInput={(params) => (
          <TextField {...params} label="استان را انتخاب کنید" />
        )}
      />
      {!notFound && (
        <Typography variant="caption" color="error">
          استان: {formik.values.province}
        </Typography>
      )}

      <Autocomplete
        minWidth={210}
        style={{ width: "100%" }}
        disablePortal
        id="city"
        options={
          cityData ? cityData.map((i) => ({ id: i.name, label: i.name })) : []
        }
        isOptionEqualToValue={(option, value) => option.id === value.id}
        onChange={(e, value) => {
          formik.setFieldValue("city", value ? value.id : "");
        }}
        value={
          formik.values.city
            ? {
                id: formik.values.city,
                label: formik.values.city,
              }
            : null
        }
        renderInput={(params) => (
          <TextField {...params} label="شهر را انتخاب کنید" />
        )}
      />

      {!notFound && (
        <Typography variant="caption" color="error">
          شهر: {formik.values.city}
        </Typography>
      )}
    </Grid>
  );
};
