import React, { useContext, useEffect, useState, useCallback } 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";

const PAGE_STEWARD = "steward_add_buyer";
const PAGE_SLAUGHTER = "slaughter_add_buyer";
const PAGE_SLAUGHTER_MANAGE = "slaughter_manage_add_buyer";
const PAGE_ADMIN = "admin_add_buyer";

const ADMIN_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,
];

const getCurrentPage = (role, pathname) => {
  if (role === "Steward" && pathname === ROUTE_STEWARD_SALE_OUT_PROVINCE) {
    return PAGE_STEWARD;
  }
  if (role === "KillHouse") {
    if (pathname === ROUTE_SLAUGHTER_INVENTORY_SELL_CARCASS_OUT_PROVINCE) {
      return PAGE_SLAUGHTER;
    }
    if (pathname === ROUTE_SLAUGHTER_MANAGE_GUILDS_OUT_PROVINCE_TRUE) {
      return PAGE_SLAUGHTER_MANAGE;
    }
  }
  if (role === "AdminX" && ADMIN_ROUTES.some((r) => r === pathname)) {
    return PAGE_ADMIN;
  }
  return null;
};

const INITIAL_VALUES_BASE = {
  mobile: "",
  firstName: "",
  lastName: "",
  unit_name: "",
  province: "",
  city: "",
};

const getInitialValues = (page) => {
  if (page === PAGE_SLAUGHTER) {
    return { ...INITIAL_VALUES_BASE, nationalId: "" };
  }
  if (page === PAGE_ADMIN) {
    return { ...INITIAL_VALUES_BASE, steward_keys: [], kill_house_keys: [] };
  }
  return { ...INITIAL_VALUES_BASE };
};

const getValidationSchema = (page, isRealPerson, isEdit) => {
  if (page === PAGE_STEWARD) return validationSchemaForStewardAddBuyer;
  if (page === PAGE_SLAUGHTER || page === PAGE_SLAUGHTER_MANAGE) {
    return validationSchemaForSlaughterAddBuyer(isRealPerson, isEdit);
  }
  if (page === PAGE_ADMIN) {
    return validationSchemaForAdminAddBuyer(isRealPerson, isEdit);
  }
  return Yup.object({});
};

const setFormDataFromTableData = (page, data, formik) => {
  if (page === PAGE_STEWARD) {
    handleSetFormDataFromTableDataForStewardAddBuyer(data, formik);
  } else if (page === PAGE_SLAUGHTER || page === PAGE_SLAUGHTER_MANAGE) {
    handleSetFormDataFromTableDataForSlaughterAddBuyer(data, formik);
  } else if (page === PAGE_ADMIN) {
    handleSetFormDataFromTableDataForAdminAddBuyer(data, formik);
  }
};

