"use client"

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

export type EventRowProps = {
  /** datetime 8601 format */
  date: string,
  end?: 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, end, 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 endObj = useMemo(() => end ? new Date(end) : undefined, [end]);
  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={styles.details}>
          <span className={classNames({ [styles.cancelled]: cancelled })}>{title}</span>
          {cancelled && <span className={styles.cancelledLabel}>Abgesagt</span>}
          <br />
          <span className={classNames({ [styles.cancelled]: cancelled })}>
            { showDate &&
              <>
                {formatEventDate(dateObj, endObj, dayFormat)}
                <br />
              </>
            }
            {location}
          </span>
        </div>
      </div>
    </Link>
  );
}