'use client';

import { useMemo } from 'react';
import { cn } from '@/components/ui/utils';
import { formatCalendarDate, checkIsToday } from './utils';
import { EVENT_COLORS } from './types';
import type { DayTimeViewProps, ScheduleEvent } from './types';
import { format, parseISO } from 'date-fns';
import { ko } from 'date-fns/locale';

/**
 * 일간 시간축 뷰 (day-time)
 *
 * 좌측에 시간 라벨, 오른쪽에 해당 날짜의 이벤트 블록 표시
 * startTime이 없는 이벤트는 all-day 영역에 표시
 */
export function DayTimeView({
  currentDate,
  events,
  timeRange = { start: 1, end: 12 },
  onDateClick,
  onEventClick,
}: DayTimeViewProps) {
  const today = checkIsToday(currentDate);
  const dayStr = formatCalendarDate(currentDate, 'yyyy-MM-dd');
  const weekdayLabel = format(currentDate, 'EEEE', { locale: ko });

  // 시간 슬롯 생성
  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 { allDayEvents, timedEvents } = useMemo(() => {
    const allDay: ScheduleEvent[] = [];
    const timed: ScheduleEvent[] = [];

    events.forEach((event) => {
      const eventStart = parseISO(event.startDate);
      const eventEnd = parseISO(event.endDate);
      const current = parseISO(dayStr);

      if (current >= eventStart && current <= eventEnd) {
        if (event.startTime) {
          timed.push(event);
        } else {
          allDay.push(event);
        }
      }
    });

    return { allDayEvents: allDay, timedEvents: timed };
  }, [events, dayStr]);

  // 시간 문자열에서 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-[300px]">
        {/* 헤더: 시간라벨컬럼 + 날짜 */}
        <div className="grid grid-cols-[60px_1fr] border-b">
          <div className="border-r bg-muted/30" />
          <div
            className={cn(
              'text-center py-2 cursor-pointer transition-colors',
              today && 'bg-primary/5',
            )}
            onClick={() => onDateClick(currentDate)}
          >
            <div className={cn(
              'text-xs text-muted-foreground',
              today && 'text-primary font-semibold',
            )}>
              {weekdayLabel}
            </div>
            <div className={cn(
              'text-sm font-medium',
              today && 'text-primary',
            )}>
              {format(currentDate, 'd')}
            </div>
          </div>
        </div>

        {/* All-day 영역 */}
        {allDayEvents.length > 0 && (
          <div className="grid grid-cols-[60px_1fr] border-b">
            <div className="border-r bg-muted/30 flex items-center justify-center">
              <span className="text-[10px] text-muted-foreground">종일</span>
            </div>
            <div className="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) => {
          const slotEvents = timedEvents.filter((event) => {
            if (!event.startTime) return false;
            return getHourFromTime(event.startTime) === slot.hour;
          });

          return (
            <div
              key={slot.hour}
              className="grid grid-cols-[60px_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>
              {/* 이벤트 셀 */}
              <div className={cn(
                '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>
  );
}
