import { Card, CardContent, CardHeader, CardTitle } from "../ui/card";
import { Badge } from "../ui/badge";
import { Calendar as CalendarIcon, Clock, MapPin, Users } from "lucide-react";
import { useState } from "react";
import { Calendar } from "../ui/calendar";
import { ko } from "date-fns/locale";

interface Event {
  time: string;
  title: string;
  location: string;
  attendees: number;
  priority: "high" | "medium" | "low";
}

interface Schedule {
  date: string;
  events: Event[];
}

export function ScheduleCalendarWidget() {
  const today = new Date();
  const [selectedDate, setSelectedDate] = useState<Date | undefined>(today);
  
  // Mock 데이터 (실제로는 API에서 가져옴)
  const schedules: Schedule[] = [
    {
      date: today.toISOString().split('T')[0],
      events: [
        { time: "09:30", title: "일일 운영회의", location: "회의실 B", attendees: 6, priority: "high" },
        { time: "11:00", title: "고객 컴플레인 대응", location: "CS실", attendees: 4, priority: "high" },
        { time: "14:00", title: "생산성 향상 간담회", location: "생산부", attendees: 15, priority: "medium" },
        { time: "16:00", title: "월말 실적 검토", location: "경영지원팀", attendees: 8, priority: "medium" }
      ]
    },
    {
      date: new Date(today.getTime() + 1 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
      events: [
        { time: "10:00", title: "신규 프로젝트 킥오프", location: "본사 대회의실", attendees: 12, priority: "high" },
        { time: "15:00", title: "부서별 주간회의", location: "각 부서", attendees: 8, priority: "medium" }
      ]
    },
    {
      date: new Date(today.getTime() + 3 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
      events: [
        { time: "13:00", title: "협력사 미팅", location: "회의실 A", attendees: 5, priority: "medium" }
      ]
    },
    {
      date: new Date(today.getTime() + 7 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
      events: [
        { time: "09:00", title: "월간 경영회의", location: "임원회의실", attendees: 10, priority: "high" },
        { time: "14:00", title: "품질 개선 워크샵", location: "교육장", attendees: 20, priority: "medium" }
      ]
    }
  ];
  
  // 선택된 날짜의 일정 찾기
  const selectedDateStr = selectedDate?.toISOString().split('T')[0];
  const selectedEvents = schedules.find((s: Schedule) => s.date === selectedDateStr);

  // 일정이 있는 날짜 체크
  const hasEventsOnDate = (date: Date) => {
    const dateStr = date.toISOString().split('T')[0];
    return schedules.some((s: Schedule) => s.date === dateStr);
  };

  return (
    <Card className="h-full">
      <CardHeader className="pb-3">
        <CardTitle className="flex items-center gap-2">
          <CalendarIcon className="h-5 w-5 text-orange-600" />
          일정 캘린더
        </CardTitle>
      </CardHeader>
      <CardContent>
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          {/* 캘린더 */}
          <div className="flex flex-col items-center justify-center p-6">
            <Calendar
              mode="single"
              selected={selectedDate}
              onSelect={setSelectedDate}
              locale={ko}
              className="rounded-md border dark:border-gray-700 p-3"
              classNames={{
                caption: "pt-3 pb-2",
                caption_label: "font-medium",
              }}
              modifiers={{
                hasEvents: (date) => hasEventsOnDate(date)
              }}
              modifiersStyles={{
                hasEvents: {
                  fontWeight: 'bold',
                  backgroundColor: 'hsl(var(--primary) / 0.15)',
                  color: 'hsl(var(--primary))',
                  borderRadius: '0.375rem'
                }
              }}
            />
            <div className="mt-4 text-xs text-muted-foreground flex items-center gap-2">
              <div className="flex items-center gap-1">
                <div className="w-3 h-3 rounded-full bg-primary/15 border border-primary dark:bg-primary/20"></div>
                <span>일정 있음</span>
              </div>
            </div>
          </div>

          {/* 선택된 날짜의 일정 목록 */}
          <div className="flex flex-col">
            <div className="mb-3 pb-2 border-b dark:border-gray-700">
              <h3 className="font-semibold">
                {selectedDate ? (
                  <>
                    {selectedDate.getMonth() + 1}월 {selectedDate.getDate()}일{' '}
                    {['일요일', '월요일', '화요일', '수요일', '목요일', '금요일', '토요일'][selectedDate.getDay()]}
                  </>
                ) : (
                  '날짜를 선택하세요'
                )}
              </h3>
              {selectedEvents && (
                <p className="text-xs text-muted-foreground mt-1">
                  총 {selectedEvents.events.length}개의 일정
                </p>
              )}
            </div>

            {selectedEvents && selectedEvents.events.length > 0 ? (
              <div className="space-y-3 overflow-y-auto max-h-96 pr-2">
                {selectedEvents.events.map((event: Event, index: number) => (
                  <div 
                    key={index} 
                    className="p-3 border border-border rounded-lg hover:shadow-md transition-all hover:border-primary/50 dark:bg-gray-800/30 dark:hover:bg-gray-800/50 dark:border-gray-700 dark:hover:border-primary/60"
                  >
                    <div className="flex items-start justify-between gap-2 mb-2">
                      <div className="flex-1 min-w-0">
                        <div className="font-semibold text-sm text-foreground mb-1 truncate">
                          {event.title}
                        </div>
                        <div className="flex flex-wrap gap-2 text-xs text-muted-foreground">
                          <div className="flex items-center gap-1">
                            <Clock className="h-3 w-3" />
                            {event.time}
                          </div>
                          <div className="flex items-center gap-1">
                            <MapPin className="h-3 w-3" />
                            {event.location}
                          </div>
                          <div className="flex items-center gap-1">
                            <Users className="h-3 w-3" />
                            {event.attendees}명
                          </div>
                        </div>
                      </div>
                      <Badge 
                        variant={
                          event.priority === "high" ? "destructive" :
                          event.priority === "medium" ? "default" : "secondary"
                        }
                        className="text-xs whitespace-nowrap"
                      >
                        {event.priority === "high" ? "높음" :
                         event.priority === "medium" ? "보통" : "낮음"}
                      </Badge>
                    </div>
                  </div>
                ))}
              </div>
            ) : (
              <div className="text-center py-8 text-muted-foreground flex-1 flex flex-col items-center justify-center">
                <CalendarIcon className="h-10 w-10 mx-auto mb-2 opacity-50" />
                <p className="text-sm">이 날짜에 예정된 일정이 없습니다.</p>
              </div>
            )}
          </div>
        </div>
      </CardContent>
    </Card>
  );
}