import React, { useContext, useEffect, useState } from "react";
import { Grid } from "../../../../components/grid/Grid";
import { Button } from "@mui/material";
import { Yup } from "../../../../lib/yup/yup";
import { AppContext } from "../../../../contexts/AppContext";
import { useDispatch, useSelector } from "react-redux";
import { DRAWER } from "../../../../lib/redux/slices/appSlice";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { useLocation } from "react-router-dom";
import {
  ROUTE_ADMINX_ROUTE_MANAGE_STEWARDS_OUT_PROVINCE_LEGAL,
  ROUTE_ADMINX_ROUTE_MANAGE_STEWARDS_OUT_PROVINCE_TRUE,
  ROUTE_ADMINX_ROUTE_OUT_PROVINCE_LEGAL_GUILDS,
  ROUTE_ADMINX_ROUTE_OUT_PROVINCE_TRUE_GUILDS,
  ROUTE_SLAUGHTER_INVENTORY_SELL_CARCASS_OUT_PROVINCE,
  ROUTE_SLAUGHTER_MANAGE_GUILDS_OUT_PROVINCE_TRUE,
  ROUTE_STEWARD_SALE_OUT_PROVINCE,
} from "../../../../routes/routes";
import {
  handleSetFormDataFromTableDataForStewardAddBuyer,
  handleSubmitForStewardAddBuyer,
  InquiryForStewardAddBuyer,
  StewardAddBuyerForm,
  validationSchemaForStewardAddBuyer,
} from "./InquiryForStewardAddBuyer";
import { useAddBuyer } from "./hooks/useAddBuyer";
import { slaughterGetCitiesService } from "../../../slaughter-house/services/slaughter-get-provinces";
import {
  handleSetFormDataFromTableDataForSlaughterAddBuyer,
  handleSubmitForSlaughterAddBuyer,
  InquiryForSlaughterAddBuyer,
  SlaughterAddBuyerForm,
  validationSchemaForSlaughterAddBuyer,
} from "./InquiryForSlaughterAddBuyer";
import { useFormik } from "formik";
import {
  AdminAddBuyerForm,
  handleSetFormDataFromTableDataForAdminAddBuyer,
  handleSubmitForAdminAddBuyer,
  InquiryForAdminAddBuyer,
  validationSchemaForAdminAddBuyer,
} from "./InquiryForAdminAddBuyer";
import { inspectorGetKillHousesService } from "../../../inspector/services/inspector-get-kill-houses";
import { slaughterGetStewardsForAllocateService } from "../../../slaughter-house/services/slaughter-get-guilds-for-allocate";

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

const getCurrentPage = (role, pathname) => {
  if (role === "Steward") {
    if (pathname === ROUTE_STEWARD_SALE_OUT_PROVINCE) {
      return "steward_add_buyer";
    }
  }
  if (role === "KillHouse") {
    if (pathname === ROUTE_SLAUGHTER_INVENTORY_SELL_CARCASS_OUT_PROVINCE) {
      return "slaughter_add_buyer";
    }
    if (pathname === ROUTE_SLAUGHTER_MANAGE_GUILDS_OUT_PROVINCE_TRUE) {
      return "slaughter_manage_add_buyer";
    }
  }
  if (role === "AdminX") {
    const routes = [
      ROUTE_ADMINX_ROUTE_OUT_PROVINCE_TRUE_GUILDS,
      ROUTE_ADMINX_ROUTE_OUT_PROVINCE_LEGAL_GUILDS,
      ROUTE_ADMINX_ROUTE_MANAGE_STEWARDS_OUT_PROVINCE_LEGAL,
      ROUTE_ADMINX_ROUTE_MANAGE_STEWARDS_OUT_PROVINCE_TRUE,
    ];
    if (routes.some((r) => r === pathname)) {
      return "admin_add_buyer";
    }
  }
};

const getInitialValues = (page) => {
  const initialValues = {
    mobile: "",
    firstName: "",
    lastName: "",
    unit_name: "",
    province: "",
    city: "",
  };
  if (page === "steward_add_buyer" || page === "slaughter_manage_add_buyer") {
    return initialValues;
  } else if (page === "slaughter_add_buyer") {
    return {
      ...initialValues,
      nationalId: "",
    };
  } else if (page === "admin_add_buyer") {
    return {
      ...initialValues,
      role_key: "",
      type: "",
    };
  }
  return initialValues;
};

