import React, { useContext, useEffect, useState } from "react";
import { Grid } from "../../../../components/grid/Grid";
import SearchIcon from "@mui/icons-material/Search";
import {
  Autocomplete,
  Button,
  IconButton,
  Radio,
  RadioGroup,
  FormControlLabel,
  TextField,
  Typography,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
} from "@mui/material";
import { useFormik } from "formik";
import { Yup } from "../../../../lib/yup/yup";
import { SPACING } from "../../../../data/spacing";
import {
  slaughterEditBuyerDataService,
  slaughterSubmitBuyerDataService,
} from "../../services/slaughter-house-submit-buyer";
import { AppContext } from "../../../../contexts/AppContext";
import { useDispatch, useSelector } from "react-redux";
import { DRAWER } from "../../../../lib/redux/slices/appSlice";
import {
  slaughterGetCitiesService,
  slaughterGetProvinceService,
} from "../../services/slaughter-get-provinces";
import { provinceGetNationalDocumentsService } from "../../../province/services/province-get-national-documents";
import { LabelField } from "../../../../components/label-field/LabelField";
import { extractProvinceFromAddress } from "../../../../utils/address";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { useLocation } from "react-router-dom";
import { inspectorGetKillHousesService } from "../../../inspector/services/inspector-get-kill-houses";
import { slaughterGetStewardsForAllocateService } from "../../services/slaughter-get-guilds-for-allocate";

// userType enums = steward | steward_true | steward_legal | _true | _legal

