'use client';
import WasteManagement from '../../components/WasteManagement';
import ContactHero from '../../components/ContactHero';
import ProvenProcess from '@/components/ProvenProcess';
import IndustrySolutions from '@/components/IndustrySolutions';
import QuoteForm, { type QuoteFormFieldItem } from '@/components/QuoteForm';
import WhyChooseUs from '@/components/WhyChooseUs';
import Certifications from '@/components/Certifications';
import BackgroundGradients from '@/components/BackgroundGradients';
import Footer from '@/components/Footer';
import PageLoading from '@/components/PageLoading';
import { useEffect, useState } from 'react';
import StaticPageSchema from "@/components/StaticPageSchema";
import {
  DEFAULT_LOCALE,
  getStoredLocale,
  getStoredLocaleRaw,
  LOCALE_CHANGE_EVENT,
  type LocaleCode,
} from '@/i18n/localeSwitcher';

const SERVICES_ZIGZAG_COUNT = 9;

const QUOTE_CMS_FORM_NAME = "Personalized Quote";

function parseQuoteFormChoicesFromFormOptionsApi(apiJson: unknown): {
  industry_type: QuoteFormFieldItem[];
  waste_volume: QuoteFormFieldItem[];
} {
  const empty = { industry_type: [] as QuoteFormFieldItem[], waste_volume: [] as QuoteFormFieldItem[] };
  const root = apiJson as Record<string, unknown> | null | undefined;
  if (!root) return empty;

  let formsRoot: Record<string, unknown> | undefined;
  if (typeof root.forms === "object" && root.forms !== null) {
    formsRoot = root.forms as Record<string, unknown>;
  } else if (root[QUOTE_CMS_FORM_NAME] != null || root["personalized quote"] != null) {
    formsRoot = root;
  }

  if (!formsRoot) return empty;

  const block =
    (formsRoot[QUOTE_CMS_FORM_NAME] as Record<string, unknown> | undefined) ??
    (formsRoot["personalized quote"] as Record<string, unknown> | undefined);

  if (!block || typeof block !== "object") return empty;

  return {
    industry_type: (Array.isArray(block.industry_type) ? block.industry_type : []) as QuoteFormFieldItem[],
    waste_volume: (Array.isArray(block.waste_volume) ? block.waste_volume : []) as QuoteFormFieldItem[],
  };
}

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

