import {
  Autocomplete,
  Button,
  Chip,
  Divider,
  FormControl,
  FormHelperText,
  IconButton,
  InputLabel,
  MenuItem,
  Select,
  TextField,
  Typography,
} from "@mui/material";

import React, { useEffect } from "react";
import { useFormik } from "formik";

import DeleteIcon from "@mui/icons-material/Delete";
import AddIcon from "@mui/icons-material/Add";

import { AppContext } from "../../../../contexts/AppContext";
import { Yup } from "../../../../lib/yup/yup";
import { Grid } from "../../../../components/grid/Grid";
import { SPACING } from "../../../../data/spacing";
import {
  DRAWER,
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { cityGetProvinces } from "../../../city/services/CityGetProvinces";
import { cityGetCity } from "../../../city/services/city-get-city";
import { useDispatch } from "react-redux";
import { useState } from "react";
import { DatePicker } from "@mui/x-date-pickers";
import moment from "moment";
import SearchIcon from "@mui/icons-material/Search";
import { provinceCheckUserExistence } from "../../services/province-check-user-existence";
import { useContext } from "react";
import { provinceRegisterUser } from "../../services/province-register-user";
import { provinceGetUserProfiles } from "../../services/province-get-user-profiles";
import { NumberInput } from "../../../../components/number-format-custom/NumberFormatCustom";
import { provinceGetKillHouses } from "../../services/province-get-kill-houses";
import { UserInfo } from "./components/userInfo";
import { CarPelak } from "../../../../components/car-pelak/CarPelak";

export const ProvinceSubmitUser = (id) => {
  const [openNotif] = useContext(AppContext);

  const [provinceData, setProvinceData] = useState([]);
  const [cityData, setCityData] = useState([]);
  const [provinceKey, setProvinceKey] = useState();
  const [cityKey, setCityKey] = useState();

  const [killHouseProvinceKey, setKillHouseProvinceKey] = useState();
  const [killHouseVetProvinceKey, setKillHouseVetProvinceKey] = useState();
  const [killHouseCityKey, setKillHouseCityKey] = useState();
  const [killHouseVetCityKey, setKillHouseVetCityKey] = useState();

  const [poultryProvinceKey, setPoultryProvincekey] = useState();
  const [poultryCityKey, setPoultryCityKey] = useState();

  const [OperatorProvinceKey, setOperatorProvinceKey] = useState();
  const [OperatorCityKey, setOperatorCityKey] = useState();

  const [userChecked, setUserChecked] = useState(false);

  const [isExistProvince, setIsExistProvince] = useState(true);

  const [userData, setUserData] = useState();

  const dispatch = useDispatch();

  const formik = useFormik({
    initialValues: {
      mobile: "",
      fname: "",
      lname: "",
      nationalcode: "",
      password: "",
      birthday: moment(Date()).format("YYYY-MM-DD hh:mm:ss"),
    },
    validationSchema: Yup.object({
      mobile: Yup.number()
        .required("این فیلد اجباری است!")
        .typeError("لطفا فیلد را به صورت عددی وارد کنید!")
        .test("len", "شماره تلفن باید با 0 شروع شود", (val, context) => {
          return context.originalValue && context.originalValue.startsWith("0");
        })
        .test("len", "شماره تماس 11 رقم باید باشد", (val, context) => {
          if (context.originalValue) {
            return context.originalValue.length === 11;
          }
        }),
      fname: Yup.string()
        .required("این فیلد اجباری است!")
        .typeError("لطفا فیلد را پر کنید!"),
      lname: Yup.string()
        .required("این فیلد اجباری است!")
        .typeError("لطفا فیلد را پر کنید!"),
      nationalcode: Yup.number()
        .required("این فیلد اجباری است!")
        .test("len", "کد ملی میبایست ده رقم باشد.", (val, context) => {
          if (context.originalValue) {
            return context.originalValue.length === 10;
          }
        }),
      password: Yup.string()
        .required("این فیلد اجباری است!")
        .typeError("لطفا مقادیر را به درستی وارد کنید!"),
    }),
  });

  const formikKillHouse = useFormik({
    initialValues: {
      KillHousePostal: "",
      KillHouseCapacity: "",
      KillHousePhone: "",
      KillHouseAddress: "",
    },
    validationSchema: Yup.object({
      KillHousePostal: Yup.number().typeError(
        "لطفا فیلد را به درستی وارد کنید!"
      ),
      KillHouseCapacity: Yup.number().typeError(
        "لطفا فیلد را به صورت عددی وارد کنید!"
      ),
      KillHousePhone: Yup.number()
        .typeError("لطفا فیلد را به صورت عددی وارد کنید!")
        .test("len", "شماره تلفن باید با 0 شروع شود", (val, context) => {
          return context.originalValue && context.originalValue.startsWith("0");
        })
        .test("len", "شماره تماس 11 رقم باید باشد", (val, context) => {
          if (context.originalValue) {
            return context.originalValue.length === 11;
          }
        }),
      KillHouseAddress: Yup.string().typeError(
        "لطفا فیلد را به درستی وارد کنید!"
      ),
    }),
  });

  const formikKillHouseVet = useFormik({
    initialValues: {
      KillHouseVetPostal: "",
      KillHouseVetAddress: "",
    },
    validationSchema: Yup.object({
      KillHouseVetPostal: Yup.number().typeError(
        "لطفا فیلد را به درستی وارد کنید!"
      ),
      KillHouseVetAddress: Yup.string().typeError(
        "لطفا فیلد را به درستی وارد کنید!"
      ),
    }),
  });

  const formikCityProvince = useFormik({
    initialValues: {
      cityProvinceAddress: "",
      cityProvincePostalCode: "",
    },
    validationSchema: Yup.object({
      cityProvinceAddress: Yup.string()
        .required("این فیلد اجباری است!")
        .typeError("لطفا فیلد را به درستی وارد کنید!"),
      cityProvincePostalCode: Yup.number()
        .required("این فیلد اجباری است!")
        .typeError("لطفا فیلد را به درستی وارد کنید!"),
    }),
  });

  const formikUserBankInfo = useFormik({
    initialValues: {
      bankName: "",
      cardNumber: "",
      accountNumber: "",
      shabaNumber: "",
      accountHolder: "",
    },
    validationSchema: Yup.object({
      cardNumber: Yup.number().typeError("لطفا شماره کارتتان را وارد کنید!"),
      accountNumber: Yup.number().typeError("لطفا شماره حسابتان را وارد کنید!"),
      shabaNumber: Yup.number().typeError("لطفا شماره شبا را وارد کنید!"),
      accountHolder: Yup.string().typeError("لطفا نام صاحب حساب را وارد کنید!"),
    }),
  });

  const formikDriver = useFormik({
    initialValues: {
      type_car: "ایسوزو",
      type_weight: "سنگین",
      capocity: "",
      health_code: "",
    },
    validationSchema: Yup.object({
      type_weight: Yup.string().typeError("لطفا فیلد را به درستی وارد کنید!"),
      capocity: Yup.string().typeError("لطفا فیلد را به درستی وارد کنید!"),
      name: Yup.string().typeError("لطفا فیلد را به درستی وارد کنید!"),
      health_code: Yup.number()
        .typeError("لطفا فیلد را به درستی وارد کنید!")
        .required("این فیلد اجباری است!"),
    }),
  });

  useEffect(() => {
    formik.validateForm();
    formik2.validateForm();
    formikKillHouse.validateForm();
    formikCityProvince.validateForm();
    formikUserBankInfo.validateForm();
    formikDriver.validateForm();
    formikKillHouseVet.validateForm();
  }, []);

  const formik2 = useFormik({
    initialValues: {
      userInfoCheck: "",
    },
    validationSchema: Yup.object({
      userInfoCheck: Yup.number()
        .required("این فیلد اجباری است!")
        .typeError("لطفا فیلد را به درستی وارد کنید!"),
    }),
  });

  const [user, setUser] = React.useState();

  const handleChange = (event) => {
    setUser(event.target.value);
  };

  useEffect(() => {
    dispatch(LOADING_START());
    dispatch(cityGetProvinces())?.then((r) => {
      dispatch(LOADING_END());
      setProvinceData(r.payload.data);
    });
  }, []);

  useEffect(() => {
    dispatch(LOADING_END());
    if (provinceKey) {
      dispatch(LOADING_START());
      dispatch(cityGetCity(provinceKey)).then((r) => {
        setCityData(r.payload.data);
        setIsExistProvince(false);
        dispatch(LOADING_END());
      });
    } else if (killHouseProvinceKey) {
      dispatch(LOADING_START());
      dispatch(cityGetCity(killHouseProvinceKey)).then((r) => {
        setCityData(r.payload.data);
        setIsExistProvince(false);
        dispatch(LOADING_END());
      });
    } else if (killHouseVetProvinceKey) {
      dispatch(LOADING_START());
      dispatch(cityGetCity(killHouseVetProvinceKey)).then((r) => {
        setCityData(r.payload.data);
        setIsExistProvince(false);
        dispatch(LOADING_END());
      });
    } else if (OperatorProvinceKey) {
      dispatch(LOADING_START());
      dispatch(cityGetCity(OperatorProvinceKey)).then((r) => {
        setCityData(r.payload.data);
        setIsExistProvince(false);
        dispatch(LOADING_END());
      });
    } else if (poultryProvinceKey) {
      dispatch(LOADING_START());
      dispatch(cityGetCity(poultryProvinceKey)).then((r) => {
        setCityData(r.payload.data);
        setIsExistProvince(false);
        dispatch(LOADING_END());
      });
      dispatch(LOADING_END());
    }
  }, [
    provinceKey,
    killHouseProvinceKey,
    OperatorProvinceKey,
    poultryProvinceKey,
    killHouseVetProvinceKey,
  ]);

  const [userExist, setUserExist] = useState(false);

  const [driverPelak, setDriverPelak] = useState([]);

  const carPelakHandleChange = (pelak1, pelak2, pelak3, pelak4) => {
    setDriverPelak([pelak1, pelak2, pelak3, pelak4]);
  };

  useEffect(() => {
    if (userData) {
      setUserExist(true);
    } else if (formik.isValid && cityKey && provinceKey) {
      setUserExist(true);
    }
  }, [userData]);

  const isFormValid = (user) => {
    if (userData)
      switch (user) {
        case "Poultry":
          return !(userExist && poultryCityKey);
        case "KillHouse":
          return !(userExist && killHouseCityKey);
        case "Driver":
          return !(userExist && formikDriver.isValid);
        case "ProvinceOperator":
          return !(userExist && formikCityProvince.isValid);
        case "CityOperator":
          return !(userExist && formikCityProvince.isValid);
        case "VetFarm":
          return !(userExist && formikCityProvince.isValid);
        case "ProvinceInspector":
          return !(userExist && formikCityProvince.isValid);
        case "ProvinceFinancial":
          return !(userExist && formikCityProvince.isValid);
        case "KillHouseVet":
          return !(
            userExist &&
            killHouseVetProvinceKey &&
            killHouseVetCityKey &&
            formikKillHouseVet.isValid
          );
        default:
          return !(userExist && user);
      }
    else {
      return !(formik.isValid && cityKey && provinceKey);
    }
  };

  const [arrKillHouse, setArrKillHouse] = useState([
    {
      id: 0,
      killHouseAddress: "",
      postal: "",
      shift_work_from: "",
      shift_work_to: "",
      province: "",
      city: "",
      name: "",
      capacity: "",
      killing_race: "",
      phone: "",
      bankName: "",
      cardNumber: "",
      accountNumber: "",
      shabaNumber: "",
      accountHolder: "",
    },
  ]);

  const addInputkillHouse = () => {
    setArrKillHouse((prevState) => {
      return [
        ...prevState,
        {
          id: prevState.length,
          killHouseAddress: "",
          postal: "",
          shift_work_from: "",
          shift_work_to: "",
          province: "",
          city: "",
          name: "",
          capacity: "",
          killing_race: "",
          phone: "",
          bankName: "",
          cardNumber: "",
          accountNumber: "",
          shabaNumber: "",
          accountHolder: "",
        },
      ];
    });
  };

  const removeInputKillHouse = (e) => {
    let number = arrKillHouse.length - 1;

    if (number !== 0) {
      let filteredArrayPrice = arrKillHouse.filter((object, i) => i < number);

      setArrKillHouse(filteredArrayPrice);
    }
  };

  const handleChangeArrayKillHouse = (e, value, i) => {
    let val, itemName, itemIndex;
    if (value) {
      val = value;
      [itemName, , itemIndex] = e.target.id.split("-");
    } else {
      val = e.target.value;
      [itemName, itemIndex] = e.target.name.split("-");
    }
    if (itemName === "shift_work_from") {
      setArrKillHouse((prevState) => {
        const newState = prevState;
        newState[itemIndex].shift_work_from = val;
        return newState;
      });
    } else if (itemName === "shift_work_to") {
      setArrKillHouse((prevState) => {
        const newState = prevState;
        newState[itemIndex].shift_work_to = val;
        return newState;
      });
    } else if (itemName === "killHouseAddress") {
      setArrKillHouse((prevState) => {
        const newState = prevState;
        newState[itemIndex].killHouseAddress = val;
        return newState;
      });
    } else if (itemName === "postal") {
      setArrKillHouse((prevState) => {
        const newState = prevState;
        newState[itemIndex].postal = val;
        return newState;
      });
    } else if (itemName === "capacity") {
      setArrKillHouse((prevState) => {
        const newState = prevState;
        newState[itemIndex].capacity = Number(val);
        return newState;
      });
    } else if (itemName === "name") {
      setArrKillHouse((prevState) => {
        const newState = prevState;
        newState[itemIndex].name = val;
        return newState;
      });
    } else if (itemName === "killing_race") {
      setArrKillHouse((prevState) => {
        const newState = prevState;
        newState[itemIndex].killing_race = val;
        return newState;
      });
    } else if (itemName === "phone") {
      setArrKillHouse((prevState) => {
        const newState = prevState;
        newState[itemIndex].phone = Number(val);
        return newState;
      });
    } else if (itemName === "province") {
      dispatch(LOADING_START());
      dispatch(cityGetCity(val)).then((r) => {
        setCityData(r.payload.data);
        setIsExistProvince(false);
        dispatch(LOADING_END());
      });
      setArrKillHouse((prevState) => {
        const newState = prevState;
        newState[i].province = val;
        return newState;
      });
    } else if (itemName === "city") {
      setArrKillHouse((prevState) => {
        const newState = prevState;
        newState[i].city = val;
        return newState;
      });
    } else if (itemName === "bankName") {
      setArrKillHouse((prevState) => {
        const newState = prevState;
        newState[itemIndex].bankName = e.target.value;
        return newState;
      });
    } else if (itemName === "cardNumber") {
      setArrKillHouse((prevState) => {
        const newState = prevState;
        newState[itemIndex].cardNumber = Number(e.target.value);
        return newState;
      });
    } else if (itemName === "accountNumber") {
      setArrKillHouse((prevState) => {
        const newState = prevState;
        newState[itemIndex].accountNumber = Number(e.target.value);
        return newState;
      });
    } else if (itemName === "shabaNumber") {
      setArrKillHouse((prevState) => {
        const newState = prevState;
        newState[itemIndex].shabaNumber = Number(e.target.value);
        return newState;
      });
    } else if (itemName === "accountHolder") {
      setArrKillHouse((prevState) => {
        const newState = prevState;
        newState[itemIndex].accountHolder = e.target.value;
        return newState;
      });
    }
  };

  const [arr, setArr] = useState([
    {
      id: 0,
      uniqueID: "",
      poultryAddress: "",
      halls: "",
      systemCode: "",
      epidemiologicalCode: "",
      unitName: "",
      capacity: "",
      licenseNumber: "",
      postal: "",
      bankName: "",
      cardNumber: "",
      accountNumber: "",
      shabaNumber: "",
      accountHolder: "",
      province: "",
      city: "",
    },
  ]);

  const addInput = () => {
    setArr((prevState) => {
      return [
        ...prevState,
        {
          id: prevState.length,
          uniqueID: "",
          poultryAddress: "",
          halls: "",
          systemCode: "",
          epidemiologicalCode: "",
          unitName: "",
          capacity: "",
          licenseNumber: "",
          postal: "",
          bankName: "",
          cardNumber: "",
          accountNumber: "",
          shabaNumber: "",
          accountHolder: "",
          province: "",
          city: "",
        },
      ];
    });
  };

  const removeInput = (e) => {
    let number = arr.length - 1;

    if (number !== 0) {
      let filteredArrayPrice = arr.filter((object, i) => i < number);
      // let filteredArrayTime = arrPrices.filter((object, i) => i < number);

      setArr(filteredArrayPrice);
      // setArrPrices(filteredArrayTime);
    }
  };

  const handleChangeArray = (e) => {
    const [itemName, itemIndex] = e.target.name.split("-");
    if (itemName === "uniqueID") {
      setArr((prevState) => {
        const newState = prevState;
        newState[itemIndex].uniqueID = e.target.value;
        return newState;
      });
    } else if (itemName === "poultryAddress") {
      setArr((prevState) => {
        const newState = prevState;
        newState[itemIndex].poultryAddress = e.target.value;
        return newState;
      });
    } else if (itemName === "halls") {
      setArr((prevState) => {
        const newState = prevState;
        newState[itemIndex].halls = Number(e.target.value);
        return newState;
      });
    } else if (itemName === "systemCode") {
      setArr((prevState) => {
        const newState = prevState;
        newState[itemIndex].systemCode = Number(e.target.value);
        return newState;
      });
    } else if (itemName === "epidemiologicalCode") {
      setArr((prevState) => {
        const newState = prevState;
        newState[itemIndex].epidemiologicalCode = Number(e.target.value);
        return newState;
      });
    } else if (itemName === "ownerName") {
      setArr((prevState) => {
        const newState = prevState;
        newState[itemIndex].ownerName = e.target.value;
        return newState;
      });
    } else if (itemName === "unitName") {
      setArr((prevState) => {
        const newState = prevState;
        newState[itemIndex].unitName = e.target.value;
        return newState;
      });
    } else if (itemName === "capacity") {
      setArr((prevState) => {
        const newState = prevState;
        newState[itemIndex].capacity = Number(e.target.value);
        return newState;
      });
    } else if (itemName === "licenseNumber") {
      setArr((prevState) => {
        const newState = prevState;
        newState[itemIndex].licenseNumber = Number(e.target.value);
        return newState;
      });
    } else if (itemName === "postal") {
      setArr((prevState) => {
        const newState = prevState;
        newState[itemIndex].postal = Number(e.target.value);
        return newState;
      });
    } else if (itemName === "bankName") {
      setArr((prevState) => {
        const newState = prevState;
        newState[itemIndex].bankName = e.target.value;
        return newState;
      });
    } else if (itemName === "cardNumber") {
      setArr((prevState) => {
        const newState = prevState;
        newState[itemIndex].cardNumber = Number(e.target.value);
        return newState;
      });
    } else if (itemName === "accountNumber") {
      setArr((prevState) => {
        const newState = prevState;
        newState[itemIndex].accountNumber = Number(e.target.value);
        return newState;
      });
    } else if (itemName === "shabaNumber") {
      setArr((prevState) => {
        const newState = prevState;
        newState[itemIndex].shabaNumber = Number(e.target.value);
        return newState;
      });
    } else if (itemName === "accountHolder") {
      setArr((prevState) => {
        const newState = prevState;
        newState[itemIndex].accountHolder = e.target.value;
        return newState;
      });
    } else if (itemName === "province") {
      setPoultryProvincekey(e.target.value);
      setArr((prevState) => {
        const newState = prevState;
        newState[itemIndex].province = e.target.value;
        return newState;
      });
    } else if (itemName === "city") {
      setPoultryCityKey(e.target.value);
      setArr((prevState) => {
        const newState = prevState;
        newState[itemIndex].city = e.target.value;
        return newState;
      });
    }
  };

  const [killHouseData, setKillHouseData] = useState();
  const [killHouseKey, setKillHouseKey] = useState();
  useEffect(() => {
    if (user === "KillHouseVet") {
      dispatch(LOADING_START());
      dispatch(provinceGetKillHouses()).then((r) => {
        setKillHouseData(r.payload.data);
        dispatch(LOADING_END());
      });
    }
  }, [user]);

  return (
    <Grid
      container
      display="block"
      gap={SPACING.SMALL}
      direction="column"
      flex="1"
      height="100%"
      justifyContent="space-between"
    >
      <Grid container direction="column" gap={SPACING.SMALL}>
        {!userChecked && (
          <>
            <Typography>بررسی کاربر</Typography>
            <Grid display="flex" width={1}>
              <TextField
                fullWidth
                id="userInfoCheck"
                label="شماره موبایل، کد کاربری یا کد ملی"
                variant="outlined"
                value={formik2.values.userInfoCheck}
                error={
                  formik2.touched.userInfoCheck
                    ? Boolean(formik2.errors.userInfoCheck)
                    : null
                }
                onChange={formik2.handleChange}
                onBlur={formik2.handleBlur}
                helperText={
                  formik2.touched.userInfoCheck &&
                  Boolean(formik2.errors.userInfoCheck)
                    ? formik2.errors.userInfoCheck
                    : null
                }
              />

              <IconButton
                disabled={!formik2.isValid}
                aria-label="delete"
                color="primary"
                onClick={() => {
                  dispatch(LOADING_START());
                  dispatch(
                    provinceCheckUserExistence({
                      type: "check_user",
                      value: formik2.values.userInfoCheck,
                    })
                  ).then((r) => {
                    dispatch(LOADING_END());
                    if (r.error) {
                      if (r.error.message.includes("409")) {
                        openNotif({
                          vertical: "top",
                          horizontal: "center",
                          msg: "کاربر پیدا نشد، یک کاربر جدید بسازید!",
                          severity: "error",
                        });
                      }
                    } else {
                      if (r.payload.data) {
                        setUserData(r.payload.data.profile);
                      } else {
                        openNotif({
                          vertical: "top",
                          horizontal: "center",
                          msg: "مشکلی پیش آمده است!",
                          severity: "error",
                        });

                        dispatch(
                          DRAWER({
                            right: false,
                            bottom: false,
                            content: null,
                          })
                        );
                      }
                    }
                  });
                  setUserChecked(true);
                }}
              >
                <SearchIcon />
              </IconButton>
            </Grid>
            <FormHelperText>شماره موبایل با صفر شروع می‌شود!</FormHelperText>
          </>
        )}

        {userChecked && (
          <>
            {userData ? (
              <UserInfo userData={userData} />
            ) : (
              <>
                <Grid>
                  <TextField
                    id="fname"
                    label="نام"
                    variant="outlined"
                    sx={{ width: "100%" }}
                    value={formik.values.fname}
                    error={
                      formik.touched.fname ? Boolean(formik.errors.fname) : null
                    }
                    onChange={formik.handleChange}
                    onBlur={formik.handleBlur}
                    helperText={
                      formik.touched.fname && Boolean(formik.errors.fname)
                        ? formik.errors.fname
                        : null
                    }
                  />
                </Grid>
                <Grid>
                  <TextField
                    id="lname"
                    label="نام خانوادگی "
                    variant="outlined"
                    sx={{ width: "100%" }}
                    value={formik.values.lname}
                    error={
                      formik.touched.lname ? Boolean(formik.errors.lname) : null
                    }
                    onChange={formik.handleChange}
                    onBlur={formik.handleBlur}
                    helperText={
                      formik.touched.lname && Boolean(formik.errors.lname)
                        ? formik.errors.lname
                        : null
                    }
                  />
                </Grid>
                <Grid>
                  <TextField
                    id="mobile"
                    label="موبایل"
                    variant="outlined"
                    sx={{ width: "100%" }}
                    value={formik.values.mobile}
                    error={
                      formik.touched.mobile
                        ? Boolean(formik.errors.mobile)
                        : null
                    }
                    onChange={formik.handleChange}
                    onBlur={formik.handleBlur}
                    helperText={
                      formik.touched.mobile && Boolean(formik.errors.mobile)
                        ? formik.errors.mobile
                        : null
                    }
                  />
                </Grid>
                <Grid>
                  <DatePicker
                    fullWidth
                    label="تاریخ تولد"
                    id="birthday"
                    renderInput={(params) => <TextField {...params} />}
                    value={formik.values.birthday}
                    error={
                      formik.touched.birthday
                        ? Boolean(formik.errors.birthday)
                        : null
                    }
                    onChange={(e) => {
                      formik.setFieldValue(
                        "birthday",
                        moment(e).format("YYYY-MM-DD hh:mm:ss")
                      );
                    }}
                    onBlur={formik.handleBlur}
                    helperText={
                      formik.touched.birthday && Boolean(formik.errors.birthday)
                        ? formik.errors.birthday
                        : null
                    }
                  />
                </Grid>
                <Grid>
                  <Autocomplete
                    disablePortal
                    id="province"
                    options={provinceData?.map((i) => ({
                      id: i.key,
                      label: i.name,
                    }))}
                    onChange={(e, value) => {
                      setProvinceKey(value.id);
                    }}
                    renderInput={(params) => (
                      <TextField {...params} label="استان را انتخاب  کنید*" />
                    )}
                  />
                </Grid>

                <Grid>
                  <Autocomplete
                    disabled={isExistProvince}
                    disablePortal
                    id="city"
                    options={cityData?.map((i) => ({
                      id: i.key,
                      label: i.name,
                    }))}
                    onChange={(e, value) => {
                      setCityKey(value.id);
                    }}
                    renderInput={(params) => (
                      <TextField {...params} label="شهر را انتخاب  کنید*" />
                    )}
                  />
                </Grid>

                <Grid>
                  <TextField
                    id="password"
                    label="رمز عبور"
                    type="password"
                    variant="outlined"
                    sx={{ width: "100%" }}
                    value={formik.values.password}
                    error={
                      formik.touched.password
                        ? Boolean(formik.errors.password)
                        : null
                    }
                    onChange={formik.handleChange}
                    onBlur={formik.handleBlur}
                    helperText={
                      formik.touched.password && Boolean(formik.errors.password)
                        ? formik.errors.password
                        : null
                    }
                  />
                </Grid>

                <Grid>
                  <TextField
                    id="nationalcode"
                    label="کد ملی"
                    variant="outlined"
                    sx={{ width: "100%" }}
                    value={formik.values.nationalcode}
                    error={
                      formik.touched.nationalcode
                        ? Boolean(formik.errors.nationalcode)
                        : null
                    }
                    onChange={formik.handleChange}
                    onBlur={formik.handleBlur}
                    helperText={
                      formik.touched.nationalcode &&
                      Boolean(formik.errors.nationalcode)
                        ? formik.errors.nationalcode
                        : null
                    }
                  />
                </Grid>
              </>
            )}

            {userData && (
              <Grid>
                <FormControl>
                  <InputLabel id="demo-simple-select-helper-label">
                    {userData ? "افزودن نقش" : "نوع کاربر"}
                  </InputLabel>
                  <Select
                    fullWidth
                    value={user}
                    label={userData ? "افزودن نقش" : "نوع کاربر"}
                    onChange={handleChange}
                  >
                    {!userData.role.includes("CityOperator") && (
                      <MenuItem value={"CityOperator"}>شهرستان</MenuItem>
                    )}
                    {!userData.role.includes("ProvinceOperator") && (
                      <MenuItem value={"ProvinceOperator"}>استان</MenuItem>
                    )}
                    {!userData.role.includes("KillHouse") && (
                      <MenuItem value={"KillHouse"}>کشتارگاه</MenuItem>
                    )}
                    {/* {!userData.role.includes("Poultry") && ( */}
                    <MenuItem value={"Poultry"}>مرغدار</MenuItem>
                    {/* )} */}
                    {!userData.role.includes("VetFarm") && (
                      <MenuItem value={"VetFarm"}>دامپزشک</MenuItem>
                    )}

                    {!userData.role.includes("ProvinceFinancial") && (
                      <MenuItem value={"ProvinceFinancial"}>
                        اپراتور مالی
                      </MenuItem>
                    )}

                    {!userData.role.includes("ProvinceInspector") && (
                      <MenuItem value={"ProvinceInspector"}>
                        بازرس استان
                      </MenuItem>
                    )}

                    {!userData.role.includes("Driver") && (
                      <MenuItem value={"Driver"}>راننده</MenuItem>
                    )}

                    {!userData.role.includes("KillHouseVet") && (
                      <MenuItem
                        disabled={userData?.role.includes("KillHouseVet")}
                        value={"KillHouseVet"}
                      >
                        دامپزشک کشتارگاه
                      </MenuItem>
                    )}
                  </Select>
                </FormControl>
              </Grid>
            )}

            {/* start of poultry ============================================================================= */}

            {arr.map((item, i) => {
              return (
                <>
                  {user === "Poultry" && (
                    <>
                      <Divider>
                        <Chip label={"اطلاعات مرغدار " + (i + 1)} />
                      </Divider>

                      <Grid>
                        <TextField
                          inputProps={{
                            inputMode: "numeric",
                            pattern: "[0-9]*",
                          }}
                          error={false}
                          fullWidth
                          label="شناسه یکتا مرغدار"
                          variant="outlined"
                          onChange={handleChangeArray}
                          name={"uniqueID-" + i}
                        />
                      </Grid>

                      <Grid>
                        <FormControl fullWidth>
                          <InputLabel id="demo-simple-select-label">
                            استان *
                          </InputLabel>
                          <Select
                            fullWidth
                            id="province"
                            label="استان *"
                            onChange={handleChangeArray}
                            name={"province-" + i}
                          >
                            {provinceData?.map((i) => {
                              return [
                                <MenuItem key={i.key} value={i.key}>
                                  {i.name}
                                </MenuItem>,
                              ];
                            })}
                          </Select>
                        </FormControl>
                      </Grid>

                      <Grid>
                        <FormControl fullWidth disabled={isExistProvince}>
                          <InputLabel id="demo-simple-select-label">
                            شهر *
                          </InputLabel>
                          <Select
                            fullWidth
                            id="city"
                            label="شهر *"
                            onChange={handleChangeArray}
                            name={"city-" + i}
                          >
                            {cityData
                              ? cityData.map((i) => {
                                  return [
                                    <MenuItem key={i.key} value={i.key}>
                                      {i.name}
                                    </MenuItem>,
                                  ];
                                })
                              : []}
                          </Select>
                        </FormControl>
                      </Grid>

                      <Grid>
                        <TextField
                          error={false}
                          fullWidth
                          label="آدرس مرغداری"
                          variant="outlined"
                          onChange={handleChangeArray}
                          name={"poultryAddress-" + i}
                        />
                      </Grid>

                      <Grid>
                        <TextField
                          inputProps={{
                            inputMode: "numeric",
                            pattern: "[0-9]*",
                          }}
                          error={false}
                          fullWidth
                          label="تعداد سالن"
                          variant="outlined"
                          onChange={handleChangeArray}
                          name={"halls-" + i}
                        />
                      </Grid>

                      <Grid>
                        <TextField
                          inputProps={{
                            inputMode: "numeric",
                            pattern: "[0-9]*",
                          }}
                          error={false}
                          fullWidth
                          label="کد سیستمی"
                          variant="outlined"
                          onChange={handleChangeArray}
                          name={"systemCode-" + i}
                        />
                      </Grid>

                      <Grid>
                        <TextField
                          inputProps={{
                            inputMode: "numeric",
                            pattern: "[0-9]*",
                          }}
                          error={false}
                          fullWidth
                          label="کد اپیدمیولوژیک"
                          variant="outlined"
                          onChange={handleChangeArray}
                          name={"epidemiologicalCode-" + i}
                        />
                      </Grid>

                      <Grid>
                        <TextField
                          error={false}
                          fullWidth
                          label="نام واحد"
                          variant="outlined"
                          onChange={handleChangeArray}
                          name={"unitName-" + i}
                        />
                      </Grid>

                      {/* <Grid>
                        <TextField
                          error={false}
                          fullWidth
                          label="نام مالک"
                          variant="outlined"
                          onChange={handleChangeArray}
                          name={"ownerName-" + i}
                        />
                      </Grid> */}

                      <Grid>
                        <TextField
                          inputProps={{
                            inputMode: "numeric",
                            pattern: "[0-9]*",
                          }}
                          error={false}
                          fullWidth
                          label="ظرفیت"
                          variant="outlined"
                          onChange={handleChangeArray}
                          name={"capacity-" + i}
                        />
                      </Grid>

                      <Grid>
                        <TextField
                          inputProps={{
                            inputMode: "numeric",
                            pattern: "[0-9]*",
                          }}
                          error={false}
                          fullWidth
                          label="شماره گواهی بهداشتی"
                          variant="outlined"
                          onChange={handleChangeArray}
                          name={"licenseNumber-" + i}
                        />
                      </Grid>

                      <Grid>
                        <TextField
                          inputProps={{
                            inputMode: "numeric",
                            pattern: "[0-9]*",
                          }}
                          error={false}
                          fullWidth
                          label="کد پستی"
                          variant="outlined"
                          onChange={handleChangeArray}
                          name={"postal-" + i}
                        />
                      </Grid>

                      <Divider>
                        <Chip label={"اطلاعات بانکی مرغدار " + (i + 1)} />
                      </Divider>
                      <Grid>
                        <FormControl fullWidth>
                          <InputLabel id="demo-simple-select-label">
                            بانک
                          </InputLabel>
                          <Select
                            fullWidth
                            id="bankName"
                            label="بانک"
                            onChange={handleChangeArray}
                            name={"bankName-" + i}
                          >
                            <MenuItem value={"موسسه افضل توس"}>
                              موسسه افضل توس
                            </MenuItem>
                            <MenuItem value={"انصار"}>انصار</MenuItem>
                            <MenuItem value={"سپه"}>سپه</MenuItem>
                            <MenuItem value={"دی"}>دی</MenuItem>
                            <MenuItem value={"کاب"}>اقتصاد نوین</MenuItem>
                            <MenuItem value={"گردشگری"}>گردشگری</MenuItem>
                            <MenuItem value={"حکمت ایرانیان"}>
                              حکمت ایرانیان
                            </MenuItem>
                            <MenuItem value={"ایران زمین"}>ایران زمین</MenuItem>
                            <MenuItem value={"کشاورزی"}>کشاورزی</MenuItem>
                            <MenuItem value={"مسکن"}>مسکن</MenuItem>
                            <MenuItem value={"مهر ایران"}>مهر ایران</MenuItem>
                            <MenuItem value={"مهر اقتصاد"}>مهر اقتصاد</MenuItem>
                            <MenuItem value={"ملت"}>ملت</MenuItem>
                            <MenuItem value={"ملی"}>ملی</MenuItem>
                            <MenuItem value={"پارسیان"}>پارسیان</MenuItem>
                            <MenuItem value={"پاسارگاد"}>پاسارگاد</MenuItem>
                            <MenuItem value={"پست بانک ایران"}>
                              پست بانک ایران
                            </MenuItem>
                            <MenuItem value={"صادرات"}>صادرات</MenuItem>
                            <MenuItem value={"سامان"}>سامان</MenuItem>
                            <MenuItem value={"صنعت و معدن"}>
                              صنعت و معدن
                            </MenuItem>
                            <MenuItem value={"سرمایه"}>سرمایه</MenuItem>
                            <MenuItem value={"شهر"}>شهر</MenuItem>
                            <MenuItem value={"سینا"}>سینا</MenuItem>
                            <MenuItem value={"تجارت"}>تجارت</MenuItem>
                            <MenuItem value={"موسسه اعتباری توسعه"}>
                              موسسه اعتباری توسعه
                            </MenuItem>
                            <MenuItem value={"خاورمیانه"}>خاورمیانه</MenuItem>
                          </Select>
                        </FormControl>
                      </Grid>

                      <Grid>
                        <TextField
                          inputProps={{
                            inputMode: "numeric",
                            pattern: "[0-9]*",
                          }}
                          error={false}
                          fullWidth
                          label="شماره کارت"
                          variant="outlined"
                          onChange={handleChangeArray}
                          name={"cardNumber-" + i}
                        />
                      </Grid>

                      <Grid>
                        <TextField
                          inputProps={{
                            inputMode: "numeric",
                            pattern: "[0-9]*",
                          }}
                          error={false}
                          fullWidth
                          label="شماره حساب"
                          variant="outlined"
                          onChange={handleChangeArray}
                          name={"accountNumber-" + i}
                        />
                      </Grid>
                      <Grid>
                        <TextField
                          inputProps={{
                            inputMode: "numeric",
                            pattern: "[0-9]*",
                          }}
                          error={false}
                          fullWidth
                          label="شماره شبا"
                          variant="outlined"
                          onChange={handleChangeArray}
                          name={"shabaNumber-" + i}
                        />
                      </Grid>

                      <Grid>
                        <TextField
                          error={false}
                          fullWidth
                          label="نام صاحب حساب"
                          variant="outlined"
                          onChange={handleChangeArray}
                          name={"accountHolder-" + i}
                        />
                      </Grid>

                      <Grid container direction="row">
                        <IconButton aria-label="delete" color="success">
                          <AddIcon onClick={addInput} />
                        </IconButton>
                        <IconButton aria-label="delete" color="secondary">
                          <DeleteIcon onClick={removeInput} />
                        </IconButton>
                      </Grid>
                    </>
                  )}
                </>
              );
            })}

            {/* end of poultry ============================================================================= */}

            {user === "Driver" && (
              <>
                <Divider>
                  <Chip label="اطلاعات راننده" />
                </Divider>
                <Grid
                  container
                  mt={SPACING.SMALL}
                  gap={SPACING.SMALL}
                  alignSelf="center"
                  direction={{ xs: "column", sm: "row" }}
                >
                  <FormControl fullWidth>
                    <InputLabel id="demo-simple-select-label">
                      مدل خودرو
                    </InputLabel>
                    <Select
                      labelId="demo-simple-select-label"
                      id="type_car"
                      label="مدل خودرو"
                      value={formikDriver.values.type_car}
                      onChange={(e) => {
                        formikDriver.setFieldValue("type_car", e.target.value);
                      }}
                      error={
                        formikDriver.touched.type_car
                          ? Boolean(formikDriver.errors.type_car)
                          : null
                      }
                      onBlur={formikDriver.handleBlur}
                      helperText={
                        formikDriver.touched.type_car &&
                        Boolean(formikDriver.errors.type_car)
                          ? formikDriver.errors.type_car
                          : null
                      }
                    >
                      <MenuItem value={"ایسوزو"}>ایسوزو</MenuItem>
                      <MenuItem value={"نیسان"}>نیسان</MenuItem>
                      <MenuItem value={"وانت"}>وانت</MenuItem>
                      <MenuItem value={"اف ام"}>اف ام</MenuItem>
                      <MenuItem value={"کامیون"}>کامیون</MenuItem>
                      <MenuItem value={"هیوندا کروس"}>هیوندا کروس</MenuItem>
                      <MenuItem value={"بادسان"}>بادسان</MenuItem>
                      <MenuItem value={"هیوندا"}>هیوندا</MenuItem>
                      <MenuItem value={"کامیونت ایسوزو"}>
                        کامیونت ایسوزو
                      </MenuItem>
                      <MenuItem value={"خاور بنز"}>خاور بنز</MenuItem>
                    </Select>
                  </FormControl>

                  <NumberInput
                    allowLeadingZeros
                    thousandSeparator=","
                    fullWidth
                    id="capocity"
                    label="ظرفیت خودرو (قطعه)"
                    variant="outlined"
                    value={formikDriver.values.capocity}
                    error={
                      formikDriver.touched.capocity
                        ? Boolean(formikDriver.errors.capocity)
                        : null
                    }
                    onChange={formikDriver.handleChange}
                    onBlur={formikDriver.handleBlur}
                    helperText={
                      formikDriver.touched.capocity &&
                      Boolean(formikDriver.errors.capocity)
                        ? formikDriver.errors.capocity
                        : null
                    }
                  />

                  <TextField
                    fullWidth
                    id="health_code"
                    label="کد بهداشتی*"
                    variant="outlined"
                    value={formikDriver.values.health_code}
                    error={
                      formikDriver.touched.health_code
                        ? Boolean(formikDriver.errors.health_code)
                        : null
                    }
                    onChange={formikDriver.handleChange}
                    onBlur={formikDriver.handleBlur}
                    helperText={
                      formikDriver.touched.health_code &&
                      Boolean(formikDriver.errors.health_code)
                        ? formikDriver.errors.health_code
                        : null
                    }
                  />
                </Grid>
                <Typography>مشخصات پلاک</Typography>
                <Grid
                  mt={SPACING.TINY}
                  justifyContent="center"
                  sx={{ display: "flex", flexDirection: "row" }}
                >
                  <CarPelak width="100%" handleChange={carPelakHandleChange} />
                </Grid>
              </>
            )}
            {user === "KillHouse" && (
              <>
                <Divider>
                  <Chip label="اطلاعات پایه کشتارگاه" />
                </Divider>

                <Grid>
                  <Autocomplete
                    disablePortal
                    id="province"
                    options={provinceData?.map((i) => ({
                      id: i.key,
                      label: i.name,
                    }))}
                    onChange={(e, value) => {
                      setKillHouseProvinceKey(value.id);
                    }}
                    renderInput={(params) => (
                      <TextField {...params} label="استان کشتارگاه*" />
                    )}
                  />
                </Grid>

                <Grid>
                  <Autocomplete
                    disabled={isExistProvince}
                    disablePortal
                    id="city"
                    options={cityData?.map((i) => ({
                      id: i.key,
                      label: i.name,
                    }))}
                    onChange={(e, value) => {
                      setKillHouseCityKey(value.id);
                    }}
                    renderInput={(params) => (
                      <TextField {...params} label="شهر کشتارگاه*" />
                    )}
                  />
                </Grid>

                <Grid>
                  <TextField
                    id="KillHouseAddress"
                    label="آدرس کشتارگاه"
                    variant="outlined"
                    sx={{ width: "100%" }}
                    value={formikKillHouse.values.KillHouseAddress}
                    error={
                      formikKillHouse.touched.KillHouseAddress
                        ? Boolean(formikKillHouse.errors.KillHouseAddress)
                        : null
                    }
                    onChange={formikKillHouse.handleChange}
                    onBlur={formikKillHouse.handleBlur}
                    helperText={
                      formikKillHouse.touched.KillHouseAddress &&
                      Boolean(formikKillHouse.errors.KillHouseAddress)
                        ? formikKillHouse.errors.KillHouseAddress
                        : null
                    }
                  />
                </Grid>

                <Grid>
                  <TextField
                    id="KillHousePostal"
                    label="کد پستی"
                    variant="outlined"
                    sx={{ width: "100%" }}
                    value={formikKillHouse.values.KillHousePostal}
                    error={
                      formikKillHouse.touched.KillHousePostal
                        ? Boolean(formikKillHouse.errors.KillHousePostal)
                        : null
                    }
                    onChange={formikKillHouse.handleChange}
                    onBlur={formikKillHouse.handleBlur}
                    helperText={
                      formikKillHouse.touched.KillHousePostal &&
                      Boolean(formikKillHouse.errors.KillHousePostal)
                        ? formikKillHouse.errors.KillHousePostal
                        : null
                    }
                  />
                </Grid>

                {arrKillHouse?.map((item, i) => {
                  return (
                    <>
                      <Divider>
                        <Chip label={"کشتارگاه " + (i + 1)} />
                      </Divider>

                      <Grid>
                        <TextField
                          error={false}
                          fullWidth
                          label="نام کشتارگاه"
                          variant="outlined"
                          onChange={handleChangeArrayKillHouse}
                          name={"name-" + i}
                        />
                      </Grid>

                      <Grid>
                        <Autocomplete
                          disablePortal
                          id={"province"}
                          options={provinceData?.map((i) => ({
                            id: i.key,
                            label: i.name,
                          }))}
                          onChange={(e, value) => {
                            handleChangeArrayKillHouse(e, value.id, i);
                          }}
                          name={"province-" + i}
                          // onChange={handleChangeArrayKillHouse}
                          renderInput={(params) => (
                            <TextField
                              name={"province-" + i}
                              {...params}
                              label="استان *"
                            />
                          )}
                        />
                      </Grid>
                      <Grid>
                        <Autocomplete
                          disabled={!arrKillHouse[0]?.province}
                          // disablePortal
                          id="city"
                          options={cityData?.map((i) => ({
                            id: i.key,
                            label: i.name,
                          }))}
                          name={"city-" + i}
                          onChange={(e, value) => {
                            handleChangeArrayKillHouse(e, value.id, i);
                          }}
                          renderInput={(params) => (
                            <TextField
                              name={"city-" + i}
                              {...params}
                              label="شهر *"
                            />
                          )}
                        />
                      </Grid>

                      <Grid>
                        <TextField
                          error={false}
                          fullWidth
                          label="آدرس"
                          variant="outlined"
                          onChange={handleChangeArrayKillHouse}
                          name={"killHouseAddress-" + i}
                        />
                      </Grid>

                      <Grid>
                        <TextField
                          inputProps={{
                            inputMode: "numeric",
                            pattern: "[0-9]*",
                          }}
                          error={false}
                          fullWidth
                          label="کد پستی"
                          variant="outlined"
                          onChange={handleChangeArrayKillHouse}
                          name={"postal-" + i}
                        />
                      </Grid>

                      <Grid>
                        <TextField
                          inputProps={{
                            inputMode: "numeric",
                            pattern: "[0-9]*",
                          }}
                          error={false}
                          fullWidth
                          label="ظرفیت"
                          variant="outlined"
                          onChange={handleChangeArrayKillHouse}
                          name={"capacity-" + i}
                        />
                      </Grid>

                      <Grid>
                        <TextField
                          inputProps={{
                            inputMode: "numeric",
                            pattern: "[0-9]*",
                          }}
                          error={false}
                          fullWidth
                          label="موبایل"
                          variant="outlined"
                          onChange={handleChangeArrayKillHouse}
                          name={"phone-" + i}
                        />
                      </Grid>

                      <Divider>
                        <Chip label={"اطلاعات بانکی کشتارگاه " + (i + 1)} />
                      </Divider>
                      <Grid>
                        <FormControl fullWidth>
                          <InputLabel id="demo-simple-select-label">
                            بانک
                          </InputLabel>
                          <Select
                            fullWidth
                            id="bankName"
                            label="بانک"
                            onChange={handleChangeArrayKillHouse}
                            name={"bankName-" + i}
                          >
                            <MenuItem value={"موسسه افضل توس"}>
                              موسسه افضل توس
                            </MenuItem>
                            <MenuItem value={"انصار"}>انصار</MenuItem>
                            <MenuItem value={"سپه"}>سپه</MenuItem>
                            <MenuItem value={"دی"}>دی</MenuItem>
                            <MenuItem value={"کاب"}>اقتصاد نوین</MenuItem>
                            <MenuItem value={"گردشگری"}>گردشگری</MenuItem>
                            <MenuItem value={"حکمت ایرانیان"}>
                              حکمت ایرانیان
                            </MenuItem>
                            <MenuItem value={"ایران زمین"}>ایران زمین</MenuItem>
                            <MenuItem value={"کشاورزی"}>کشاورزی</MenuItem>
                            <MenuItem value={"مسکن"}>مسکن</MenuItem>
                            <MenuItem value={"مهر ایران"}>مهر ایران</MenuItem>
                            <MenuItem value={"مهر اقتصاد"}>مهر اقتصاد</MenuItem>
                            <MenuItem value={"ملت"}>ملت</MenuItem>
                            <MenuItem value={"ملی"}>ملی</MenuItem>
                            <MenuItem value={"پارسیان"}>پارسیان</MenuItem>
                            <MenuItem value={"پاسارگاد"}>پاسارگاد</MenuItem>
                            <MenuItem value={"پست بانک ایران"}>
                              پست بانک ایران
                            </MenuItem>
                            <MenuItem value={"صادرات"}>صادرات</MenuItem>
                            <MenuItem value={"سامان"}>سامان</MenuItem>
                            <MenuItem value={"صنعت و معدن"}>
                              صنعت و معدن
                            </MenuItem>
                            <MenuItem value={"سرمایه"}>سرمایه</MenuItem>
                            <MenuItem value={"شهر"}>شهر</MenuItem>
                            <MenuItem value={"سینا"}>سینا</MenuItem>
                            <MenuItem value={"تجارت"}>تجارت</MenuItem>
                            <MenuItem value={"موسسه اعتباری توسعه"}>
                              موسسه اعتباری توسعه
                            </MenuItem>
                            <MenuItem value={"خاورمیانه"}>خاورمیانه</MenuItem>
                          </Select>
                        </FormControl>
                      </Grid>

                      <Grid>
                        <TextField
                          inputProps={{
                            inputMode: "numeric",
                            pattern: "[0-9]*",
                          }}
                          error={false}
                          fullWidth
                          label="شماره کارت"
                          variant="outlined"
                          onChange={handleChangeArrayKillHouse}
                          name={"cardNumber-" + i}
                        />
                      </Grid>

                      <Grid>
                        <TextField
                          inputProps={{
                            inputMode: "numeric",
                            pattern: "[0-9]*",
                          }}
                          error={false}
                          fullWidth
                          label="شماره حساب"
                          variant="outlined"
                          onChange={handleChangeArrayKillHouse}
                          name={"accountNumber-" + i}
                        />
                      </Grid>
                      <Grid>
                        <TextField
                          inputProps={{
                            inputMode: "numeric",
                            pattern: "[0-9]*",
                          }}
                          error={false}
                          fullWidth
                          label="شماره شبا"
                          variant="outlined"
                          onChange={handleChangeArrayKillHouse}
                          name={"shabaNumber-" + i}
                        />
                      </Grid>

                      <Grid>
                        <TextField
                          error={false}
                          fullWidth
                          label="نام صاحب حساب"
                          variant="outlined"
                          onChange={handleChangeArrayKillHouse}
                          name={"accountHolder-" + i}
                        />
                      </Grid>

                      <Grid container direction="row">
                        <IconButton aria-label="delete" color="success">
                          <AddIcon onClick={addInputkillHouse} />
                        </IconButton>
                        <IconButton aria-label="delete" color="secondary">
                          <DeleteIcon onClick={removeInputKillHouse} />
                        </IconButton>
                      </Grid>
                    </>
                  );
                })}
              </>
            )}

            {user === "KillHouseVet" && (
              <>
                <Divider>
                  <Chip label="اطلاعات دامپزشک کشتارگاه" />
                </Divider>

                <Grid>
                  <Autocomplete
                    disablePortal
                    id="province"
                    options={killHouseData?.map((i) => ({
                      id: i.key,
                      label: i.name,
                    }))}
                    onChange={(e, value) => {
                      setKillHouseKey(value.id);
                    }}
                    renderInput={(params) => (
                      <TextField {...params} label="انتخاب کشتارگاه" />
                    )}
                  />
                </Grid>

                <Grid>
                  <Autocomplete
                    disablePortal
                    id="province"
                    options={provinceData?.map((i) => ({
                      id: i.key,
                      label: i.name,
                    }))}
                    onChange={(e, value) => {
                      setKillHouseVetProvinceKey(value.id);
                    }}
                    renderInput={(params) => (
                      <TextField {...params} label="استان کشتارگاه*" />
                    )}
                  />
                </Grid>

                <Grid>
                  <Autocomplete
                    disabled={isExistProvince}
                    disablePortal
                    id="city"
                    options={cityData?.map((i) => ({
                      id: i.key,
                      label: i.name,
                    }))}
                    onChange={(e, value) => {
                      setKillHouseVetCityKey(value.id);
                    }}
                    renderInput={(params) => (
                      <TextField {...params} label="شهر کشتارگاه*" />
                    )}
                  />
                </Grid>

                <Grid>
                  <TextField
                    id="KillHouseVetAddress"
                    label="آدرس "
                    variant="outlined"
                    sx={{ width: "100%" }}
                    value={formikKillHouseVet.values.KillHouseVetAddress}
                    error={
                      formikKillHouseVet.touched.KillHouseAddress
                        ? Boolean(formikKillHouseVet.errors.KillHouseVetAddress)
                        : null
                    }
                    onChange={formikKillHouseVet.handleChange}
                    onBlur={formikKillHouseVet.handleBlur}
                    helperText={
                      formikKillHouseVet.touched.KillHouseVetAddress &&
                      Boolean(formikKillHouseVet.errors.KillHouseVetAddress)
                        ? formikKillHouseVet.errors.KillHouseVetAddress
                        : null
                    }
                  />
                </Grid>

                <Grid>
                  <TextField
                    id="KillHouseVetPostal"
                    label="کد پستی"
                    variant="outlined"
                    sx={{ width: "100%" }}
                    value={formikKillHouseVet.values.KillHouseVetPostal}
                    error={
                      formikKillHouseVet.touched.KillHouseVetPostal
                        ? Boolean(formikKillHouseVet.errors.KillHouseVetPostal)
                        : null
                    }
                    onChange={formikKillHouseVet.handleChange}
                    onBlur={formikKillHouseVet.handleBlur}
                    helperText={
                      formikKillHouseVet.touched.KillHouseVetPostal &&
                      Boolean(formikKillHouseVet.errors.KillHouseVetPostal)
                        ? formikKillHouseVet.errors.KillHouseVetPostal
                        : null
                    }
                  />
                </Grid>
              </>
            )}

            {(user === "CityOperator" ||
              user === "ProvinceOperator" ||
              user === "VetFarm" ||
              user === "ProvinceInspector" ||
              user === "ProvinceFinancial") && (
              <>
                <Divider>
                  <Chip label="اطلاعات اپراتور" />
                </Divider>

                <Grid>
                  <Autocomplete
                    disablePortal
                    id="province"
                    options={provinceData?.map((i) => ({
                      id: i.key,
                      label: i.name,
                    }))}
                    onChange={(e, value) => {
                      setOperatorProvinceKey(value.id);
                    }}
                    renderInput={(params) => (
                      <TextField {...params} label="استان *" />
                    )}
                  />
                </Grid>

                <Grid>
                  <Autocomplete
                    disabled={isExistProvince}
                    disablePortal
                    id="city"
                    options={cityData?.map((i) => ({
                      id: i.key,
                      label: i.name,
                    }))}
                    onChange={(e, value) => {
                      setOperatorCityKey(value.id);
                    }}
                    renderInput={(params) => (
                      <TextField {...params} label="شهر *" />
                    )}
                  />
                </Grid>

                <Grid>
                  <TextField
                    id="cityProvinceAddress"
                    label="آدرس"
                    variant="outlined"
                    sx={{ width: "100%" }}
                    value={formikCityProvince.values.cityProvinceAddress}
                    error={
                      formikCityProvince.touched.cityProvinceAddress
                        ? Boolean(formikCityProvince.errors.cityProvinceAddress)
                        : null
                    }
                    onChange={formikCityProvince.handleChange}
                    onBlur={formikCityProvince.handleBlur}
                    helperText={
                      formikCityProvince.touched.cityProvinceAddress &&
                      Boolean(formikCityProvince.errors.cityProvinceAddress)
                        ? formikCityProvince.errors.cityProvinceAddress
                        : null
                    }
                  />
                </Grid>

                <Grid>
                  <TextField
                    id="cityProvincePostalCode"
                    label="کد پستی"
                    variant="outlined"
                    sx={{ width: "100%" }}
                    value={formikCityProvince.values.cityProvincePostalCode}
                    error={
                      formikCityProvince.touched.cityProvincePostalCode
                        ? Boolean(
                            formikCityProvince.errors.cityProvincePostalCode
                          )
                        : null
                    }
                    onChange={formikCityProvince.handleChange}
                    onBlur={formikCityProvince.handleBlur}
                    helperText={
                      formikCityProvince.touched.cityProvincePostalCode &&
                      Boolean(formikCityProvince.errors.cityProvincePostalCode)
                        ? formikCityProvince.errors.cityProvincePostalCode
                        : null
                    }
                  />
                </Grid>
              </>
            )}

            {(user === "CityOperator" ||
              user === "KillHouseVet" ||
              user === "VetFarm" ||
              user === "ProvinceOperator" ||
              user === "Driver" ||
              user === "ProvinceFinancial") && (
              <>
                <Divider>
                  <Chip label="اطلاعات بانکی" />
                </Divider>
                <Grid>
                  <FormControl fullWidth>
                    <InputLabel id="demo-simple-select-label">بانک</InputLabel>
                    <Select
                      fullWidth
                      value={formikUserBankInfo.values.bankName}
                      id="bankName"
                      label="بانک"
                      onChange={(e) => {
                        formikUserBankInfo.setFieldValue(
                          "bankName",
                          e.target.value
                        );
                      }}
                    >
                      <MenuItem value={"موسسه افضل توس"}>
                        موسسه افضل توس
                      </MenuItem>
                      <MenuItem value={"انصار"}>انصار</MenuItem>
                      <MenuItem value={"سپه"}>سپه</MenuItem>
                      <MenuItem value={"دی"}>دی</MenuItem>
                      <MenuItem value={"کاب"}>اقتصاد نوین</MenuItem>
                      <MenuItem value={"گردشگری"}>گردشگری</MenuItem>
                      <MenuItem value={"حکمت ایرانیان"}>حکمت ایرانیان</MenuItem>
                      <MenuItem value={"ایران زمین"}>ایران زمین</MenuItem>
                      <MenuItem value={"کشاورزی"}>کشاورزی</MenuItem>
                      <MenuItem value={"مسکن"}>مسکن</MenuItem>
                      <MenuItem value={"مهر ایران"}>مهر ایران</MenuItem>
                      <MenuItem value={"مهر اقتصاد"}>مهر اقتصاد</MenuItem>
                      <MenuItem value={"ملت"}>ملت</MenuItem>
                      <MenuItem value={"ملی"}>ملی</MenuItem>
                      <MenuItem value={"پارسیان"}>پارسیان</MenuItem>
                      <MenuItem value={"پاسارگاد"}>پاسارگاد</MenuItem>
                      <MenuItem value={"پست بانک ایران"}>
                        پست بانک ایران
                      </MenuItem>
                      <MenuItem value={"صادرات"}>صادرات</MenuItem>
                      <MenuItem value={"سامان"}>سامان</MenuItem>
                      <MenuItem value={"صنعت و معدن"}>صنعت و معدن</MenuItem>
                      <MenuItem value={"سرمایه"}>سرمایه</MenuItem>
                      <MenuItem value={"شهر"}>شهر</MenuItem>
                      <MenuItem value={"سینا"}>سینا</MenuItem>
                      <MenuItem value={"تجارت"}>تجارت</MenuItem>
                      <MenuItem value={"موسسه اعتباری توسعه"}>
                        موسسه اعتباری توسعه
                      </MenuItem>
                      <MenuItem value={"خاورمیانه"}>خاورمیانه</MenuItem>
                    </Select>
                  </FormControl>
                </Grid>

                <Grid>
                  <TextField
                    fullWidth
                    id="cardNumber"
                    label="شماره کارت"
                    value={formikUserBankInfo.values.cardNumber}
                    error={
                      formikUserBankInfo.touched.cardNumber
                        ? Boolean(formikUserBankInfo.errors.cardNumber)
                        : null
                    }
                    onChange={formikUserBankInfo.handleChange}
                    onBlur={formikUserBankInfo.handleBlur}
                    helperText={
                      formikUserBankInfo.touched.cardNumber &&
                      Boolean(formikUserBankInfo.errors.cardNumber)
                        ? formikUserBankInfo.errors.cardNumber
                        : null
                    }
                    autoComplete="current-password"
                    variant="outlined"
                  />
                </Grid>

                <Grid>
                  <TextField
                    fullWidth
                    id="accountNumber"
                    label="شماره حساب"
                    value={formikUserBankInfo.values.accountNumber}
                    error={
                      formikUserBankInfo.touched.accountNumber
                        ? Boolean(formikUserBankInfo.errors.accountNumber)
                        : null
                    }
                    onChange={formikUserBankInfo.handleChange}
                    onBlur={formikUserBankInfo.handleBlur}
                    helperText={
                      formikUserBankInfo.touched.accountNumber &&
                      Boolean(formikUserBankInfo.errors.accountNumber)
                        ? formikUserBankInfo.errors.accountNumber
                        : null
                    }
                    autoComplete="current-password"
                    variant="outlined"
                  />
                </Grid>
                <Grid>
                  <TextField
                    fullWidth
                    id="shabaNumber"
                    label="شماره شبا"
                    value={formikUserBankInfo.values.shabaNumber}
                    error={
                      formikUserBankInfo.touched.shabaNumber
                        ? Boolean(formikUserBankInfo.errors.shabaNumber)
                        : null
                    }
                    onChange={formikUserBankInfo.handleChange}
                    onBlur={formikUserBankInfo.handleBlur}
                    helperText={
                      formikUserBankInfo.touched.shabaNumber &&
                      Boolean(formikUserBankInfo.errors.shabaNumber)
                        ? formikUserBankInfo.errors.shabaNumber
                        : null
                    }
                    autoComplete="current-password"
                    variant="outlined"
                  />
                </Grid>
                <Grid>
                  <TextField
                    fullWidth
                    id="accountHolder"
                    label="نام صاحب حساب"
                    value={formikUserBankInfo.values.accountHolder}
                    error={
                      formikUserBankInfo.touched.accountHolder
                        ? Boolean(formikUserBankInfo.errors.accountHolder)
                        : null
                    }
                    onChange={formikUserBankInfo.handleChange}
                    onBlur={formikUserBankInfo.handleBlur}
                    helperText={
                      formikUserBankInfo.touched.accountHolder &&
                      Boolean(formikUserBankInfo.errors.accountHolder)
                        ? formikUserBankInfo.errors.accountHolder
                        : null
                    }
                    variant="outlined"
                  />
                </Grid>
              </>
            )}

            <Grid mb={SPACING.SMALL}>
              <Button
                fullWidth
                variant="contained"
                disabled={isFormValid(user)}
                onClick={() => {
                  dispatch(LOADING_START());
                  if (userData) {
                    if (
                      user === "ProvinceOperator" ||
                      user === "CityOperator" ||
                      user === "VetFarm" ||
                      user === "ProvinceInspector" ||
                      user === "ProvinceFinancial"
                    ) {
                      dispatch(
                        provinceRegisterUser({
                          type: user,
                          userprofile_key: userData.key,
                          city: OperatorCityKey,
                          province: OperatorProvinceKey,
                          address:
                            formikCityProvince.values.cityProvinceAddress,
                          postal_code:
                            formikCityProvince.values.cityProvincePostalCode,
                          user_bank_info: {
                            name_of_bank_user:
                              formikUserBankInfo.values.accountHolder,
                            bank_name: formikUserBankInfo.values.bankName,
                            card: formikUserBankInfo.values.cardNumber,
                            shaba: formikUserBankInfo.values.shabaNumber,
                            account: formikUserBankInfo.values.accountNumber,
                          },
                        })
                      ).then((r) => {
                        dispatch(LOADING_END());
                        if (r.error) {
                          if (r.error.message.includes("403")) {
                            openNotif({
                              vertical: "top",
                              horizontal: "center",
                              msg: "کاربر از قبل موجود است!",
                              severity: "error",
                            });
                          } else if (r.error.message.includes("406")) {
                            openNotif({
                              vertical: "top",
                              horizontal: "center",
                              msg: "اپراتور تکراری قابل ثبت نیست!",
                              severity: "error",
                            });
                          } else {
                            openNotif({
                              vertical: "top",
                              horizontal: "center",
                              msg: "مشکلی پیش آمده است!",
                              severity: "error",
                            });
                          }
                        } else {
                          openNotif({
                            vertical: "top",
                            horizontal: "center",
                            msg: "عملیات با موفقیت انجام شد.",
                            severity: "success",
                          });
                          dispatch(provinceGetUserProfiles());
                          dispatch(
                            DRAWER({
                              right: false,
                              bottom: false,
                              content: null,
                            })
                          );
                        }
                      });
                    } else if (user === "KillHouse") {
                      dispatch(
                        provinceRegisterUser({
                          type: "KillHouse",
                          userprofile_key: userData.key,
                          city: killHouseCityKey,
                          province: killHouseProvinceKey,
                          address: formikKillHouse.values.KillHouseAddress,
                          postal_code: formikKillHouse.values.KillHousePostal,
                          killhouse_data: arrKillHouse.map((item, i) => {
                            return {
                              address: {
                                city_key: item.city,
                                province_key: item.province,
                                address: item.killHouseAddress,
                                postal_code: item.postal,
                              },
                              user_bank_info: {
                                name_of_bank_user: item.accountHolder,
                                bank_name: item.bankName,
                                card: item.cardNumber,
                                shaba: item.shabaNumber,
                                account: item.accountNumber,
                              },
                              name: item.name,
                              capacity: item.capacity,
                              phone: item.phone,
                            };
                          }),
                        })
                      ).then((r) => {
                        dispatch(LOADING_END());
                        if (r.error) {
                          if (r.error.message.includes("403")) {
                            openNotif({
                              vertical: "top",
                              horizontal: "center",
                              msg: "کشتارگاه با این مشخصات از قبل موجود است!",
                              severity: "error",
                            });
                          } else {
                            openNotif({
                              vertical: "top",
                              horizontal: "center",
                              msg: "مشکلی پیش آمده است!",
                              severity: "error",
                            });
                          }
                        } else {
                          openNotif({
                            vertical: "top",
                            horizontal: "center",
                            msg: "عملیات با موفقیت انجام شد.",
                            severity: "success",
                          });
                          dispatch(provinceGetUserProfiles());
                          dispatch(
                            DRAWER({
                              right: false,
                              bottom: false,
                              content: null,
                            })
                          );
                        }
                      });
                    } else if (user === "Poultry") {
                      dispatch(
                        provinceRegisterUser({
                          type: "Poultry",
                          owner_key: userData.key,
                          poultry_list: arr.map((item, i) => {
                            return {
                              address: {
                                province_key: item.province,
                                city_key: item.city,
                                address: item.poultryAddress,
                                postal_code: item.postal,
                              },
                              user_bank_info: {
                                name_of_bank_user: item.accountHolder,
                                bank_name: item.bankName,
                                card: item.cardNumber,
                                shaba: item.shabaNumber,
                                account: item.accountNumber,
                              },
                              epidemiological_code: item.epidemiologicalCode,
                              system_code: item.systemCode,
                              number_of_halls: item.halls,
                              breeding_unique_id: item.uniqueID,
                              unit_name: item.unitName,
                              licence_number: item.licenseNumber,
                              total_capacity: item.capacity,
                              health_certificate_number: item.licenseNumber,
                            };
                          }),
                        })
                      ).then((r) => {
                        dispatch(LOADING_END());
                        if (r.payload.error) {
                          openNotif({
                            vertical: "top",
                            horizontal: "center",
                            msg: r.payload.error,
                            severity: "error",
                          });
                        } else {
                          openNotif({
                            vertical: "top",
                            horizontal: "center",
                            msg: "عملیات با موفقیت انجام شد.",
                            severity: "success",
                          });
                          dispatch(provinceGetUserProfiles());
                          dispatch(
                            DRAWER({
                              right: false,
                              bottom: false,
                              content: null,
                            })
                          );
                        }
                      });
                    } else if (user === "Driver") {
                      dispatch(
                        provinceRegisterUser({
                          type: "Driver",
                          userprofile_key: userData.key,
                          driver_name: userData.fullname,
                          driver_mobile: userData.mobile,
                          type_car: formikDriver.values.type_car,
                          capocity: formikDriver.values.capocity,
                          weight_without_load: "0",
                          health_code: formikDriver.values.health_code,
                          pelak:
                            driverPelak[0] +
                            " " +
                            driverPelak[1] +
                            " " +
                            driverPelak[2] +
                            " " +
                            driverPelak[3],

                          user_bank_info: {
                            name_of_bank_user:
                              formikUserBankInfo.values.accountHolder,
                            bank_name: formikUserBankInfo.values.bankName,
                            card: formikUserBankInfo.values.cardNumber,
                            shaba: formikUserBankInfo.values.shabaNumber,
                            account: formikUserBankInfo.values.accountNumber,
                          },
                        })
                      ).then((r) => {
                        dispatch(
                          DRAWER({ right: false, bottom: false, content: null })
                        );

                        dispatch(LOADING_END());
                        if (r.error) {
                          if (r.error.message.includes("403")) {
                            openNotif({
                              vertical: "top",
                              horizontal: "center",
                              msg: "راننده با این مشخصات از قبل موجود است!",
                              severity: "error",
                            });
                          } else {
                            openNotif({
                              vertical: "top",
                              horizontal: "center",
                              msg: "مشکلی پیش آمده است!",
                              severity: "error",
                            });
                          }
                        } else {
                          openNotif({
                            vertical: "top",
                            horizontal: "center",
                            msg: "عملیات با موفقیت انجام شد.",
                            severity: "success",
                          });
                          dispatch(provinceGetUserProfiles());
                        }
                      });
                    } else if (user === "KillHouseVet") {
                      dispatch(
                        provinceRegisterUser({
                          userprofile_key: userData.key,
                          type: "KillHouseVet",
                          kill_house_key: killHouseKey,
                          city: killHouseVetCityKey,
                          province: killHouseVetProvinceKey,
                          address:
                            formikKillHouseVet.values.KillHouseVetAddress,
                          postal_code:
                            formikKillHouseVet.values.KillHouseVetPostal,
                          user_bank_info: {
                            name_of_bank_user:
                              formikUserBankInfo.values.accountHolder,
                            bank_name: formikUserBankInfo.values.bankName,
                            card: formikUserBankInfo.values.cardNumber,
                            shaba: formikUserBankInfo.values.shabaNumber,
                            account: formikUserBankInfo.values.accountNumber,
                          },
                        })
                      ).then((r) => {
                        dispatch(LOADING_END());
                        if (r.error) {
                          if (r.error.message.includes("403")) {
                            openNotif({
                              vertical: "top",
                              horizontal: "center",
                              msg: "دامپزشک کشتارگاه با این مشخصات از قبل موجود است!",
                              severity: "error",
                            });
                          } else {
                            openNotif({
                              vertical: "top",
                              horizontal: "center",
                              msg: "مشکلی پیش آمده است!",
                              severity: "error",
                            });
                          }
                        } else {
                          openNotif({
                            vertical: "top",
                            horizontal: "center",
                            msg: "عملیات با موفقیت انجام شد.",
                            severity: "success",
                          });
                          dispatch(provinceGetUserProfiles());
                          dispatch(
                            DRAWER({
                              right: false,
                              bottom: false,
                              content: null,
                            })
                          );
                        }
                      });
                    }
                  } else {
                    dispatch(
                      provinceRegisterUser({
                        type: "profile",
                        fullname:
                          formik.values.fname + " " + formik.values.lname,
                        first_name: formik.values.fname,
                        last_name: formik.values.lname,
                        national_code: formik.values.nationalcode,
                        national_id: formik.values.national_id,
                        birthday: formik.values.birthday,
                        mobile: formik.values.mobile,
                        password: formik.values.password,
                        city: cityKey,
                        province: provinceKey,
                        image: "",
                      })
                    ).then((r) => {
                      dispatch(LOADING_END());
                      if (r.payload.error) {
                        openNotif({
                          vertical: "top",
                          horizontal: "center",
                          msg: r.payload.error,
                          severity: "error",
                        });
                      } else {
                        openNotif({
                          vertical: "top",
                          horizontal: "center",
                          msg: "عملیات با موفقیت انجام شد.",
                          severity: "success",
                        });
                        setUserData(r.payload.data);
                        dispatch(provinceGetUserProfiles());
                      }
                    });
                  }
                }}
              >
                ثبت اطلاعات
              </Button>
            </Grid>
          </>
        )}
      </Grid>
    </Grid>
  );
};
