import {
  format,
  isSameDay,
  isToday,
  parseISO,
  differenceInMinutes,
  startOfDay,
} from "date-fns";
import type { CalendarEvent, Calendar } from "../types";
import { eventStart, eventEnd } from "../types";

interface DayViewProps {
  currentDate: Date;
  events: CalendarEvent[];
  calendars: Calendar[];
  visibleCalendarIds: Set<string>;
  onTimeClick: (date: Date) => void;
  onEventClick: (event: CalendarEvent) => void;
}

const HOURS = Array.from({ length: 24 }, (_, i) => i);
const HOUR_HEIGHT = 64;

export default function DayView({
  currentDate,
  events,
  calendars,
  visibleCalendarIds,
  onTimeClick,
  onEventClick,
}: DayViewProps) {
  const calColorMap = new Map(calendars.map((c) => [c.id, c.color]));
  const filtered = events.filter((e) => visibleCalendarIds.has(e.calendar_id));

  const allDayEvents = filtered.filter(
    (e) => e.all_day && isSameDay(parseISO(eventStart(e)), currentDate),
  );
  const timedEvents = filtered.filter(
    (e) => !e.all_day && isSameDay(parseISO(eventStart(e)), currentDate),
  );

  const today = isToday(currentDate);

  const getEventStyle = (evt: CalendarEvent) => {
    const start = parseISO(eventStart(evt));
    const dayStart = startOfDay(start);
    const top = differenceInMinutes(start, dayStart);
    const end = parseISO(eventEnd(evt));
    const duration = Math.max(differenceInMinutes(end, start), 15);
    return {
      top: `${top * (HOUR_HEIGHT / 60)}px`,
      height: `${duration * (HOUR_HEIGHT / 60)}px`,
      minHeight: "24px",
    };
  };

  return (
    <div className="flex flex-col h-full overflow-hidden">
      {/* Header */}
      <div className="text-center py-3 border-b border-gray-200 dark:border-gray-700 flex-shrink-0">
        <div className="text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase">
          {format(currentDate, "EEEE")}
        </div>
        <div
          className={`text-2xl font-bold mt-1 ${
            today
              ? "bg-blue-600 text-white w-10 h-10 rounded-full flex items-center justify-center mx-auto"
              : "text-gray-800 dark:text-gray-200"
          }`}
        >
          {format(currentDate, "d")}
        </div>
      </div>

      {/* All-day */}
      {allDayEvents.length > 0 && (
        <div className="px-4 py-2 border-b border-gray-200 dark:border-gray-700 space-y-1 flex-shrink-0">
          {allDayEvents.map((evt) => (
            <button
              key={evt.id}
              onClick={() => onEventClick(evt)}
              className="block w-full text-left text-sm px-3 py-1.5 rounded-lg text-white font-medium hover:opacity-80"
              style={{ backgroundColor: calColorMap.get(evt.calendar_id) || "#3B82F6" }}
            >
              {evt.title}
            </button>
          ))}
        </div>
      )}

      {/* Time grid */}
      <div className="flex-1 overflow-y-auto">
        <div className="flex relative" style={{ height: `${24 * HOUR_HEIGHT}px` }}>
          <div className="w-20 flex-shrink-0 relative">
            {HOURS.map((h) => (
              <div
                key={h}
                className="absolute w-full text-right pr-3 text-xs text-gray-400 dark:text-gray-500 -mt-2"
                style={{ top: `${h * HOUR_HEIGHT}px` }}
              >
                {h === 0 ? "" : format(new Date(2000, 0, 1, h), "h a")}
              </div>
            ))}
          </div>

          <div className="flex-1 relative border-l border-gray-200 dark:border-gray-700">
            {HOURS.map((h) => (
              <div
                key={h}
                className="absolute w-full border-t border-gray-100 dark:border-gray-700/30 cursor-pointer hover:bg-blue-50/50 dark:hover:bg-blue-900/10"
                style={{ top: `${h * HOUR_HEIGHT}px`, height: `${HOUR_HEIGHT}px` }}
                onClick={() => {
                  const d = new Date(currentDate);
                  d.setHours(h, 0, 0, 0);
                  onTimeClick(d);
                }}
              />
            ))}
            {timedEvents.map((evt) => {
              const style = getEventStyle(evt);
              return (
                <button
                  key={evt.id}
                  onClick={(e) => {
                    e.stopPropagation();
                    onEventClick(evt);
                  }}
                  className="absolute left-1 right-4 rounded-lg px-3 py-1.5 text-white font-medium overflow-hidden hover:opacity-90 z-10 shadow-sm"
                  style={{
                    ...style,
                    backgroundColor:
                      calColorMap.get(evt.calendar_id) || "#3B82F6",
                  }}
                >
                  <div className="text-sm truncate">{evt.title}</div>
                  <div className="text-xs opacity-80">
                    {format(parseISO(evt.start_time), "h:mm a")} -{" "}
                    {format(parseISO(evt.end_time), "h:mm a")}
                  </div>
                  {evt.location && (
                    <div className="text-xs opacity-70 truncate">{evt.location}</div>
                  )}
                </button>
              );
            })}
          </div>
        </div>
      </div>
    </div>
  );
}
