"use client";

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

const VISIBLE_START = 7;
const VISIBLE_END = 22;
const HOUR_HEIGHT = 64; // px per hour
const HOURS = Array.from({ length: VISIBLE_END - VISIBLE_START }, (_, i) => i + VISIBLE_START);

const DE_WEEKDAYS_SHORT = ["Mo", "Di", "Mi", "Do", "Fr", "Sa", "So"];

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

export function WeekView({
  currentDate,
  items,
  onTimeClick,
  onEventClick,
}: WeekViewProps) {
  const days = getWeekDays(currentDate);
  const scrollRef = useRef<HTMLDivElement>(null);

  // Scroll to current time on mount
  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);
  }, []);

  function getAllDayItems(date: Date) {
    return items.filter((item) => item.allDay && isSameDay(item.start, date));
  }

  function getTimedItems(date: Date) {
    return items.filter((item) => !item.allDay && isSameDay(item.start, date));
  }

  // Compute position and height for a timed event
  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(24, (durationMin / 60) * HOUR_HEIGHT);

    return {
      top,
      height,
      left: 2,
      right: 2,
      position: "absolute",
    };
  }

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

  return (
    <div className="overflow-x-auto">
    <div className="flex min-w-[640px] flex-col">
      {/* Day header row */}
      <div className="grid grid-cols-[52px_repeat(7,1fr)] border-b border-white/[0.07]">
        <div />
        {days.map((date, i) => {
          const today = isToday(date);
          // getDay(): 0=Sun, 1=Mon...6=Sat => convert to Mon-start index
          const dayIdx = date.getDay() === 0 ? 6 : date.getDay() - 1;
          return (
            <div key={i} className="border-l border-white/[0.07] py-2 text-center">
              <span className="text-[10px] font-semibold uppercase tracking-widest text-white/30">
                {DE_WEEKDAYS_SHORT[dayIdx]}
              </span>
              <div className="mt-0.5 flex items-center justify-center">
                <span
                  className={cn(
                    "flex h-7 w-7 items-center justify-center rounded-full text-[14px] font-bold",
                    today
                      ? "bg-violet-500 text-white"
                      : "text-white/60"
                  )}
                >
                  {date.getDate()}
                </span>
              </div>
            </div>
          );
        })}
      </div>

      {/* All-day row */}
      <div className="grid grid-cols-[52px_repeat(7,1fr)] border-b border-white/[0.07]">
        <div className="flex items-center justify-end pr-2 py-1">
          <span className="text-[9px] text-white/20 uppercase tracking-widest">All Day</span>
        </div>
        {days.map((date, i) => {
          const allDayItems = getAllDayItems(date).slice(0, 2);
          return (
            <div key={i} className="min-h-[28px] border-l border-white/[0.07] p-0.5 space-y-0.5">
              {allDayItems.map((item) => (
                <button
                  key={item.id}
                  onClick={() => onEventClick(item)}
                  className="flex w-full items-center gap-1 truncate rounded-md px-1.5 py-0.5 text-[10px] font-semibold"
                  style={{
                    backgroundColor: (item.color || "#8b5cf6") + "20",
                    color: item.color || "#8b5cf6",
                  }}
                >
                  {item.type === "task" && <CheckSquare className="h-2.5 w-2.5 shrink-0" />}
                  <span className="truncate">{item.title}</span>
                </button>
              ))}
            </div>
          );
        })}
      </div>

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

          {/* Day columns */}
          {days.map((date, dayIdx) => {
            const timedItems = getTimedItems(date);
            const todayCol = isToday(date);

            return (
              <div
                key={dayIdx}
                className="relative border-l border-white/[0.07]"
                style={{ height: (VISIBLE_END - VISIBLE_START) * HOUR_HEIGHT }}
              >
                {/* Hour divider lines */}
                {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(date);
                      d.setHours(hour, 0, 0, 0);
                      onTimeClick(d);
                    }}
                  />
                ))}

                {/* Events */}
                {timedItems.map((item) => {
                  const style = getEventStyle(item);
                  const startHour = item.start.getHours();
                  const startMin = item.start.getMinutes();
                  if (startHour < VISIBLE_START || startHour >= VISIBLE_END) return null;

                  return (
                    <button
                      key={item.id}
                      onClick={(e) => {
                        e.stopPropagation();
                        onEventClick(item);
                      }}
                      className="absolute rounded-lg px-2 py-1 text-[11px] font-semibold overflow-hidden cursor-pointer z-10 text-left"
                      style={{
                        ...style,
                        backgroundColor: (item.color || "#8b5cf6") + "20",
                        borderLeft: `2px solid ${item.color || "#8b5cf6"}`,
                        color: item.color || "#8b5cf6",
                      }}
                    >
                      <span className="truncate block">
                        {String(startHour).padStart(2, "0")}:{String(startMin).padStart(2, "0")} {item.title}
                      </span>
                    </button>
                  );
                })}

                {/* Current time indicator */}
                {todayCol && 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 w-2 rounded-full bg-red-500 -ml-1 shrink-0" />
                      <div className="flex-1 h-px bg-red-500" />
                    </div>
                  </div>
                )}
              </div>
            );
          })}
        </div>
      </div>
    </div>
    </div>
  );
}