function getServicesSeoMeta(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 ServicesPage() {
  const [pageData, setPageData] = useState<any>(null);
  const [quoteFormFields, setQuoteFormFields] = useState<{
    industry_type: QuoteFormFieldItem[];
    waste_volume: QuoteFormFieldItem[];
  }>({ industry_type: [], waste_volume: [] });
  const [isLoading, setIsLoading] = useState(true);
  const [seo, setSeo] = useState<SeoMeta>({
    title: "Biomket",
    description: "Biomket marketplace",
    keywords: [],
  });
  const [uiLocale, setUiLocale] = useState<LocaleCode>(DEFAULT_LOCALE);

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

    const loadServicesPage = async () => {
      const xMedusaLocale = (getStoredLocaleRaw() ?? getStoredLocale()).trim();
      try {
        const base = (process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL ?? "").replace(/\/$/, "");
        const publishable = process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_API_KEY || "";
        const headers = { "x-publishable-api-key": publishable, "x-medusa-locale": xMedusaLocale };

        const [pageRes, formOptionsRes] = await Promise.all([
          fetch(`${base}/store/pages/services`, { method: "GET", headers, cache: "no-store" }),
          fetch(`${base}/store/form-options`, { method: "GET", headers, cache: "no-store" }),
        ]);

        if (pageRes.ok && isMounted) {
          const servicesPageJson = await pageRes.json();
          setPageData(servicesPageJson);
          setSeo(getServicesSeoMeta(servicesPageJson));
        }

        if (formOptionsRes.ok && isMounted) {
          try {
            const formOptionsJson = await formOptionsRes.json();
            setQuoteFormFields(parseQuoteFormChoicesFromFormOptionsApi(formOptionsJson));
          } catch {
            setQuoteFormFields({ industry_type: [], waste_volume: [] });
          }
        }
      } catch {
      } finally {
        if (isMounted) setIsLoading(false);
      }
    };

    loadServicesPage();
    return () => {
      isMounted = false;
    };
  }, [uiLocale]);

  useEffect(() => {
    const syncLocale = () => setUiLocale(getStoredLocale());
    syncLocale();
    window.addEventListener("storage", syncLocale);
    window.addEventListener(LOCALE_CHANGE_EVENT, syncLocale);
    return () => {
      window.removeEventListener("storage", syncLocale);
      window.removeEventListener(LOCALE_CHANGE_EVENT, syncLocale);
    };
  }, []);

  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;
    return data?.items?.[0] ?? data ?? null;
  };

  const bannerData = findSectionData("service-hero");
  const wasteManagementSectionData = findSectionData("waste-management");
  const provenProcessSectionData = findSectionData("proven-process");
  const industrySolutionsSectionData = findSectionData("industry-solutions");
  const whyChooseUsSectionData = findSectionData("why-choose-us");
  const certificationsSectionData = findSectionData("certifications--partnerships");

  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 ?? "";
  const heroButton1Label = bannerData?.button?.items?.[0]?.button_text ?? bannerData?.buttontext1 ?? "";
  const heroButton1Url = bannerData?.button?.items?.[0]?.button_url ?? bannerData?.buttontext1url ?? "";
  const heroButton2Label = bannerData?.button?.items?.[1]?.button_text ?? bannerData?.buttontext2 ?? "";
  const pageMeta = pageData?.page?.page?.meta ?? {};
  const brochureUrl = pageMeta?.brochure_url ?? "";
  const brochureFilename = pageMeta?.brochure_filename ?? "";
  const heroButton2Url = brochureUrl || (bannerData?.button?.items?.[1]?.button_url ?? bannerData?.buttontext2url ?? "");

  const wasteManagementData = wasteManagementSectionData
    ? {
      title: wasteManagementSectionData.title ?? "",
      description: wasteManagementSectionData.description ?? "",
      services:
        wasteManagementSectionData.cards?.items?.map((item: any) => ({
          title: item.title ?? "",
          description: String(item.description ?? item.content ?? item.html ?? item.richtext ?? "")
            .replace(/<ul[\s\S]*<\/ul>/i, "")
            .trim(),
          list:
            item.points?.items
              ?.map((p: any) => p.html ?? p.content ?? p.description ?? p.text ?? p.title ?? "")
              .filter(Boolean) ??
            (String(item.richtext ?? "").match(/<li\b[^>]*>[\s\S]*?<\/li>/gi)?.map((li: string) =>
              li.replace(/^<li\b[^>]*>/i, "").replace(/<\/li>$/i, "").trim()
            ) ?? []),
          svg: item.svg ?? "",
        })) ??
        wasteManagementSectionData.cards?.items?.map((item: any) => ({
          title: item.title ?? "",
          description: item.description ?? "",
          list: [],
          svg: item.svg ?? "",
        })) ??
        [],
    }
    : undefined;

  const provenProcessData = provenProcessSectionData
    ? {
      title: provenProcessSectionData.title ?? "",
      description: provenProcessSectionData.description ?? "",
      steps:
        provenProcessSectionData.process_steps?.items?.map((item: any, i: number) => ({
          id: item["step_no."] ?? item.step_no ?? "",
          number: item["step_no."] ?? item.step_no ?? "",
          week: item.step_tag ?? "",
          weekDesktop: item.step_tag ?? item.step_tag ?? "",
          title: item.title ?? "",
          description: item.description ?? "",
        })) ?? [],
    }
    : undefined;

  const industrySolutionsItems =
    industrySolutionsSectionData?.cards?.items ??
    industrySolutionsSectionData?.cards?.items ??
    [];
  const industrySolutionsData = industrySolutionsSectionData
    ? {
      title: industrySolutionsSectionData.title ?? "",
      description: industrySolutionsSectionData.description ?? "",
      industries: industrySolutionsItems.map((item: any) => ({
        title: item.card_title ?? "",
        challenges: item.subtitle_1 ?? "",
        challenges_description: item.description_1 ?? "",
        solutions: item.subtitle_2 ?? "",
        solutions_description: item.description_2 ?? "",
        results: item.result_subtitle ?? "",
        results_description: item.result_description ?? "",
        svg: item.card_logo ?? "",
      })),
    }
    : undefined;

  const whyChooseUsData = whyChooseUsSectionData
    ? {
      title: whyChooseUsSectionData.title ?? "",
      description: whyChooseUsSectionData.description ?? "",
      stats:
        whyChooseUsSectionData.resions?.items?.map((item: any) => ({
          value: item.title ?? "",
          label: item.subtitle ?? "",
        })) ?? [],
    }
    : undefined;

  const certificationsData = certificationsSectionData
    ? {
      title: certificationsSectionData.title ?? "",
      logos:
        certificationsSectionData.certifications?.items?.map((item: any) => ({
          image: item.image ?? item.image ?? "",
          alt: item.image_alt_tag ?? "",
        })) ?? [],
    }
    : undefined;

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

  return (
    <>
      <StaticPageSchema
        apiSlug="services"
        pageUrl="/services"
        fallbackTitle="Services"
        fallbackDescription="Explore Biomket waste management services."
      />
      <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">

      <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}
      >
        <div className="flex flex-col sm:flex-row gap-4 md:mt-4">

          {heroButton1Label && <a href={heroButton1Url} className="group flex items-center justify-center gap-2 mx-auto bg-[#DAE6DC] text-[#053F31] p-[7px_7px_7px_15px] rounded-full font-semibold cursor-pointer border-2 border-[#DAE6DC] hover:bg-[#DAE6DC]/10 hover:text-white hover:backdrop-blur-sm transition">
            {heroButton1Label}

            <svg width="36" height="36" viewBox="0 0 36 36" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path className="fill-[#053F31] group-hover:fill-[#F7FAF8] transition-colors" d="M0 18C0 8.05887 8.05887 0 18 0V0C27.9411 0 36 8.05887 36 18V18C36 27.9411 27.9411 36 18 36V36C8.05887 36 0 27.9411 0 18V18Z" />
              <path className="stroke-[#DAE6DC] group-hover:stroke-[#053F31] transition-colors" d="M10 18H25.5M25.5 18L19.5 12M25.5 18L19.5 24.5" strokeWidth="2" />
            </svg>

          </a>}

          {heroButton2Label && <a href={heroButton2Url} download={brochureFilename || true} target='_blank' rel='noopener noreferrer' className="group flex items-center justify-center gap-2 border-2 text-[#DAE6DC] border-[#DAE6DC] bg-white/10 backdrop-blur-sm p-[7px_7px_7px_15px] rounded-full font-semibold cursor-pointer hover:bg-[#DAE6DC] hover:text-[#053F31] transition">
            {heroButton2Label}

            <svg width="36" height="36" viewBox="0 0 36 36" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path className="fill-[#F7FAF8] group-hover:fill-[#053F31] transition-colors" d="M0 18C0 8.05888 8.05888 0 18 0C27.9411 0 36 8.05888 36 18C36 27.9411 27.9411 36 18 36C8.05888 36 0 27.9411 0 18Z" />
              <path className="stroke-[#053F31] group-hover:stroke-[#DAE6DC] transition-colors" d="M10 18H25.5M25.5 18L19.5 12M25.5 18L19.5 24.5" strokeWidth="2" />
            </svg>

          </a>}
        </div>
      </ContactHero>
      <BackgroundGradients count={SERVICES_ZIGZAG_COUNT} />
      <WasteManagement data={wasteManagementData} />
      <ProvenProcess data={provenProcessData} />
      <IndustrySolutions data={industrySolutionsData} />
      <QuoteForm
        industryTypeChoices={quoteFormFields.industry_type}
        wasteVolumeChoices={quoteFormFields.waste_volume}
      />
      <WhyChooseUs data={whyChooseUsData} />
      <Certifications data={certificationsData} />
      <Footer />
      </main>
    </>
  );
}