import { notFound } from "next/navigation";
import * as cheerio from "cheerio";

import { formatSection } from "@/utils/posts-utils";
import {
  mapUnitSlugToComponentMapping,
  type ServiceFeaturePost,
  type ServiceResourcePost,
} from "@/components/pages/client/services/services";
import {
  SERVICE_FEATURE_TAGS,
  SERVICE_RESOURCE_TAGS,
  ServicesBlogSentences,
  isServiceUnit,
} from "@/constants/services-data";
import { fetchPostsByTag } from "@/services/blogActions";
import { trustedGhostPdfUrl } from "@/utils/ghost-pdf";
import { loadConsumerRecruitmentContent } from "@/lib/services-ghost-content";

type Params = Promise<{ unit: string }>;

function extractDownloadUrl(html: string) {
  const $ = cheerio.load(html);
  const fileCard = $(".kg-file-card").first();
  const href = fileCard.is("a")
    ? fileCard.attr("href")
    : fileCard.find("a").first().attr("href");

  if (!href) {
    return undefined;
  }

  return trustedGhostPdfUrl(href)?.toString();
}

export async function generateMetadata({ params }: { params: Params }) {
  const { unit } = await params;
  const formattedTitle = `${formatSection(unit)} | Services`;

  const description = isServiceUnit(unit)
    ? ServicesBlogSentences[unit]
    : "Explore the range of participant recruitment services offered by People for Research, from usability testing to global market research, ensuring reliable insights for your project.";

  return {
    title: formattedTitle,
    description,
    openGraph: {
      title: formattedTitle,
      description,
      images: [
        {
          url: "/global-assets/pfr-logo-og-client.svg",
          alt: "People for Research logo, featuring a person inside a circle, representing a focus on human-centered research and activities.",
          width: 200,
          height: 150,
        },
      ],
    },
    twitter: {
      card: "summary_large_image",
      title: formattedTitle,
      images: "/global-assets/pfr-logo-og-client.svg",
      description,
    },
  };
}

export default async function ServiceUnitPage({ params }: { params: Params }) {
  const { unit } = await params;
  if (!isServiceUnit(unit)) {
    notFound();
  }

  const ServiceComponent = mapUnitSlugToComponentMapping(unit);
  const resourceTag = SERVICE_RESOURCE_TAGS[unit];
  const fetchPostForTag = async (tag: string) => {
    try {
      return (
        await fetchPostsByTag([tag], 1, {
          revalidate: 60,
          timeoutMs: 5000,
        })
      ).posts[0];
    } catch {
      return undefined;
    }
  };
  const [featuredPostData, resourcePostData, ghostContent] = await Promise.all([
    fetchPostForTag(SERVICE_FEATURE_TAGS[unit]),
    resourceTag ? fetchPostForTag(resourceTag) : Promise.resolve(undefined),
    unit === "consumer-recruitment"
      ? loadConsumerRecruitmentContent()
      : Promise.resolve(undefined),
  ]);
  let featuredPost: ServiceFeaturePost | undefined;
  let resourcePost: ServiceResourcePost | undefined;

  if (featuredPostData) {
    const { title, slug, feature_image, feature_image_alt } = featuredPostData;
    featuredPost = { title, slug, feature_image, feature_image_alt };
  }

  if (resourcePostData?.title.trim() && resourcePostData.feature_image) {
    const downloadUrl = extractDownloadUrl(resourcePostData.html);

    if (downloadUrl) {
      const { title, feature_image, feature_image_alt } = resourcePostData;
      resourcePost = {
        title,
        feature_image,
        feature_image_alt,
        downloadUrl,
      };
    }
  }

  return (
    <ServiceComponent
      consumerContent={ghostContent}
      featuredPost={featuredPost}
      resourcePost={resourcePost}
    />
  );
}
