"use client";

import { useEffect, useRef } from "react";
import { isSameDay, isToday } from "@/lib/calendar-utils";
import { cn } from "@/lib/utils";
import type { CalendarItem } from "@/hooks/use-events";
import { CheckSquare, Users } from "lucide-react";

const VISIBLE_START = 7;
const VISIBLE_END = 22;
const HOUR_HEIGHT = 72; // px per hour (larger than week view for detail)
const HOURS = Array.from({ length: VISIBLE_END - VISIBLE_START }, (_, i) => i + VISIBLE_START);

interface DayViewProps {
  currentDate: Date;
  items: CalendarItem[];
  onTimeClick: (date: Date) => void;
  onEventClick: (item: CalendarItem) => void;
}

function formatTimeRange(item: CalendarItem): string {
  const sh = String(item.start.getHours()).padStart(2, "0");
  const sm = String(item.start.getMinutes()).padStart(2, "0");
  if (!item.end) return `${sh}:${sm}`;
  const eh = String(item.end.getHours()).padStart(2, "0");
  const em = String(item.end.getMinutes()).padStart(2, "0");
  return `${sh}:${sm} – ${eh}:${em}`;
}

// Simple overlap detection: returns groups of overlapping events
function groupOverlappingEvents(events: CalendarItem[]): CalendarItem[][] {
  if (events.length === 0) return [];

  const sorted = [...events].sort((a, b) => a.start.getTime() - b.start.getTime());
  const groups: CalendarItem[][] = [];
  let currentGroup: CalendarItem[] = [sorted[0]];
  let groupEnd = sorted[0].end ?? new Date(sorted[0].start.getTime() + 3600000);

  for (let i = 1; i < sorted.length; i++) {
    const item = sorted[i];
    const itemEnd = item.end ?? new Date(item.start.getTime() + 3600000);
    if (item.start < groupEnd) {
      currentGroup.push(item);
      if (itemEnd > groupEnd) groupEnd = itemEnd;
    } else {
      groups.push(currentGroup);
      currentGroup = [item];
      groupEnd = itemEnd;
    }
  }
  groups.push(currentGroup);
  return groups;
}

