import Link from "next/link";
import Container from "@/components/Container/Container";
import Section from "@/components/Section/Section";
import FAQs from "@/components/FAQs/FAQs";
import { getCachedServicesByIds } from "@/services/wp";
import { stripHtmlTags } from "@/utils/stripHtmlTags";
import { unescapeHtml } from "@/utils/unescapeHtml";
import { FAQPage, WithContext } from "schema-dts";

type ServiceItem = {
  title: string;
  url?: string;
};

const toPathname = (link: string) => {
  try {
    return new URL(link).pathname;
  } catch {
    return link.replace(/^https?:\/\/[^/]+/i, "") || link;
  }
};

const collectServiceIds = (props: { [rest: string]: any }) => {
  const ids: number[] = [];

  for (let i = 0; i < props.services; i++) {
    const selected = props[`services_${i}_service`];
    if (!selected) {
      continue;
    }

    const values = Array.isArray(selected) ? selected : [selected];
    for (const value of values) {
      const id = Number(value);
      if (Number.isFinite(id) && id > 0) {
        ids.push(id);
      }
    }
  }

  return ids;
};

const ServiceFaqBlock = async (props: { [rest: string]: any }) => {
  const faqs: { question: string; answer: string }[] = [];

  for (let i = 0; i < props.faqs; i++) {
    const question = String(props[`faqs_${i}_question`] || "").trim();
    const answer = String(props[`faqs_${i}_answer`] || "").trim();

    if (!question || !answer) {
      continue;
    }

    faqs.push({ question, answer });
  }

  const serviceIds = collectServiceIds(props);
  const selectedServices =
    serviceIds.length > 0 ? await getCachedServicesByIds(serviceIds) : [];
  const serviceById = new Map(
    (Array.isArray(selectedServices) ? selectedServices : []).map((service: any) => [
      Number(service.id),
      service,
    ]),
  );

  const services: ServiceItem[] = [];

  for (let i = 0; i < props.services; i++) {
    const selected = props[`services_${i}_service`];

    if (selected) {
      const values = Array.isArray(selected) ? selected : [selected];
      for (const value of values) {
        const id = Number(value);
        const service = serviceById.get(id);
        if (!service) {
          continue;
        }

        const title = unescapeHtml(
          stripHtmlTags(service.title?.rendered || service.name || ""),
        ).trim();
        const link = service.link || service.permalink;

        if (!title) {
          continue;
        }

        services.push({
          title,
          url: link ? toPathname(String(link)) : undefined,
        });
      }
      continue;
    }

    const title = String(props[`services_${i}_title`] || "").trim();
    const url = String(props[`services_${i}_url`] || "").trim();

    if (title) {
      services.push({ title, url: url || undefined });
    }
  }

  if (services.length < 1 || faqs.length < 1) return <></>;

  const faqJsonLd: WithContext<FAQPage> = {
    "@context": "https://schema.org",
    "@type": "FAQPage",
    mainEntity: faqs.map(({ question, answer }) => ({
      "@type": "Question",
      name: question,
      acceptedAnswer: {
        "@type": "Answer",
        text: answer,
      },
    })),
  };

  return (
    <Container id={props.anchor}>
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(faqJsonLd) }}
      />
      <Section
        gridArea="thin"
        className="grid grid-cols-1 lg:grid-cols-4 gap-x-sm gap-y-md lg:items-start"
      >
        <div className="lg:col-span-1 flex flex-col gap-xs self-start pt-xs">
          <h3 className="h4 m-none leading-none mb-xs">SERVICES</h3>
          <ul className="list-none p-none m-none flex flex-col gap-[0.5rem]">
            {services.map((service, index) => (
              <li key={index}>
                {service.url ? (
                  <Link
                    href={service.url}
                    className="m-none text-[22px] font-bold leading-tight underline underline-offset-2 hover:text-primary"
                  >
                    {service.title}
                  </Link>
                ) : (
                  <span className="m-none text-[22px] font-bold leading-tight">
                    {service.title}
                  </span>
                )}
              </li>
            ))}
          </ul>
        </div>
        <div className="lg:col-span-3 min-w-0 self-start">
          <FAQs faqs={faqs} />
        </div>
      </Section>
    </Container>
  );
};

export default ServiceFaqBlock;
