'use client';

import { useMemo } from 'react';
import { cn } from '@/components/ui/utils';
import { getWeekDays, getWeekdayHeaders, formatCalendarDate, checkIsToday, isSameDate } from './utils';
import { EVENT_COLORS } from './types';
import type { WeekTimeViewProps, ScheduleEvent } from './types';
import { format, parseISO } from 'date-fns';

/**
 * 시간축 주간 뷰 (week-time)
 *
 * 좌측에 시간 라벨, 상단에 요일+날짜, 시간 슬롯에 이벤트 블록 표시
 * startTime이 없는 이벤트는 all-day 영역에 표시
 */
export function WeekTimeView({
  currentDate,
  events,
  selectedDate,
  weekStartsOn,
  timeRange = { start: 1, end: 12 },
  onDateClick,
  onEventClick,
}: WeekTimeViewProps) {
  const weekDays = useMemo(() => getWeekDays(currentDate, weekStartsOn), [currentDate, weekStartsOn]);
  const weekdayHeaders = useMemo(() => getWeekdayHeaders(weekStartsOn), [weekStartsOn]);

  // 시간 슬롯 생성 (AM 시간대)
  const timeSlots = useMemo(() => {
    const slots: { hour: number; label: string }[] = [];
    for (let h = timeRange.start; h <= timeRange.end; h++) {
      slots.push({
        hour: h,
        label: `AM ${h}시`,
      });
    }
    return slots;
  }, [timeRange]);

  // 이벤트를 날짜별로 분류
  const eventsByDate = useMemo(() => {
    const map = new Map<string, { allDay: ScheduleEvent[]; timed: ScheduleEvent[] }>();

    weekDays.forEach((day) => {
      const dateStr = formatCalendarDate(day, 'yyyy-MM-dd');
      map.set(dateStr, { allDay: [], timed: [] });
    });

    events.forEach((event) => {
      const eventStartDate = parseISO(event.startDate);
      const eventEndDate = parseISO(event.endDate);

      weekDays.forEach((day) => {
        const dateStr = formatCalendarDate(day, 'yyyy-MM-dd');
        // 이벤트가 이 날짜를 포함하는지 확인
        if (day >= eventStartDate && day <= eventEndDate) {
          const bucket = map.get(dateStr);
          if (bucket) {
            if (event.startTime) {
              bucket.timed.push(event);
            } else {
              bucket.allDay.push(event);
            }
          }
        }
      });
    });

    return map;
  }, [events, weekDays]);

  // all-day 이벤트가 있는지 확인
  const hasAllDayEvents = useMemo(() => {
    for (const [, bucket] of eventsByDate) {
      if (bucket.allDay.length > 0) return true;
    }
    return false;
  }, [eventsByDate]);

  // 시간 문자열에서 hour 추출
  const getHourFromTime = (time: string): number => {
    const [hours] = time.split(':').map(Number);
    return hours;
  };

  // 이벤트 색상 클래스
  const getEventColorClasses = (event: ScheduleEvent): string => {
    const color = event.color || 'blue';
    return EVENT_COLORS[color] || EVENT_COLORS.blue;
  };

  return (
    <div className="overflow-x-auto">
      <div className="min-w-[700px]">
        {/* 헤더: 시간라벨컬럼 + 요일/날짜 */}
        <div className="grid grid-cols-[60px_repeat(7,1fr)] border-b">
          {/* 빈 코너셀 */}
          <div className="border-r bg-muted/30" />
          {/* 요일 + 날짜 */}
          {weekDays.map((day, i) => {
            const today = checkIsToday(day);
            const selected = isSameDate(selectedDate, day);
            return (
              <div
                key={i}
                className={cn(
                  'text-center py-2 border-r last:border-r-0 cursor-pointer transition-colors',
                  today && 'bg-primary/5',
                  selected && 'bg-primary/10',
                )}
                onClick={() => onDateClick(day)}
              >
                <div className={cn(
                  'text-xs text-muted-foreground',
                  today && 'text-primary font-semibold',
                )}>
                  {weekdayHeaders[i]}
                </div>
                <div className={cn(
                  'text-sm font-medium',
                  today && 'text-primary',
                )}>
                  {format(day, 'd')}
                </div>
              </div>
            );
          })}
        </div>

        {/* All-day 영역 */}
        {hasAllDayEvents && (
          <div className="grid grid-cols-[60px_repeat(7,1fr)] border-b">
            <div className="border-r bg-muted/30 flex items-center justify-center">
              <span className="text-[10px] text-muted-foreground">종일</span>
            </div>
            {weekDays.map((day, i) => {
              const dateStr = formatCalendarDate(day, 'yyyy-MM-dd');
              const allDayEvents = eventsByDate.get(dateStr)?.allDay || [];
              return (
                <div
                  key={i}
                  className="border-r last:border-r-0 p-0.5 min-h-[28px]"
                >
                  {allDayEvents.map((event) => (
                    <div
                      key={event.id}
                      className={cn(
                        'text-[10px] px-1 py-0.5 rounded truncate cursor-pointer hover:opacity-80 mb-0.5',
                        getEventColorClasses(event),
                      )}
                      title={event.title}
                      onClick={() => onEventClick(event)}
                    >
                      {event.title}
                    </div>
                  ))}
                </div>
              );
            })}
          </div>
        )}

        {/* 시간 그리드 */}
        {timeSlots.map((slot) => (
          <div
            key={slot.hour}
            className="grid grid-cols-[60px_repeat(7,1fr)] border-b last:border-b-0"
          >
            {/* 시간 라벨 */}
            <div className="border-r bg-muted/30 flex items-start justify-center pt-1">
              <span className="text-[10px] text-muted-foreground whitespace-nowrap">
                {slot.label}
              </span>
            </div>
            {/* 요일별 셀 */}
            {weekDays.map((day, i) => {
              const dateStr = formatCalendarDate(day, 'yyyy-MM-dd');
              const timedEvents = eventsByDate.get(dateStr)?.timed || [];
              const slotEvents = timedEvents.filter((event) => {
                if (!event.startTime) return false;
                const eventHour = getHourFromTime(event.startTime);
                return eventHour === slot.hour;
              });

              const today = checkIsToday(day);

              return (
                <div
                  key={i}
                  className={cn(
                    'border-r last:border-r-0 p-0.5 min-h-[40px] relative',
                    today && 'bg-primary/[0.02]',
                  )}
                >
                  {slotEvents.map((event) => (
                    <div
                      key={event.id}
                      className={cn(
                        'text-[10px] px-1.5 py-1 rounded cursor-pointer hover:opacity-80 mb-0.5 leading-tight',
                        getEventColorClasses(event),
                      )}
                      title={event.title}
                      onClick={() => onEventClick(event)}
                    >
                      <span className="line-clamp-2">{event.title}</span>
                    </div>
                  ))}
                </div>
              );
            })}
          </div>
        ))}
      </div>
    </div>
  );
}
