"use client";
import BackgroundGradients from "@/components/BackgroundGradients";
import ContactHero from "@/components/ContactHero";
import Footer from "@/components/Footer";
import ForgotPasswordPage from "@/components/ForgotPasswordPage";
import PageLoading from "@/components/PageLoading";
import { requestPasswordReset } from "@/lib/request-password-reset";
import { useEffect, useState } from "react";
import { getStoredLocale, getStoredLocaleRaw, LOCALE_CHANGE_EVENT } from "@/i18n/localeSwitcher";

const LOGIN_ZIGZAG_COUNT = 2;
type SeoMeta = {
  title: string;
  description: string;
  keywords: string[];
};

function getForgotPasswordSeoMeta(data: any): SeoMeta {
  const seoSection = data?.page?.sections?.find((section: any) => section.key === "seo");
  const seoComponent = seoSection?.components?.find(
    (component: any) => component?.type?.name === "seo_meta"
  );
  const seoItem = seoComponent?.instance?.data ?? {};

  const title = typeof seoItem?.title === "string" ? seoItem.title : "";
  const description = typeof seoItem?.description === "string" ? seoItem.description : "";
  const keywordsRaw = typeof seoItem?.keywords === "string" ? seoItem.keywords : "";
  const keywords = keywordsRaw
    .split(",")
    .map((keyword: string) => keyword.trim())
    .filter(Boolean);

  return { title, description, keywords };
}

export default function ForgotPassword() {

    const [pageData, setPageData] = useState<any>(null);
    const [isLoading, setIsLoading] = useState(true);
    const [seo, setSeo] = useState<SeoMeta>({
        title: "Biomket",
        description: "Biomket marketplace",
        keywords: [],
    });

    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;
                const forgotPasswordPageJson = await res.json();
                if (!isMounted || seq !== loadSeq) return;
                setPageData(forgotPasswordPageJson);
                setSeo(getForgotPasswordSeoMeta(forgotPasswordPageJson));
            } 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);
            }
        };
    }, []);

    useEffect(() => {
        document.title = seo.title || "Biomket";

        const descriptionContent = seo.description || "Biomket marketplace";
        let descriptionMeta = document.querySelector('meta[name="description"]');
        if (!descriptionMeta) {
            descriptionMeta = document.createElement("meta");
            descriptionMeta.setAttribute("name", "description");
            document.head.appendChild(descriptionMeta);
        }
        descriptionMeta.setAttribute("content", descriptionContent);

        const keywordsContent = seo.keywords.length > 0 ? seo.keywords.join(", ") : "";
        let keywordsMeta = document.querySelector('meta[name="keywords"]');
        if (!keywordsMeta) {
            keywordsMeta = document.createElement("meta");
            keywordsMeta.setAttribute("name", "keywords");
            document.head.appendChild(keywordsMeta);
        }
        if (keywordsContent) {
            keywordsMeta.setAttribute("content", keywordsContent);
        } else {
            keywordsMeta.removeAttribute("content");
        }
    }, [seo]);


    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 ?? "";
    const heroBgMobileAlt =
        heroBg?.mobile_image_alt_tag ?? "";
    const heroBgDesktopAlt =
        heroBg?.desktop_image_alt_tag ?? "";

    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}
                    backgroundImageMobileAlt={heroBgMobileAlt || undefined}
                    backgroundImageDesktopAlt={heroBgDesktopAlt || undefined}
                />
                <BackgroundGradients count={LOGIN_ZIGZAG_COUNT} />
                <ForgotPasswordPage requestPasswordReset={requestPasswordReset} />
                <Footer />
            </main>
        </>
    );
}
