import type { Metadata } from "next";
import ContactHero from "../../components/ContactHero";
import ContactContent from "../../components/ContactContent";
import BackgroundGradients from "@/components/BackgroundGradients";
import Footer from "@/components/Footer";
import { buildDynamicMetadata } from "@/lib/metadata";
import StaticPageSchema from "@/components/StaticPageSchema";
import { getMedusaLocaleHeaderForStoreApi } from "@/i18n/localeSwitcher";
import { cookies } from "next/headers";

const CONTACT_ZIGZAG_COUNT = 1;

async function getMedusaLocaleHeaderValue(): Promise<string> {
  const jar = await cookies();
  return getMedusaLocaleHeaderForStoreApi(jar);
}

async function getContactPageData() {
  const xMedusaLocale = await getMedusaLocaleHeaderValue();
  const res = await fetch(
    `${process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL}/store/pages/contact-us`,
    {
      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) {
    throw new Error("Failed to fetch Contact page data");
  }

  return res.json();
}

async function getFooterData() {
    const xMedusaLocale = await getMedusaLocaleHeaderValue();
    const res = await fetch(
      `${process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL}/store/pages/footer`,
      {
        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) {
      throw new Error("Failed to fetch Footer data");
    }
  
    return res.json();
}

function getContactSeoMeta(data: any) {
  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 };
}

function getContactOpenGraph(data: any) {
  const seoSection = data?.page?.sections?.find((section: any) => section.key === "open-graph-section");
  const seoComponent = seoSection?.components?.find(
    (component: any) =>
      component?.type?.name === "open_graph"
  );
  const seoItem = seoComponent?.instance?.data ?? {};

  const title = typeof seoItem?.title === "string" ? seoItem.title : "";
  const description = typeof seoItem?.description === "string" ? seoItem.description : "";
  const image =
    typeof seoItem?.image?.items?.[0]?.image === "string" ? seoItem.image.items[0].image : "";

  return { title, description, image };
}

export async function generateMetadata(): Promise<Metadata> {
  const data = await getContactPageData().catch(() => ({ page: { sections: [] } }));
  const seo = getContactSeoMeta(data);
  const openGraph = getContactOpenGraph(data);
  return buildDynamicMetadata({
    seoTitle: seo.title,
    seoDescription: seo.description,
    seoKeywords: seo.keywords,
    pageUrl: "/contact",
    ogTitle: openGraph.title,
    ogDescription: openGraph.description,
    ogImage: openGraph.image,
    fallbackTitle: "Biomket",
    fallbackDescription: "Biomket marketplace",
  });
}

export default async function Page() {
  const contactData = await getContactPageData();
  const footerData = await getFooterData();

  const sections = contactData?.page?.sections || [];
  const heroData = sections.find((s: any) => s.key === "contact-hero")?.components?.[0]?.instance?.data?.items?.[0];
  const extraCards = sections.find((s: any) => s.key === "address-section")?.components?.[0]?.instance?.data?.items || [];

  const footerSections = footerData?.page?.sections || [];
  const addressItems = footerSections.find((s: any) => s.key === "address")?.components?.[0]?.instance?.data?.items || [];

  return (
    <>
      <StaticPageSchema
        apiSlug="contact-us"
        pageUrl="/contact"
        fallbackTitle="Contact"
        fallbackDescription="Get in touch with Biomket."
      />
      <div className="relative w-full min-h-screen">
        <div className="mx-auto max-w-[1440px] px-[20px] md:px-0 lg:px-[60px] rounded-[20px] xl:max-w-[1440px] 2xl:max-w-[1920px]">
          <div className="md:px-[40px] lg:px-0">
          <ContactHero 
            headline={<h1 className="font-lexend font-extralight text-[#ffffff] max-w-[782px]">
              {(() => {
                const words = heroData?.title.trim().split(/\s+/);
                return (
                  <>
                    {words.slice(0, 3).join(" ")}{" "}
                    {words.length > 3 ? (
                      <span className="font-medium">{words.slice(3).join(" ")}</span>
                    ) : null}
                  </>
                );
              })()}
            </h1>} 
            description={heroData?.description} 
            backgroundImageMobile={heroData?.bg_image?.items?.[0]?.image_mobile}
            backgroundImageDesktop={heroData?.bg_image?.items?.[0]?.image_desktop}
            backgroundImageMobileAlt={heroData?.bg_image?.items?.[0]?.mobile_image_alt_tag}
            backgroundImageDesktopAlt={heroData?.bg_image?.items?.[0]?.desktop_image_alt_tag}
          />
        </div>
        <BackgroundGradients count={CONTACT_ZIGZAG_COUNT} />

        <ContactContent 
            addressItems={addressItems}
            extraItems={extraCards}
        />

          <Footer />
        </div>
      </div>
    </>
  );
}