export const StewardAddBuyer = ({
  updateTable,
  isEdit = false,
  data,
  isRealPerson,
  buyerType = "",
  // buyerYype => "Guilds" | "Steward"
}) => {
  const role = getRoleFromUrl();
  const { pathname } = useLocation();

  const page = getCurrentPage(role, pathname);

  const IS_STEWARD_ADD_BUYER = page === "steward_add_buyer";
  const IS_SLAUGHTER_ADD_BUYER = page === "slaughter_add_buyer";
  const IS_SLAUGHTER_MANAGE_ADD_BUYER = page === "slaughter_manage_add_buyer";
  const IS_ADMIN_ADD_BUYER = page === "admin_add_buyer";

  const {
    killHouses,
    stewards,
    setStewards,
    provinceData,
    cityData,
    setCityData,
    userData,
    setUserData,
  } = useAddBuyer(page);

  const { selectedSubUser } = useSelector((state) => state.userSlice);

  const [openNotif] = useContext(AppContext);
  const [notFound, setNotFound] = useState(false);
  const dispatch = useDispatch();

  const formik = useFormik({
    initialValues: getInitialValues(page),
    validationSchema: IS_STEWARD_ADD_BUYER
      ? validationSchemaForStewardAddBuyer
      : IS_SLAUGHTER_ADD_BUYER || IS_SLAUGHTER_MANAGE_ADD_BUYER
      ? validationSchemaForSlaughterAddBuyer(isRealPerson, isEdit)
      : IS_ADMIN_ADD_BUYER
      ? validationSchemaForAdminAddBuyer(isRealPerson, isEdit)
      : Yup.object({}),
  });

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

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

  useEffect(() => {
    if (isEdit) {
      if (IS_STEWARD_ADD_BUYER) {
        handleSetFormDataFromTableDataForStewardAddBuyer(data, formik);
      }
      if (IS_SLAUGHTER_ADD_BUYER || IS_SLAUGHTER_MANAGE_ADD_BUYER) {
        handleSetFormDataFromTableDataForSlaughterAddBuyer(data, formik);
      }
      if (IS_ADMIN_ADD_BUYER) {
        handleSetFormDataFromTableDataForAdminAddBuyer(data, formik);
      }
    }
  }, [isEdit]);

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

  return (
    <Grid
      container
      justifyContent="space-between"
      alignItems="center"
      xs={12}
      direction="column"
      gap={2}
    >
      {!isEdit ? (
        IS_STEWARD_ADD_BUYER ? (
          <InquiryForStewardAddBuyer
            notFound={notFound}
            setNotFound={setNotFound}
            setUserData={setUserData}
            formik={formik}
          />
        ) : IS_SLAUGHTER_ADD_BUYER || IS_SLAUGHTER_MANAGE_ADD_BUYER ? (
          <InquiryForSlaughterAddBuyer
            notFound={notFound}
            setNotFound={setNotFound}
            setUserData={setUserData}
            formik={formik}
            isEdit={isEdit}
            isRealPerson={isRealPerson}
            provinceData={provinceData}
          />
        ) : IS_ADMIN_ADD_BUYER ? (
          <InquiryForAdminAddBuyer
            notFound={notFound}
            setNotFound={setNotFound}
            setUserData={setUserData}
            formik={formik}
            isEdit={isEdit}
            isRealPerson={isRealPerson}
            provinceData={provinceData}
          />
        ) : null
      ) : null}
      {userData || notFound || isEdit ? (
        IS_STEWARD_ADD_BUYER ? (
          <StewardAddBuyerForm
            formik={formik}
            provinceData={provinceData}
            cityData={cityData}
            notFound={notFound}
          />
        ) : IS_SLAUGHTER_ADD_BUYER || IS_SLAUGHTER_MANAGE_ADD_BUYER ? (
          <SlaughterAddBuyerForm
            formik={formik}
            provinceData={provinceData}
            cityData={cityData}
            notFound={notFound}
            isRealPerson={isRealPerson}
          />
        ) : IS_ADMIN_ADD_BUYER ? (
          <AdminAddBuyerForm
            formik={formik}
            provinceData={provinceData}
            cityData={cityData}
            notFound={notFound}
            isRealPerson={isRealPerson}
            killHouses={killHouses}
            stewards={stewards}
          />
        ) : null
      ) : null}
      {(userData || notFound || isEdit) && (
        <Grid container xs={12}>
          <Button
            fullWidth
            variant="contained"
            disabled={!formik.isValid}
            onClick={() => {
              if (IS_STEWARD_ADD_BUYER) {
                handleSubmitForStewardAddBuyer(
                  formik,
                  dispatch,
                  isEdit,
                  data,
                  updateTable,
                  openNotif,
                  DRAWER,
                  role
                );
              }
              if (IS_SLAUGHTER_ADD_BUYER) {
                handleSubmitForSlaughterAddBuyer(
                  formik,
                  dispatch,
                  isEdit,
                  data,
                  updateTable,
                  openNotif,
                  DRAWER,
                  selectedSubUser,
                  isRealPerson
                );
              }
              if (IS_SLAUGHTER_MANAGE_ADD_BUYER) {
                handleSubmitForSlaughterAddBuyer(
                  formik,
                  dispatch,
                  isEdit,
                  data,
                  updateTable,
                  openNotif,
                  DRAWER,
                  selectedSubUser,
                  isRealPerson,
                  buyerType
                );
              }
              if (IS_ADMIN_ADD_BUYER) {
                handleSubmitForAdminAddBuyer(
                  formik,
                  dispatch,
                  isEdit,
                  data,
                  updateTable,
                  openNotif,
                  DRAWER,
                  isRealPerson,
                  buyerType
                );
              }
            }}
          >
            {isEdit ? "ویرایش" : "ثبت"}
          </Button>
        </Grid>
      )}
    </Grid>
  );
};
