"use client";

import styles from "./eventItem.module.scss";
import Link from "next/link";
import Image from "../general/Image";
import {
  SingularEvent,
  EventFragment,
  getFutureOccurrences,
} from "@/lib/event";
import { formatDate, formatExtendedDateTime } from "@/lib/date";

const DATES_TO_SHOW = 2;

export const EventItem = ({
  event,
  mode,
  size,
}: {
  event: SingularEvent | EventFragment;
  mode: "list" | "calendar" | "singular";
  size?: "small" | "medium" | "large";
}) => {
  const futureOccurrences = getFutureOccurrences(event);
  const numOccurrences = event?.occurrences?.length ?? 0;
  const nextOccurrence = numOccurrences ? futureOccurrences[0] : null;
  const featuredImage: any = event.featuredImage;

  return (
    <li
      className={`${styles.eventItem} ${
        size ? styles[size] : styles.large
      } linkItem`}
    >
      <div className={styles.image}>
        {featuredImage && (
          <Image
            src={featuredImage.url}
            alt={featuredImage.alt}
            width={0}
            height={0}
            sizes="20vw"
          />
        )}
      </div>
      <div className={styles.time}>
        {mode === "list" && nextOccurrence && (
          <div className={styles.dates}>
            {futureOccurrences.slice(0, DATES_TO_SHOW).map((occurrence) => (
              <span key={occurrence.id} className={styles.datePill}>
                {formatDate(occurrence.start, "d. MMMM")}
              </span>
            ))}
            {futureOccurrences.length > DATES_TO_SHOW && (
              <span className={styles.moreDates}>{`+${
                futureOccurrences.length - DATES_TO_SHOW
              }`}</span>
            )}
          </div>
        )}
        {mode === "singular" &&
          "occurrence" in event &&
          event.occurrence?.start && (
            <p className={styles.dates}>
              {formatExtendedDateTime(event.occurrence.start)}
            </p>
          )}
        {mode === "calendar" &&
          "occurrence" in event &&
          event.occurrence?.start && (
            <p className={styles.dates}>
              {formatDate(event.occurrence?.start, "'kl.' HH:mm")}
            </p>
          )}
      </div>
      <div className={styles.text}>
        <h1 className={styles.title}>{event.title}</h1>
        <p className={styles.details}>Evt. andre detaljer</p>
      </div>
      <Link href={`/arrangementer/${event.slug}`} className="hiddenLink">
        Mer om arrangementet {event.title}
      </Link>
    </li>
  );
};
