"use client";

import { useState } from "react";
import {
  formatDate,
  formatExtendedDateTime,
  isTodayOrFuture,
  compareDates,
} from "@/lib/date";
import { EventFragment, EventOccurrence } from "@/lib/event";
import styles from "./dateList.module.scss";
import Link from "next/link";

const DateListItem = ({ occurrence }: { occurrence: EventOccurrence }) => {
  const dateFormat = "EEEE d. MMMM yyyy";
  const timeFormat = "'kl.' HH:mm";

  return (
    <li className={styles.date}>
      <div className={styles.time}>
        <span className={styles.day}>
          {formatExtendedDateTime(occurrence.start, true)}
        </span>
        <span className={styles.hour}>
          {formatDate(occurrence.start, timeFormat)}
        </span>
      </div>
      <div className={styles.venue}>
        <span>
          {occurrence.venue?.preposition + " " ?? ""}
          {occurrence.venue?.url && (
            <Link href={occurrence.venue?.url}>{occurrence.venue?.title}</Link>
          )}
          {!occurrence.venue?.url && <>{occurrence.venue?.title}</>}
        </span>
      </div>
    </li>
  );
};

export const DateList = ({ event }: { event: EventFragment }) => {
  const [showPast, setShowPast] = useState(false);

  const futureOccurrences = event.occurrences
    .filter((occurrence) => isTodayOrFuture(occurrence.start))
    .sort((a, b) => compareDates(a.start, b.start));
  const pastOccurrences = event.occurrences
    .filter((occurrence) => !isTodayOrFuture(occurrence.start))
    .sort((a, b) => compareDates(a.start, b.start));

  // TODO: events occurring once
  // TODO: end date/time?
  // TODO: past occurrences?

  return (
    <div className={styles.dateWrapper}>
      <h2 className="suphead">
        Kommende datoer{" "}
        <span className="number">({futureOccurrences.length})</span>
      </h2>
      <ul className={styles.dateList}>
        {futureOccurrences.map((occurrence) => (
          <DateListItem
            key={occurrence.id}
            occurrence={occurrence as EventOccurrence}
          />
        ))}
      </ul>
      {/* <div onClick={() => setShowPast(!showPast)}>
        {showPast ? "Skjul" : "Vis"} tidligere
      </div>
      {showPast && (
        <>
          <h2 className="circlehead">
            <span className="circle"></span>
            <span className="circle"></span>
            <span className="circle"></span>
            Tidligere datoer{" "}
            <span className="number">({pastOccurrences.length})</span>
          </h2>
          <ul className={styles.dateList}>
            {pastOccurrences.map((occurrence) => (
              <DateListItem key={occurrence.id} occurrence={occurrence} />
            ))}
          </ul>
        </>
      )} */}
    </div>
  );
};
