"use client";
import ContactHero from '@/components/ContactHero';
import Footer from '@/components/Footer';
import BackgroundGradients from '@/components/BackgroundGradients';
import FindYourWaste from '@/components/FindYourWaste';
import { useEffect, useState } from 'react';
import WhatAreEWCCodes from '@/components/WhatAreEWCCodes';
import HowToInterpretLer from '@/components/HowToInterpretLer';
import ErrorFallback from "@/components/ErrorFallback";
import PageLoading from "@/components/PageLoading";
import { getStoredLocale, getStoredLocaleRaw, LOCALE_CHANGE_EVENT } from "@/i18n/localeSwitcher";

const CODE_ZIGZAG_COUNT = 3;

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

    async function loadServicesPage() {
        setIsLoading(true);
        setIsError(false);
        try {
            const xMedusaLocale = (getStoredLocaleRaw() ?? getStoredLocale()).trim();
            const res = await fetch(
                `${process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL}/store/pages/ewc-code-page`,
                {
                    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) {
                setIsError(true);
                return;
            }
            const json = await res.json();
            setPageData(json);
        } catch (err) {
            setIsError(true);
        } finally {
            setIsLoading(false);
        }
    }

    useEffect(() => {
        loadServicesPage();
    }, []);

    useEffect(() => {
        const onLocaleChange = () => {
            void loadServicesPage();
        };
        if (typeof window !== "undefined") {
            window.addEventListener(LOCALE_CHANGE_EVENT, onLocaleChange);
        }
        return () => {
            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()))
        );
        return section?.components?.[0]?.instance?.data ?? null;
    };

    const bannerSection = findSectionData("banner-section");
    const bannerData = bannerSection?.items?.[0] ?? bannerSection;

    const whatAreEwcSectionData = findSectionData("what-are-ewc-codes");
    const whatAreEwcItem = whatAreEwcSectionData?.items?.[0] ?? whatAreEwcSectionData;

    const whatAreEwcData = whatAreEwcSectionData
        ? {
            title: whatAreEwcItem?.title ?? "",
            description: whatAreEwcItem?.description ?? "",
            intro_text:
                whatAreEwcItem?.card_deatil?.items?.map((item: any) => ({
                    value: item.title ?? "",
                    label: item.richtext ?? "",
                    svg: item.svg ?? "",
                })) ?? [],
        }
        : undefined;

    const howToInterpretSectionData = findSectionData("how-to-interpret");
    const howToInterpretItem = howToInterpretSectionData?.items?.[0] ?? howToInterpretSectionData;

    const interpretStepItems =
        howToInterpretItem?.interpret_steps?.items ??
        howToInterpretItem?.steps?.items ??
        howToInterpretItem?.process_steps?.items ??
        [];

    const howToInterpretData = howToInterpretSectionData
        ? {
            title: howToInterpretItem?.title ?? "",
            description: howToInterpretItem?.description ?? "",
            about_code_info:
                howToInterpretItem?.about_code_info ??
                howToInterpretItem?.footer_html ??
                howToInterpretItem?.bottom_content ??
                "",
            interpret_steps: {
                items: interpretStepItems.map((item: any) => ({
                    "step_no.":
                        item["step_no."] ??
                        item.step_no ??
                        item.number ??
                        item.id ??
                        "",
                    step_tag: item.step_tag ?? item.label ?? item.tag ?? "",
                    title: item.title ?? "",
                    description:
                        item.description ??
                        item.content ??
                        item.html ??
                        item.richtext ??
                        "",
                })),
            },
        }
        : undefined;

    const findYourWasteSectionData = findSectionData("find-your-waste");
    const findYourWasteRawItems =
        (Array.isArray(findYourWasteSectionData?.items) ? findYourWasteSectionData.items : null) ??
        (Array.isArray(findYourWasteSectionData?.categories?.items)
            ? findYourWasteSectionData.categories.items
            : null) ??
        (Array.isArray(findYourWasteSectionData) ? findYourWasteSectionData : []) ??
        [];

    const findYourWasteData = findYourWasteRawItems.map((item: any) => {
        const nestedSource =
            item.cat?.items ??
            item.nested?.items ??
            item.subcategories?.items ??
            item.children?.items ??
            item.items ??
            [];
        const nested = Array.isArray(nestedSource)
            ? nestedSource.map((nestedItem: any, nIdx: number) => ({
                id: String(nestedItem.id ?? nIdx + 1).padStart(2, "0"),
                title: nestedItem.title ?? nestedItem.name ?? "",
                content:
                    nestedItem.content ??
                    nestedItem.html ??
                    nestedItem.richtext ??
                    nestedItem.description ??
                    "",
            }))
            : [];
        return {
            section_title: item.section_title ?? item.title ?? item.name ?? "",
            cat: { items: nested },
        };
    });

    const findYourWasteTitle = findYourWasteSectionData?.title ?? findYourWasteSectionData?.items?.[0]?.title ?? findYourWasteSectionData?.heading ?? "";
    const findYourWasteSearchPlaceholder =
        findYourWasteSectionData?.search_placeholder ?? findYourWasteSectionData?.items?.[0]?.search_placeholder ?? findYourWasteSectionData?.placeholder ?? "";

    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 />;
    }
    if (isError || sections.length === 0) {
        return <ErrorFallback onRetry={loadServicesPage} />;
    }


    return (
        <main className="min-h-screen px-[20px] md:px-[40px] xl:px-[60px] xl:max-w-[1440px] 2xl:max-w-[1920px] mx-auto font-outfit">
             <style dangerouslySetInnerHTML={{
                __html: `
                .rich-text-container ol {
                    list-style-type: decimal !important;
                    padding-left: 1.5rem !important;
                    margin-bottom: 1.5rem !important;
                    margin-top: 1rem !important;
                }
                .rich-text-container ul {
                    list-style-type: disc !important;
                    padding-left: 1.5rem !important;
                    margin-bottom: 1.5rem !important;
                    margin-top: 1rem !important;
                }
                .rich-text-container li {
                    margin-bottom: 0.5rem !important;
                }
                .rich-text-container p {
                    margin-bottom: 1rem;
                }
                .rich-text-container a {
                    color: inherit;
                    text-decoration: underline;
                }
            `}} />
            <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={CODE_ZIGZAG_COUNT} />
            <WhatAreEWCCodes data={whatAreEwcData} />
            <HowToInterpretLer data={howToInterpretData} />
            <FindYourWaste
                data={findYourWasteData}
                title={findYourWasteTitle}
                searchPlaceholder={findYourWasteSearchPlaceholder}
            />
            <Footer />
        </main>
    );
}