const useState = wp.element.useState;
const useEffect = wp.element.useEffect;
import "./App.css";
import { signal } from "@preact/signals-react";
import Navigation from "./features/navigation/components/TOD.Navigation.js";
import SideBar from "./features/navigation/components/TOD.SideBar.js";
import {
  formDataContext,
  formData,
  leadershipUtils,
  leadershipStatus,
} from "./features/context/TOD.FormulaireData.js";
import MioCommerceOlympusFormSteps from "./forms/miocommerce/olympus/Metadata.js";
import WBSpinner from "./components/WBSpinner.js";
import LeaderOverlay from "./components/leaderOverlay/LeaderOverlay.js";

/**
 *
 * **This is a signal that holds the current step index of the form.**
 *
 * @type {import('@preact/signals-react').Signal<number>}
 */
export const Step_n = signal(0);
export const previewModal = signal({
  isReady: false,
  url: "",
  visible: false,
  error: null,
});

let metaSteps = null;
console.log(window.wb_onboard_options);
if (
  window.wb_onboard_options &&
  window.wb_onboard_options.company_uuid ==
    "67d4d57e-c5e3-49d4-8cbb-6201342e7d3d"
) {
  metaSteps = MioCommerceOlympusFormSteps;
}

const App = () => {
  const [isInitialized, setIsInitialized] = useState(false);

  useEffect(() => {
    const initializeForm = async () => {
      if (!isInitialized) {
        // Générer un page_id unique pour cet onglet dès le démarrage
        const pageId = leadershipUtils.generatePageId();

        await formDataContext.init();
        setIsInitialized(true);
      }
    };

    initializeForm();

    // Cleanup lors du démontage
    return () => {
      formDataContext.cleanup();
    };
  }, []); // Dépendances vides pour n'exécuter qu'au montage

  // Séparer la logique de sauvegarde dans un autre useEffect
  useEffect(() => {
    if (!isInitialized) return; // Ne pas sauvegarder avant l'initialisation

    // Vérifier le leadership avant de sauvegarder manuellement
    if (!leadershipStatus.value.isLeader) {
      return;
    }

    console.log(formData.value);
    wp.apiFetch({
      path: "/wb-onboard/v1/save-form",
      method: "POST",
      data: {
        wb_onboard_form_data: formData.value,
        step_n: Step_n.value,
        page_id: leadershipStatus.value.pageId,
      },
    })
      .then(() => {
        console.log("Sauvegarde manuelle effectuée (leader)");
      })
      .catch((error) => {
        // Si erreur NOT_LEADER, on perd le leadership
        if (error.code === "NOT_LEADER") {
          console.log(
            "Leadership perdu détecté lors de la sauvegarde manuelle"
          );
          leadershipStatus.value = {
            ...leadershipStatus.value,
            isLeader: false,
          };
        }
        console.error("Erreur lors de la sauvegarde manuelle:", error);
      });
  }, [Step_n.value, isInitialized]);

  if (!isInitialized) {
    return (
      <div>
        <WBSpinner />
      </div>
    );
  }

  return (
    <div className="wb-react-app-wrap">
      {/* Overlay de leadership - s'affiche par-dessus tout */}
      <LeaderOverlay />

      {metaSteps && (
        <>
          <div className="wb-admin-page-sidebar">
            <SideBar metaSteps={metaSteps} />
          </div>
          <div className="wb-admin-page-body">
            <div className="wb-admin-page-content-wrap">
              <div className="wb-admin-page-content">
                <div className="wb-admin-page-container">
                  <div className="wb-form-step-wrap">
                    {React.createElement(metaSteps[Step_n.value].component)}
                  </div>
                </div>
              </div>
            </div>
            <Navigation metaSteps={metaSteps} />
          </div>
        </>
      )}
      {!metaSteps && (
        <>
          <div>Could not initialize form, please contact us for support.</div>
        </>
      )}
    </div>
  );
};

export default App;
