import type { Metadata } from "next";
import type { ReactNode } from "react";
import { notFound } from 'next/navigation';
import BlockResolver from "@/components/BlockResolver/BlockResolver";
import BreadcrumbLayout from "@/layouts/BreadcrumbLayout";
import { generateMeta } from "@/utils/generateMeta";
import { stripHtmlTags } from "@/utils/stripHtmlTags";
import { unescapeHtml } from "@/utils/unescapeHtml";
import { Product, Service as ServiceSchema, WithContext } from "schema-dts";
import { getCachedServiceRouteParams, getRawServiceByPath, getServicePathPrefix } from "@/services/wp";

type Props = {
  params: Promise<{ pageSlug: string[] }>;
  searchParams: Promise<{ [key: string]: string | string[] | undefined }>;
};

const formatSlugLabel = (value: string) =>
  value
    .replace(/-/g, " ")
    .replace(/\b\w/g, (match) => match.toUpperCase());

const removeTrailingSlash = (value: string) => value.replace(/\/+$/, "");

const getLayout = (
  page: ReactNode,
  siteUrl: string,
  breadcrumbItems: { label: string; href: string }[]
) => {
  return (
    <BreadcrumbLayout siteUrl={siteUrl} items={breadcrumbItems}>
      {page}
    </BreadcrumbLayout>
  );
};

type SchemaReview = {
  "@type": "Review";
  reviewBody: string;
  datePublished?: string;
  author?: {
    "@type": "Person";
    name: string;
  };
  reviewRating?: {
    "@type": "Rating";
    ratingValue: number;
  };
};

const parseRatingValue = (value: unknown): number | null => {
  if (typeof value === "number" && Number.isFinite(value)) {
    return Math.min(5, Math.max(1, value));
  }

  if (typeof value === "string") {
    const parsed = Number(value.trim());
    if (Number.isFinite(parsed)) {
      return Math.min(5, Math.max(1, parsed));
    }
  }

  return null;
};

const extractSchemaReviews = (acf: any): SchemaReview[] => {
  const reviewCandidates = [
    acf?.reviews,
    acf?.service_reviews,
    acf?.schema_reviews,
    acf?.testimonials,
  ].find((candidate) => Array.isArray(candidate));

  if (!Array.isArray(reviewCandidates)) {
    return [];
  }

  return reviewCandidates
    .map((item: any) => {
      const reviewBody = item?.reviewBody || item?.review_body || item?.content || item?.review;
      const authorName = item?.author?.name || item?.author_name || item?.name || item?.author;
      const datePublished = item?.datePublished || item?.date_published || item?.date;
      const ratingValue = parseRatingValue(
        item?.reviewRating?.ratingValue || item?.review_rating || item?.rating || item?.rating_value
      );

      if (typeof reviewBody !== "string" || !reviewBody.trim()) {
        return null;
      }

      const review: SchemaReview = {
        "@type": "Review",
        reviewBody: reviewBody.trim(),
      };

      if (typeof authorName === "string" && authorName.trim()) {
        review.author = {
          "@type": "Person",
          name: authorName.trim(),
        };
      }

      if (typeof datePublished === "string" && datePublished.trim()) {
        review.datePublished = datePublished.trim();
      }

      if (ratingValue !== null) {
        review.reviewRating = {
          "@type": "Rating",
          ratingValue,
        };
      }

      return review;
    })
    .filter((review): review is SchemaReview => Boolean(review));
};

