"use client";

import type { CSSProperties, ReactNode } from "react";
import type { Locale } from "date-fns";

import { cn } from "@/lib/utils";
import { Typography } from "@/components/ui/typography";

import { DEFAULT_EVENT_COLOR, EVENT_COLOR_CLASSES } from "./constants";
import { formatTimeRange } from "./lib/date-utils";
import type { CalendarEvent } from "./types";

interface EventBlockProps<TMeta> {
  event: CalendarEvent<TMeta>;
  locale: Locale;
  /** Absolute position/size (top/height/inset-inline-start/width), supplied by the view. */
  style: CSSProperties;
  /** Hide the time line for very short blocks. */
  compact?: boolean;
  onClick: (event: CalendarEvent<TMeta>) => void;
  renderEvent?: (event: CalendarEvent<TMeta>) => ReactNode;
}

/** A timed event box positioned inside a week/day time column. */
export function EventBlock<TMeta>({
  event,
  locale,
  style,
  compact,
  onClick,
  renderEvent,
}: EventBlockProps<TMeta>) {
  const color = EVENT_COLOR_CLASSES[event.color ?? DEFAULT_EVENT_COLOR];

  return (
    <button
      type="button"
      style={style}
      onClick={(e) => {
        e.stopPropagation();
        onClick(event);
      }}
      className={cn(
        "pointer-events-auto absolute z-10 overflow-hidden rounded-md border px-1.5 py-1 text-start transition-shadow hover:shadow-sm",
        color.block,
      )}
    >
      {renderEvent ? (
        renderEvent(event)
      ) : (
        <div className="flex min-w-0 flex-col leading-tight">
          <Typography
            as="span"
            variant="caption"
            color="inherit"
            className="truncate font-medium"
          >
            {event.title}
          </Typography>
          {!compact && (
            <Typography
              as="span"
              variant="caption"
              color="inherit"
              className="truncate opacity-80"
            >
              {formatTimeRange(event.start, event.end, locale)}
            </Typography>
          )}
        </div>
      )}
    </button>
  );
}