export function DayView({
  currentDate,
  items,
  onTimeClick,
  onEventClick,
}: DayViewProps) {
  const scrollRef = useRef<HTMLDivElement>(null);
  const today = isToday(currentDate);

  useEffect(() => {
    if (!scrollRef.current) return;
    const now = new Date();
    const clampedHour = Math.max(VISIBLE_START, Math.min(VISIBLE_END, now.getHours()));
    const scrollTop = (clampedHour - VISIBLE_START) * HOUR_HEIGHT - 64;
    scrollRef.current.scrollTop = Math.max(0, scrollTop);
  }, []);

  const allDayItems = items.filter((item) => item.allDay && isSameDay(item.start, currentDate));
  const timedItems = items.filter((item) => !item.allDay && isSameDay(item.start, currentDate));
  const visibleTimedItems = timedItems.filter(
    (item) => item.start.getHours() >= VISIBLE_START && item.start.getHours() < VISIBLE_END
  );

  const overlapGroups = groupOverlappingEvents(visibleTimedItems);

  // Build a map from item.id -> { index, total } within its group
  const layoutMap = new Map<string, { index: number; total: number }>();
  for (const group of overlapGroups) {
    group.forEach((item, idx) => {
      layoutMap.set(item.id, { index: idx, total: group.length });
    });
  }

  function getEventStyle(item: CalendarItem): React.CSSProperties {
    const startHour = item.start.getHours();
    const startMin = item.start.getMinutes();
    const top = ((startHour - VISIBLE_START) + startMin / 60) * HOUR_HEIGHT;

    let durationMin = 60;
    if (item.end) {
      durationMin = Math.max(15, (item.end.getTime() - item.start.getTime()) / 60000);
    }
    const height = Math.max(28, (durationMin / 60) * HOUR_HEIGHT);

    const layout = layoutMap.get(item.id);
    const total = layout?.total ?? 1;
    const idx = layout?.index ?? 0;

    const colWidth = total > 1 ? `calc(${100 / total}% - 4px)` : "calc(100% - 4px)";
    const left = total > 1 ? `calc(${(idx / total) * 100}% + 2px)` : "2px";

    return {
      top,
      height,
      left,
      width: colWidth,
      position: "absolute",
    };
  }

  const now = new Date();
  const nowTop = ((now.getHours() - VISIBLE_START) + now.getMinutes() / 60) * HOUR_HEIGHT;

  return (
    <div className="flex flex-col">
      {/* All-day events strip */}
      {allDayItems.length > 0 && (
        <div className="border-b border-white/[0.07] px-4 py-2">
          <p className="mb-1.5 text-[10px] font-semibold uppercase tracking-widest text-white/20">
            Ganztägig
          </p>
          <div className="flex flex-wrap gap-2">
            {allDayItems.map((item) => (
              <button
                key={item.id}
                onClick={() => onEventClick(item)}
                className="flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-[12px] font-semibold transition-opacity hover:opacity-80"
                style={{
                  backgroundColor: (item.color || "#8b5cf6") + "20",
                  color: item.color || "#8b5cf6",
                  border: `1px solid ${item.color || "#8b5cf6"}30`,
                }}
              >
                {item.type === "task" && <CheckSquare className="h-3 w-3 shrink-0" />}
                {item.title}
              </button>
            ))}
          </div>
        </div>
      )}

      {/* Time grid */}
      <div ref={scrollRef} className="overflow-y-auto max-h-[calc(100vh-340px)]">
        <div
          className="grid grid-cols-[52px_1fr]"
          style={{ height: (VISIBLE_END - VISIBLE_START) * HOUR_HEIGHT }}
        >
          {/* Time labels */}
          <div className="relative border-r border-white/[0.07]">
            {HOURS.map((hour) => (
              <div
                key={hour}
                className="absolute right-2 text-[11px] text-white/20 select-none"
                style={{ top: (hour - VISIBLE_START) * HOUR_HEIGHT - 8 }}
              >
                {String(hour).padStart(2, "0")}
              </div>
            ))}
          </div>

          {/* Main column */}
          <div
            className="relative"
            style={{ height: (VISIBLE_END - VISIBLE_START) * HOUR_HEIGHT }}
          >
            {/* Hour divider lines + click zones */}
            {HOURS.map((hour) => (
              <div
                key={hour}
                className="absolute left-0 right-0 border-t border-white/[0.04] cursor-pointer hover:bg-white/[0.03] transition-colors"
                style={{ top: (hour - VISIBLE_START) * HOUR_HEIGHT, height: HOUR_HEIGHT }}
                onClick={() => {
                  const d = new Date(currentDate);
                  d.setHours(hour, 0, 0, 0);
                  onTimeClick(d);
                }}
              />
            ))}

            {/* Events */}
            {visibleTimedItems.map((item) => {
              const style = getEventStyle(item);
              const timeRange = formatTimeRange(item);

              return (
                <button
                  key={item.id}
                  onClick={(e) => {
                    e.stopPropagation();
                    onEventClick(item);
                  }}
                  className={cn(
                    "absolute rounded-xl px-3 py-2 text-left overflow-hidden cursor-pointer z-10 transition-opacity hover:opacity-90"
                  )}
                  style={{
                    ...style,
                    backgroundColor: (item.color || "#8b5cf6") + "18",
                    borderLeft: `3px solid ${item.color || "#8b5cf6"}`,
                    color: item.color || "#8b5cf6",
                  }}
                >
                  <p className="text-[11px] font-medium opacity-75">{timeRange}</p>
                  <p className="text-[13px] font-semibold leading-tight truncate mt-0.5">
                    {item.title}
                  </p>
                  {/* description */}
                  {"description" in item && (item as { description?: string }).description && (
                    <p className="text-[11px] text-white/50 mt-0.5 truncate">
                      {(item as { description?: string }).description}
                    </p>
                  )}
                  {/* participant count */}
                  {(item.participantCount ?? 0) > 0 && (
                    <p className="mt-0.5 flex items-center gap-1 text-[10px] opacity-60">
                      <Users className="h-2.5 w-2.5" />
                      {item.participantCount}
                    </p>
                  )}
                </button>
              );
            })}

            {/* Current time indicator */}
            {today && nowTop >= 0 && nowTop <= (VISIBLE_END - VISIBLE_START) * HOUR_HEIGHT && (
              <div
                className="absolute left-0 right-0 z-20 pointer-events-none"
                style={{ top: nowTop }}
              >
                <div className="relative flex items-center">
                  <div className="h-2.5 w-2.5 rounded-full bg-red-500 -ml-1.5 shrink-0" />
                  <div className="flex-1 h-px bg-red-500" />
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