export const SlaughterSellCarcassOutProvinceAddBuyer = ({
  updateTable,
  isEdit,
  data,
  defaultPersonType,
  defaultNationalCode,
  userType,
}) => {
  const IS_STEWARD = userType === "steward";
  const IS_ADMINX = getRoleFromUrl() === "AdminX";
  const { pathname } = useLocation();
  const IS_OUT_PROVINCE = pathname.includes("out-province");
  const { inspectorGetKillHouses } = useSelector(
    (state) => state.inspectorSlice
  );
  const [openNotif] = useContext(AppContext);
  const [userData, setUserData] = useState(null);
  const [notFound, setNotFound] = useState(false);
  const [inquiryInProgress, setInquiryInProgress] = useState(false);
  const [lockedFields, setLockedFields] = useState({});
  const dispatch = useDispatch();
  const [provinceData, setProvinceData] = useState([]);
  const [cityData, setCityData] = useState([]);
  const [killhouses, setKillhouses] = useState([]);
  const [stewardsData, setStewardsData] = useState([]);

  const formik = useFormik({
    initialValues: {
      mobile: "",
      firstName: "",
      lastName: "",
      unit_name: "",
      province: "",
      city: "",
      nationalId: "",
      role_key: "",
      type: "",
    },
    validationSchema: 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:
        defaultPersonType === "legal" && isEdit
          ? Yup.string().nullable()
          : Yup.string()
              .required("این فیلد اجباری است!")
              .matches(/^\d{10,11}$/, "شناسه باید 10 یا 11 رقم و فقط عدد باشد"),
      role_key:
        IS_ADMINX && IS_OUT_PROVINCE
          ? Yup.string().required("این فیلد اجباری است!")
          : Yup.string(),
      type:
        IS_ADMINX && IS_OUT_PROVINCE
          ? Yup.string().oneOf(["Steward", "KillHouse"]).required()
          : Yup.string().nullable(),
    }),
    validateOnMount: true,
  });

  useEffect(() => {
    const d = inspectorGetKillHouses?.map((item) => {
      return { name: item.name, key: item.key, killer: item.killer };
    });
    setKillhouses(d);
  }, [inspectorGetKillHouses]);

  useEffect(() => {
    if (IS_OUT_PROVINCE && IS_ADMINX) {
      if (formik.values.type === "KillHouse") {
        dispatch(inspectorGetKillHousesService());
      } else {
        dispatch(
          slaughterGetStewardsForAllocateService({
            free: true,
          })
        ).then((r) => {
          setStewardsData(r.payload.data || []);
        });
      }
      formik.validateForm();
    }
  }, [formik.values.type]);

  const formik2 = useFormik({
    initialValues: {
      personType: defaultPersonType || "real", // real | legal
      nationalCode: defaultNationalCode || "",
    },
    validationSchema: Yup.object({
      personType: Yup.string().oneOf(["real", "legal"]).required(),
      nationalCode:
        isEdit && defaultPersonType === "real"
          ? 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,
  });

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

  // Fallback: ensure values are populated from data when editing
  useEffect(() => {
    if (isEdit && data?.buyer) {
      if (data.buyer.isRealPerson === false) {
        formik2.setFieldValue("personType", "legal", false);
      }
      if (data.buyer.nationalCode) {
        // formik2.setFieldValue("nationalCode", data.buyer.nationalCode, false);
      } else if (data.buyer.parentLegalPersonNationalCode) {
        formik2.setFieldValue(
          "nationalCode",
          IS_STEWARD
            ? data?.buyer?.nationalId
            : data.buyer.parentLegalPersonNationalCode,
          false
        );
      }
    }
  }, [isEdit, data]);

  useEffect(() => {
    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 || "",
        ...(IS_ADMINX &&
          IS_OUT_PROVINCE && {
            type: formik.values?.type,
            role_key: formik.values?.role_key,
          }),
      };

      formik.setValues(formData);

      const fieldKeys = [
        "nationalId",
        "mobile",
        "firstName",
        "lastName",
        "unit_name",
        "city",
        "type",
        "role_key",
      ];
      const locks = fieldKeys.reduce((acc, key) => {
        const value = userData[key];
        acc[key] = Boolean(value && value !== "");
        return acc;
      }, {});
      // Province is not locked so user can change it
      locks.province = false;
      setLockedFields(locks);
      setTimeout(() => {
        formik.validateForm();
      }, 1);
    }
  }, [userData]);

  useEffect(() => {
    if (isEdit) {
      const formData = {
        mobile: data.mobile || "",
        firstName: data.firstName || "",
        lastName: data.lastName || "",
        province: data.province || "",
        city: data.city || "",
        nationalId: (IS_STEWARD ? defaultNationalCode : data.nationalId) || "",
        unit_name: data?.unitName || "",
        ...(IS_ADMINX &&
          IS_OUT_PROVINCE && {
            type: formik.values?.type,
            role_key: formik.values?.role_key,
          }),
      };

      formik.setValues(formData);
      setLockedFields({});
      // formik2.setFieldValue(
      //   "nationalCode",
      //   data.national_code ||
      //     data.nationalCode ||
      //     data.national_id ||
      //     data.nationalId ||
      //     ""
      // );
      setTimeout(() => {
        formik.validateForm();
      }, 1);
    }
  }, [isEdit]);

  useEffect(() => {
    dispatch(slaughterGetProvinceService()).then((r) => {
      setProvinceData(r.payload.data);
    });
  }, []);

  useEffect(() => {
    if (formik.values.province) {
      setCityData(
        [],
        dispatch(slaughterGetCitiesService(formik.values.province)).then(
          (r) => {
            setCityData(r.payload.data);
          }
        )
      );
    }
  }, [formik.values.province]);

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

    const nationalCode = formik2.values.nationalCode;
    const personType = formik2.values.personType;

    setInquiryInProgress(true);
    setNotFound(false);
    setUserData(null);
    setLockedFields({});

    let personData = null;
    let selectedGuild = null;

    try {
      if (personType === "legal") {
        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: "",
            firstName: d.name || "",
            lastName: d.name || "",
            unitName: (IS_STEWARD ? d.unitName : d.unitName) || "",
            province: d.state || extractedProvince || "",
            city: "", // User will select city manually
            nationalId: d.nationalCode || nationalCode,
            ...(IS_ADMINX &&
              IS_OUT_PROVINCE && {
                type: formik.values?.type,
                role_key: formik.values?.role_key,
              }),
          };
          setUserData(aggregatedUserData);
          formik2.setFieldValue(
            "nationalCode",
            aggregatedUserData.nationalId || nationalCode
          );
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "اطلاعات حقوقی با موفقیت دریافت شد.",
            severity: "success",
          });
        } else {
          setNotFound(true);
          formik.setFieldValue("nationalId", nationalCode);
          setLockedFields({});
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "اطلاعات حقوقی برای این شناسه یافت نشد، لطفا اطلاعات را به صورت دستی ثبت کنید.",
            severity: "warning",
          });
        }
        return;
      }

      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);
        setLockedFields({});
        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,
        ...(IS_ADMINX &&
          IS_OUT_PROVINCE && {
            type: formik.values?.type,
            role_key: formik.values?.role_key,
          }),
      };

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

  return (
    <Grid
      container
      justifyContent="space-between"
      alignItems="center"
      xs={12}
      direction="column"
      gap={2}
    >
      {!isEdit && (
        <Grid container xs={12}>
          <LabelField label="نوع شخص">
            <RadioGroup
              row
              name="personType"
              value={formik2.values.personType}
              onChange={(e) => {
                const value = e.target.value;
                formik2.setFieldValue("personType", value);
                // reset previous results when toggling type
                setUserData(null);
                setNotFound(false);
                setLockedFields({});
                formik.resetForm({
                  values: {
                    mobile: "",
                    firstName: "",
                    lastName: "",
                    unit_name: "",
                    province: "",
                    city: "",
                    nationalId: "",
                  },
                });
              }}
            >
              <FormControlLabel
                value="real"
                control={<Radio />}
                label="حقیقی"
              />
              <FormControlLabel
                value="legal"
                control={<Radio />}
                label="حقوقی"
              />
            </RadioGroup>
          </LabelField>

          <Typography mt={2}>
            {"استعلام "}
            {formik2.values.personType === "legal"
              ? "شناسه ملی حقوقی"
              : "کد ملی"}
          </Typography>
          <Grid mt={SPACING.SMALL} display="flex" width={1}>
            <TextField
              fullWidth
              id="nationalCode"
              name="nationalCode"
              label={
                formik2.values.personType === "legal"
                  ? "شناسه ملی حقوقی"
                  : "کد ملی"
              }
              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: formik2.values.personType === "legal" ? 11 : 10,
              }}
            />
            <IconButton
              disabled={!formik2.isValid || inquiryInProgress}
              aria-label="search"
              color="primary"
              onClick={handleNationalInquiry}
            >
              <SearchIcon />
            </IconButton>
          </Grid>
        </Grid>
      )}

      {userData || notFound || isEdit ? (
        <Grid
          container
          justifyContent="space-between"
          alignItems="start"
          xs={12}
          direction="column"
          gap={2}
        >
          <TextField
            fullWidth
            id="nationalId"
            name="nationalId"
            label={
              formik2.values.personType === "legal"
                ? "شناسه ملی حقوقی"
                : "کد ملی"
            }
            disabled={true}
            variant="outlined"
            value={
              formik2.values.personType === "legal"
                ? formik2.values.nationalCode
                : formik.values.nationalId
            }
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            helperText={formik.touched.nationalId && formik.errors.nationalId}
            InputProps={{ readOnly: Boolean(lockedFields.nationalId) }}
          />
          {IS_OUT_PROVINCE && IS_ADMINX ? (
            <>
              <LabelField label="انتخاب نوع واحد">
                <RadioGroup
                  row
                  name="type"
                  value={formik.values.type}
                  onChange={(e) => {
                    const value = e.target.value;
                    formik.setFieldValue("type", value);
                  }}
                >
                  <FormControlLabel
                    value="Steward"
                    control={<Radio />}
                    label="مباشر"
                  />
                  <FormControlLabel
                    value="KillHouse"
                    control={<Radio />}
                    label="کشتارگاه"
                  />
                </RadioGroup>
              </LabelField>
              {formik.values.type === "Steward" ? (
                <Autocomplete
                  fullWidth
                  disablePortal
                  id="role_key"
                  options={stewardsData.map((item) => {
                    return {
                      key: item?.key,
                      label: `${item?.name || ""} - ${
                        item?.user?.fullname || ""
                      } (${item?.user?.mobile || ""})`,
                    };
                  })}
                  onChange={(event, value) => {
                    formik.setFieldValue("role_key", value?.key || "");
                  }}
                  value={
                    formik.values.role_key
                      ? {
                          key: formik.values.role_key,
                          label:
                            stewardsData.find(
                              (item) => item.key === formik.values.role_key
                            )?.name || "",
                        }
                      : null
                  }
                  isOptionEqualToValue={(option, value) =>
                    option.key === value.key
                  }
                  label="انتخاب مباشر"
                  renderInput={(params) => (
                    <TextField fullWidth {...params} label={"انتخاب مباشر"} />
                  )}
                />
              ) : formik.values.type === "KillHouse" ? (
                <FormControl
                  fullWidth
                  error={
                    formik.errors.selectedOption &&
                    formik.touched.selectedOption
                  }
                >
                  <InputLabel>انتخاب کشتارگاه یا کشتارکن</InputLabel>
                  <Select
                    label="انتخاب کشتارگاه یا کشتارکن"
                    id="role_key"
                    name="role_key"
                    //   value={formik.values.role_key}
                    onChange={(e) => {
                      const [key] = e.target.value.split("#");
                      formik.setFieldValue("role_key", key);
                    }}
                    onBlur={formik.handleBlur}
                  >
                    {killhouses?.map((option) => (
                      <MenuItem
                        key={option}
                        value={`${option.key + "#" + option.killer}`}
                      >
                        {option.killer
                          ? `کشتارکن ${option.name}`
                          : `کشتارگاه ${option.name}`}
                      </MenuItem>
                    ))}
                  </Select>
                  {formik.errors.role_key && formik.touched.role_key && (
                    <div>{formik.errors.role_key}</div>
                  )}
                </FormControl>
              ) : null}
            </>
          ) : null}
          <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}
            disabled={Boolean(lockedFields.firstName)}
            InputProps={{ readOnly: Boolean(lockedFields.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}
            disabled={Boolean(lockedFields.lastName)}
            InputProps={{ readOnly: Boolean(lockedFields.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}
            disabled={Boolean(lockedFields.unit_name)}
            InputProps={{ readOnly: Boolean(lockedFields.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 }))
                : []
            }
            disabled={Boolean(lockedFields.province)}
            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%" }}
            disabled={!formik.values.province || Boolean(lockedFields.city)}
            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>
      ) : (
        <Typography variant="body2" color="text.secondary">
          برای نمایش فرم، ابتدا استعلام کد ملی را انجام دهید.
        </Typography>
      )}

      {(userData || notFound || isEdit) && (
        <Grid container xs={12}>
          <Button
            fullWidth
            variant="contained"
            disabled={!formik.isValid}
            onClick={() => {
              if (isEdit) {
                const submitData = {
                  buyer_type: IS_STEWARD ? "Steward" : "Guilds",
                  buyer_key: data?.key,
                  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,
                  type: formik.values.type,
                  role_key: formik.values.role_key,
                };

                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 = {
                  mobile: formik.values.mobile,
                  buyer_type: IS_STEWARD ? "Steward" : "Guilds",
                  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:
                    formik2.values.personType === "legal"
                      ? null
                      : formik.values.nationalId,
                  type: formik.values.type,
                  role_key: formik.values.role_key,
                  ...(formik2.values.personType === "legal" && {
                    isRealPerson: false,
                    info_value: formik2.values.nationalCode,
                  }),
                };

                // 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",
                      });
                    }
                  }
                );
              }
            }}
          >
            {isEdit ? "ویرایش" : "ثبت"}
          </Button>
        </Grid>
      )}
    </Grid>
  );
};
