import Link from "next/link";
import Container from "@/components/Container/Container";
import Section from "@/components/Section/Section";
import { getCachedServicesByIds } from "@/services/wp";
import { stripHtmlTags } from "@/utils/stripHtmlTags";
import { unescapeHtml } from "@/utils/unescapeHtml";
import styles from "./BulletServiceList.module.css";

type ServiceListItem = {
  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 BulletServiceList = async (props: { [rest: string]: any }) => {
  const serviceIds = collectServiceIds(props);

  if (serviceIds.length < 1) return <></>;

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

  const services: ServiceListItem[] = [];

  for (const id of serviceIds) {
    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,
    });
  }

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

  return (
    <Container id={props.anchor}>
      <Section gridArea="thin">
        <ul className={`${styles.list} grid grid-cols-1 md:grid-cols-2 gap-xs lg:gap-sm`}>
          {services.map((service, index) => {
            if (service.url) {
              return (
                <li key={index}>
                  <Link href={service.url} className={styles.itemLink}>
                    <span className={styles.chevron} aria-hidden="true" />
                    <span className={styles.title}>{service.title}</span>
                  </Link>
                </li>
              );
            }

            return (
              <li key={index} className={styles.item}>
                <span className={styles.chevron} aria-hidden="true" />
                <span className={styles.title}>{service.title}</span>
              </li>
            );
          })}
        </ul>
      </Section>
    </Container>
  );
};

export default BulletServiceList;