export const StewardAddBuyer = ({
  updateTable,
  isEdit = false,
  data,
  isRealPerson,
  buyerType = "",
}) => {
  const role = getRoleFromUrl();
  const { pathname } = useLocation();
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);
  const [notFound, setNotFound] = useState(false);
  const { selectedSubUser } = useSelector((state) => state.userSlice);

  const page = getCurrentPage(role, pathname);

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

  const formik = useFormik({
    initialValues: getInitialValues(page),
    validationSchema: getValidationSchema(page, isRealPerson, isEdit),
  });

  // Re-validate when switching to edit mode
  useEffect(() => {
    if (isEdit) formik.validateForm();
  }, [isEdit]);

  // Populate form when editing
  useEffect(() => {
    if (isEdit && page && data) {
      setFormDataFromTableData(page, data, formik);
    }
  }, [isEdit, page]);

  // Load cities when province changes
  useEffect(() => {
    if (!formik.values.province) {
      setCityData([]);
      return;
    }
    setCityData([]);
    dispatch(slaughterGetCitiesService(formik.values.province)).then((r) => {
      setCityData(r.payload?.data ?? []);
    });
  }, [formik.values.province, dispatch]);

  // Admin: load both stewards and kill houses
  useEffect(() => {
    if (page !== PAGE_ADMIN) return;
    dispatch(inspectorGetKillHousesService());
    dispatch(slaughterGetStewardsForAllocateService({ free: true })).then(
      (r) => {
        setStewards(r.payload?.data ?? []);
      }
    );
  }, [page, dispatch]);

  const handleSubmit = useCallback(() => {
    if (page === PAGE_STEWARD) {
      handleSubmitForStewardAddBuyer(
        formik,
        dispatch,
        isEdit,
        data,
        updateTable,
        openNotif,
        DRAWER,
        role
      );
      return;
    }
    if (page === PAGE_SLAUGHTER) {
      handleSubmitForSlaughterAddBuyer(
        formik,
        dispatch,
        isEdit,
        data,
        updateTable,
        openNotif,
        DRAWER,
        selectedSubUser,
        isRealPerson
      );
      return;
    }
    if (page === PAGE_SLAUGHTER_MANAGE) {
      handleSubmitForSlaughterAddBuyer(
        formik,
        dispatch,
        isEdit,
        data,
        updateTable,
        openNotif,
        DRAWER,
        selectedSubUser,
        isRealPerson,
        buyerType
      );
      return;
    }
    if (page === PAGE_ADMIN) {
      handleSubmitForAdminAddBuyer(
        formik,
        dispatch,
        isEdit,
        data,
        updateTable,
        openNotif,
        DRAWER,
        isRealPerson,
        buyerType
      );
    }
  }, [
    page,
    formik,
    dispatch,
    isEdit,
    data,
    updateTable,
    openNotif,
    role,
    selectedSubUser,
    isRealPerson,
    buyerType,
  ]);

  const showInquiry = !isEdit && page;
  const showForm = (userData || notFound || isEdit) && page;

  const inquiryProps = {
    notFound,
    setNotFound,
    setUserData,
    formik,
  };

  const formProps = {
    formik,
    provinceData,
    cityData,
    notFound,
  };

  const renderInquiry = () => {
    if (!showInquiry) return null;
    if (page === PAGE_STEWARD) {
      return <InquiryForStewardAddBuyer {...inquiryProps} />;
    }
    if (page === PAGE_SLAUGHTER || page === PAGE_SLAUGHTER_MANAGE) {
      return (
        <InquiryForSlaughterAddBuyer
          {...inquiryProps}
          isEdit={isEdit}
          isRealPerson={isRealPerson}
          provinceData={provinceData}
        />
      );
    }
    if (page === PAGE_ADMIN) {
      return (
        <InquiryForAdminAddBuyer
          {...inquiryProps}
          isEdit={isEdit}
          isRealPerson={isRealPerson}
          provinceData={provinceData}
        />
      );
    }
    return null;
  };

  const renderForm = () => {
    if (!showForm) return null;
    if (page === PAGE_STEWARD) {
      return <StewardAddBuyerForm {...formProps} />;
    }
    if (page === PAGE_SLAUGHTER || page === PAGE_SLAUGHTER_MANAGE) {
      return (
        <SlaughterAddBuyerForm {...formProps} isRealPerson={isRealPerson} />
      );
    }
    if (page === PAGE_ADMIN) {
      return (
        <AdminAddBuyerForm
          {...formProps}
          isRealPerson={isRealPerson}
          killHouses={killHouses}
          stewards={stewards}
          editData={isEdit ? data : null}
        />
      );
    }
    return null;
  };

  if (!page) {
    return null;
  }

  return (
    <Grid
      container
      justifyContent="space-between"
      alignItems="center"
      xs={12}
      direction="column"
      gap={2}
    >
      {renderInquiry()}
      {renderForm()}
      {showForm && (
        <Grid container xs={12}>
          <Button
            fullWidth
            variant="contained"
            disabled={!formik.isValid}
            onClick={handleSubmit}
          >
            {isEdit ? "ویرایش" : "ثبت"}
          </Button>
        </Grid>
      )}
    </Grid>
  );
};
