"use client"

import { useEffect, useMemo, useState } from 'react'
import styles from "./styles.module.scss"
import classNames from 'classnames'
import Link from 'next/link'

export type EventRowProps = {
  /** datetime 8601 format */
  date: string,
  showDate?: boolean
  title: string,
  href?: string,
  location?: string,
  cancelled: boolean
  color?: "base" | "white" | "contrast"
}

/**
 * Given a date in ISO 8601 format,
 * return a short readable version
 */
const shortMonth = (date: string) => {
  const months = [
    "JAN",
    "FEB",
    "MRZ",
    "APR",
    "MAI",
    "JUN",
    "JUL",
    "AUG",
    "SEP",
    "OKT",
    "NOV",
    "DEC"
  ]

  const month = parseInt(date.substring(5, 7));
  return months[month - 1];
}



export const EventRow = ({date, title, location, cancelled, href, color = "base", showDate = true}: EventRowProps) => {
  const day = useMemo(() => date.substring(8, 10), [date]);
  const dateObj = useMemo(() => new Date(date), [date]);
  const month = useMemo(() => shortMonth(date), [date]);
  const [dayFormat, setDayFormat] = useState<"long" | "short">("long")
  useEffect(() => {
    if(window.innerWidth <= 576) {
      setDayFormat("short")
    }
  }, [setDayFormat])

  return (
    <Link href={href || "https://"} className={styles.link}>
      <div className={styles.container}>
        <div className={classNames({
          [styles.day]: true,
          [styles.dayBase]: color === "base",
          [styles.dayContrast]: color === "contrast",
          [styles.dayWhite]: color === "white"
        })}>
          {day} <br />
          {month}
        </div>

        <div className={classNames({
          [styles.line]: true,
          [styles.lineWhite]: color === "white",
        })}></div>

        <div className={classNames({
          [styles.details]: true,
          [styles.cancelled]: cancelled
        })}>
          {title} <br />
          { showDate &&
            <>
              {dateObj.toLocaleDateString("de-DE", { weekday: "long" })}
              {dayFormat === "long" && " " + dateObj.toLocaleDateString("de-DE", { dateStyle: "medium" })}, {dateObj.toLocaleTimeString("de-DE", { timeStyle: "short", timeZone: "Europe/Berlin" })} Uhr
              <br />
            </>
          }
          {location}
        </div>
      </div>
    </Link>
  );
}