"use client";
import BackgroundGradients from "@/components/BackgroundGradients";
import ContactHero from "@/components/ContactHero";
import Footer from "@/components/Footer";
import ResetPasswordPage from "./ResetPasswordClient";
import PageLoading from "@/components/PageLoading";
import { useEffect, useState } from "react";
import { getStoredLocale, getStoredLocaleRaw, LOCALE_CHANGE_EVENT } from "@/i18n/localeSwitcher";
import { submitPasswordReset } from "@/lib/submit-password-reset";

const LOGIN_ZIGZAG_COUNT = 2;

export default function ResetPassword() {
  const [pageData, setPageData] = useState<any>(null);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    let isMounted = true;
    let loadSeq = 0;

    const loadServicesPage = async () => {
      const seq = ++loadSeq;
      setIsLoading(true);
      try {
        const xMedusaLocale = (getStoredLocaleRaw() ?? getStoredLocale()).trim();
        const res = await fetch(
          `${process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL}/store/pages/forgot-password`,
          {
            method: "GET",
            headers: {
              "x-publishable-api-key": process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_API_KEY || "",
              "x-medusa-locale": xMedusaLocale,
            },
            cache: "no-store",
          }
        );

        if (!res.ok) return;
        if (!isMounted || seq !== loadSeq) return;
        setPageData(await res.json());
      } catch {
      } finally {
        if (isMounted && seq === loadSeq) setIsLoading(false);
      }
    };

    loadServicesPage();

    const onLocaleChange = () => {
      void loadServicesPage();
    };
    if (typeof window !== "undefined") {
      window.addEventListener(LOCALE_CHANGE_EVENT, onLocaleChange);
    }
    return () => {
      isMounted = false;
      if (typeof window !== "undefined") {
        window.removeEventListener(LOCALE_CHANGE_EVENT, onLocaleChange);
      }
    };
  }, []);

  const sections = pageData?.page?.sections ?? [];
  const findSectionData = (...keys: string[]) => {
    const section = sections.find((s: any) =>
      keys.some((k) => String(s?.key ?? "").toLowerCase().includes(k.toLowerCase()))
    );
    const data = section?.components?.[0]?.instance?.data?.items?.[0];
    return data?.items?.[0] ?? data ?? null;
  };

  const bannerData = findSectionData("banner-section");
  const heroTitle = bannerData?.title ?? "";
  const heroDescription = bannerData?.description ?? "";
  const heroBg = bannerData?.bg_image?.items?.[0] ?? {};
  const heroBgMobile = heroBg?.image_mobile ?? "";
  const heroBgDesktop = heroBg?.image_desktop ?? "";

  if (isLoading) {
    return <PageLoading />;
  }

  return (
    <>
      <main className="px-[20px] md:px-[40px] xl:px-[60px]">
        <ContactHero
          headline={
            <h1 className="font-lexend font-extralight text-[#ffffff] max-w-[782px]">
              {(() => {
                const words = heroTitle.trim().split(/\s+/);
                return (
                  <>
                    {words.slice(0, 2).join(" ")}{" "}
                    {words.length > 2 ? (
                      <span className="font-medium">{words.slice(2).join(" ")}</span>
                    ) : null}
                  </>
                );
              })()}
            </h1>
          }
          description={heroDescription}
          showSearch={false}
          backgroundImageMobile={heroBgMobile || undefined}
          backgroundImageDesktop={heroBgDesktop || undefined}
        />
        <BackgroundGradients count={LOGIN_ZIGZAG_COUNT} />
        <ResetPasswordPage submitPasswordReset={submitPasswordReset} />
        <Footer />
      </main>
    </>
  );
}