const Service = async (props: { params: Promise<{ pageSlug: string[] }> }) => {
  const params = await props.params;
  const slugs = [...(params.pageSlug || [])].filter(Boolean);

  if (slugs.length === 0) {
    notFound();
  }

  let currentService: Awaited<ReturnType<typeof getRawServiceByPath>> = null;

  try {
    currentService = await getRawServiceByPath(slugs);
  } catch {
    notFound();
  }

  if (!currentService) {
    notFound();
  }

  const siteUrl = removeTrailingSlash(process.env.SITE_URL || "https://teapot.agency");
  const rawName = currentService.acf?.meta_title || currentService.title?.rendered || currentService.name || formatSlugLabel(slugs[slugs.length - 1]);
  const jsonName = stripHtmlTags(unescapeHtml(String(rawName))).trim();
  const rawDescription = currentService.acf?.meta_description || currentService.name || currentService.title?.rendered || "";
  const description = stripHtmlTags(unescapeHtml(String(rawDescription))).trim();
  const serviceUrl = currentService.link || currentService.permalink || `${siteUrl}/services/${slugs.join("/")}`;
  const organizationId = `${siteUrl}/#organization`;
  const serviceId = `${serviceUrl}#service`;
  const schemaReviews = extractSchemaReviews(currentService.acf);
  const ratingValues = schemaReviews
    .map((review) => review.reviewRating?.ratingValue)
    .filter((value): value is number => typeof value === "number");
  const averageRating = ratingValues.length
    ? Number((ratingValues.reduce((sum, value) => sum + value, 0) / ratingValues.length).toFixed(1))
    : null;
  const breadcrumbItems = [
    { label: "Home", href: "/" },
    { label: "Services", href: "/services" },
    ...slugs.map((slug, index) => {
      const isLast = index === slugs.length - 1;
      return {
        label: isLast
          ? currentService.title?.rendered || currentService.name || formatSlugLabel(slug)
          : formatSlugLabel(slug),
        href: `/services/${slugs.slice(0, index + 1).join("/")}`,
      };
    }),
  ];

  const jsonLd: WithContext<Product> = {
    "@context": "https://schema.org",
    "@type": "Product",
    "@id": `${serviceUrl}#product`,
    name: jsonName,
    image: `${siteUrl}/image/teapot.svg`,
    url: serviceUrl,
    description,
    brand: {
      "@type": "Brand",
      name: "Teapot",
    },
    ...(averageRating !== null && schemaReviews.length > 0
      ? {
          aggregateRating: {
            "@type": "AggregateRating",
            ratingValue: averageRating,
            reviewCount: schemaReviews.length,
            bestRating: 5,
            worstRating: 1,
          },
        }
      : {}),
    ...(schemaReviews.length > 0 ? { review: schemaReviews } : {}),
  };

  const serviceJsonLd: WithContext<ServiceSchema> = {
    "@context": "https://schema.org",
    "@type": "Service",
    "@id": serviceId,
    name: jsonName,
    description,
    url: serviceUrl,
    serviceType: formatSlugLabel(slugs[0] || "Service"),
    mainEntityOfPage: serviceUrl,
    areaServed: {
      "@type": "Country",
      name: "United Kingdom",
    },
    provider: {
      "@type": "Organization",
      "@id": organizationId,
      name: "Teapot",
      url: siteUrl,
      logo: `${siteUrl}/image/teapot.svg`,
    },
  };

  return (
    <>
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
      />
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(serviceJsonLd) }}
      />
      {getLayout(<BlockResolver blocks={currentService.blocks_json} />, siteUrl, breadcrumbItems)}
    </>
  );
};

export const generateStaticParams = async () => {
  try {
    return await getCachedServiceRouteParams();
  } catch {
    return [];
  }
};

export const generateMetadata = async (props: Props): Promise<Metadata> => {
  const params = await props.params;
  const slugs = [...(params.pageSlug || [])].filter(Boolean);

  if (slugs.length === 0) {
    notFound();
  }

  let currentService: Awaited<ReturnType<typeof getRawServiceByPath>> = null;

  try {
    currentService = await getRawServiceByPath(slugs);
  } catch {
    notFound();
  }

  if (!currentService) {
    notFound();
  }

  let prefix = "services";

  try {
    prefix = await getServicePathPrefix(currentService);
  } catch {
    prefix = "services";
  }

  return generateMeta([currentService], prefix);
};

export default Service;
