'use client';

import { useState, useMemo } from 'react';
import { useRouter } from 'next/navigation';
import { Card, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Plus, ExternalLink } from 'lucide-react';
import { ScheduleCalendar } from '@/components/common/ScheduleCalendar';
import type { ScheduleEvent } from '@/components/common/ScheduleCalendar/types';
import type {
  CalendarScheduleItem,
  CalendarViewType,
  CalendarDeptFilterType,
  CalendarTaskFilterType,
  TodayIssueListItem,
  TodayIssueListBadgeType,
} from '../types';

interface CalendarSectionProps {
  schedules: CalendarScheduleItem[];
  issues?: TodayIssueListItem[];
  onScheduleClick?: (schedule: CalendarScheduleItem) => void;
  onScheduleEdit?: (schedule: CalendarScheduleItem) => void;
}

// 일정 타입별 색상
const SCHEDULE_TYPE_COLORS: Record<string, string> = {
  schedule: 'blue',
  order: 'green',
  construction: 'purple',
  issue: 'red',
  other: 'gray',
};

// 이슈 뱃지별 색상
const ISSUE_BADGE_COLORS: Record<TodayIssueListBadgeType, string> = {
  '수주 성공': 'bg-blue-100 text-blue-700',
  '추심 이슈': 'bg-purple-100 text-purple-700',
  '적정 재고': 'bg-orange-100 text-orange-700',
  '지출예상내역서': 'bg-green-100 text-green-700',
  '세금 신고': 'bg-red-100 text-red-700',
  '결재 요청': 'bg-yellow-100 text-yellow-700',
  '신규거래처': 'bg-emerald-100 text-emerald-700',
  '기타': 'bg-gray-100 text-gray-700',
};

// 부서 필터 옵션
const DEPT_FILTER_OPTIONS: { value: CalendarDeptFilterType; label: string }[] = [
  { value: 'all', label: '전체' },
  { value: 'department', label: '부' },
  { value: 'personal', label: '개인' },
];

// 업무 필터 옵션 (이슈 추가)
type ExtendedTaskFilterType = CalendarTaskFilterType | 'issue';
const TASK_FILTER_OPTIONS: { value: ExtendedTaskFilterType; label: string }[] = [
  { value: 'all', label: '전체' },
  { value: 'schedule', label: '일정' },
  { value: 'order', label: '발주' },
  { value: 'construction', label: '시공' },
  { value: 'issue', label: '이슈' },
];

export function CalendarSection({
  schedules,
  issues = [],
  onScheduleClick,
  onScheduleEdit,
}: CalendarSectionProps) {
  const router = useRouter();
  const [selectedDate, setSelectedDate] = useState<Date | null>(new Date());
  const [currentDate, setCurrentDate] = useState(new Date());
  const [viewType, setViewType] = useState<CalendarViewType>('month');
  const [deptFilter, setDeptFilter] = useState<CalendarDeptFilterType>('all');
  const [taskFilter, setTaskFilter] = useState<ExtendedTaskFilterType>('all');

  // 날짜가 있는 이슈만 필터링
  const issuesWithDate = useMemo(() => {
    return issues.filter((issue) => issue.date);
  }, [issues]);

  // 필터링된 스케줄
  const filteredSchedules = useMemo(() => {
    // 이슈 필터일 경우 스케줄 제외
    if (taskFilter === 'issue') {
      return [];
    }

    let result = schedules;

    // 업무 필터
    if (taskFilter !== 'all') {
      result = result.filter((s) => s.type === taskFilter);
    }

    // 부서 필터 (실제 구현시 부서/개인 로직 추가 필요)
    // 현재는 기본 구현만

    return result;
  }, [schedules, taskFilter, deptFilter]);

  // 필터링된 이슈
  const filteredIssues = useMemo(() => {
    // 이슈 필터가 아니고 all도 아닌 경우 이슈 제외
    if (taskFilter !== 'all' && taskFilter !== 'issue') {
      return [];
    }
    return issuesWithDate;
  }, [issuesWithDate, taskFilter]);

  // ScheduleCalendar용 이벤트 변환 (스케줄 + 이슈 통합)
  const calendarEvents: ScheduleEvent[] = useMemo(() => {
    const scheduleEvents = filteredSchedules.map((schedule) => ({
      id: schedule.id,
      // 기획서: [부서명] 제목 형식
      title: schedule.department ? `[${schedule.department}] ${schedule.title}` : schedule.title,
      startDate: schedule.startDate,
      endDate: schedule.endDate,
      color: SCHEDULE_TYPE_COLORS[schedule.type] || 'gray',
      data: { ...schedule, _type: 'schedule' as const },
    }));

    const issueEvents = filteredIssues.map((issue) => ({
      id: issue.id,
      title: `[${issue.badge}] ${issue.content}`,
      startDate: issue.date!,
      endDate: issue.date!,
      color: 'red',
      data: { ...issue, _type: 'issue' as const },
    }));

    return [...scheduleEvents, ...issueEvents];
  }, [filteredSchedules, filteredIssues]);

  // 선택된 날짜의 일정 + 이슈 목록
  const selectedDateItems = useMemo(() => {
    if (!selectedDate) return { schedules: [], issues: [] };
    // 로컬 타임존 기준으로 날짜 문자열 생성 (UTC 변환 방지)
    const year = selectedDate.getFullYear();
    const month = String(selectedDate.getMonth() + 1).padStart(2, '0');
    const day = String(selectedDate.getDate()).padStart(2, '0');
    const dateStr = `${year}-${month}-${day}`;

    const dateSchedules = filteredSchedules.filter((schedule) => {
      return schedule.startDate <= dateStr && schedule.endDate >= dateStr;
    });

    const dateIssues = filteredIssues.filter((issue) => issue.date === dateStr);

    return { schedules: dateSchedules, issues: dateIssues };
  }, [selectedDate, filteredSchedules, filteredIssues]);

  // 총 건수 계산
  const totalItemCount = selectedDateItems.schedules.length + selectedDateItems.issues.length;

  // 날짜 포맷 (기획서: "1월 6일 화요일")
  const formatSelectedDate = (date: Date) => {
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const dayNames = ['일요일', '월요일', '화요일', '수요일', '목요일', '금요일', '토요일'];
    const dayName = dayNames[date.getDay()];
    return `${month}월 ${day}일 ${dayName}`;
  };

  // 일정 상세 정보 포맷 (기획서: 부서명 | 날짜 | 시간)
  const formatScheduleDetail = (schedule: CalendarScheduleItem) => {
    const parts: string[] = [];

    // 부서명 또는 담당자명
    if (schedule.department) {
      parts.push(schedule.department);
    } else if (schedule.personName) {
      parts.push(schedule.personName);
    }

    // 날짜 (여러 날인 경우)
    if (schedule.startDate !== schedule.endDate) {
      parts.push(`${schedule.startDate}~${schedule.endDate}`);
    }

    // 시간
    if (schedule.startTime && schedule.endTime) {
      parts.push(`${schedule.startTime} ~ ${schedule.endTime}`);
    } else if (schedule.startTime) {
      parts.push(schedule.startTime);
    }

    return parts.join(' | ');
  };

  const handleDateClick = (date: Date) => {
    setSelectedDate(date);
  };

  const handleEventClick = (event: ScheduleEvent) => {
    const schedule = event.data as CalendarScheduleItem;
    onScheduleClick?.(schedule);
  };

  const handleMonthChange = (date: Date) => {
    setCurrentDate(date);
  };

  return (
    <Card>
      <CardContent className="p-6">
        {/* 섹션 헤더: 타이틀 + 필터들 */}
        <div className="flex items-center justify-between mb-4">
          <h3 className="text-lg font-semibold">캘린더</h3>
          <div className="flex items-center gap-2">
          {/* 부서 필터 */}
          <Select
            value={deptFilter}
            onValueChange={(value) => setDeptFilter(value as CalendarDeptFilterType)}
          >
            <SelectTrigger className="w-[80px] h-8">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              {DEPT_FILTER_OPTIONS.map((option) => (
                <SelectItem key={option.value} value={option.value}>
                  {option.label}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>

          {/* 업무 필터 */}
          <Select
            value={taskFilter}
            onValueChange={(value) => setTaskFilter(value as CalendarTaskFilterType)}
          >
            <SelectTrigger className="w-[80px] h-8">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              {TASK_FILTER_OPTIONS.map((option) => (
                <SelectItem key={option.value} value={option.value}>
                  {option.label}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
          </div>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          {/* 캘린더 영역 */}
          <div>
            <ScheduleCalendar
              events={calendarEvents}
              currentDate={currentDate}
              selectedDate={selectedDate}
              onDateClick={handleDateClick}
              onEventClick={handleEventClick}
              onMonthChange={handleMonthChange}
              maxEventsPerDay={4}
              weekStartsOn={1} // 월요일 시작 (기획서)
              className="[&_.weekend]:bg-yellow-50"
            />
          </div>

          {/* 선택된 날짜 일정 + 이슈 목록 */}
          <div className="border rounded-lg p-4">
            {/* 헤더: 날짜 + 일정등록 버튼 */}
            <div className="flex items-center justify-between mb-2">
              <h4 className="text-lg font-semibold">
                {selectedDate ? formatSelectedDate(selectedDate) : '날짜를 선택하세요'}
              </h4>
              {/* 일정등록 버튼 */}
              <Button
                variant="outline"
                size="sm"
                className="h-7 text-xs gap-1"
                onClick={() => {
                  // 선택된 날짜 기준으로 새 일정 등록
                  const year = selectedDate?.getFullYear() || new Date().getFullYear();
                  const month = String((selectedDate?.getMonth() || new Date().getMonth()) + 1).padStart(2, '0');
                  const day = String(selectedDate?.getDate() || new Date().getDate()).padStart(2, '0');
                  const dateStr = `${year}-${month}-${day}`;
                  onScheduleEdit?.({
                    id: '',
                    title: '',
                    startDate: dateStr,
                    endDate: dateStr,
                    type: 'schedule',
                  });
                }}
              >
                <Plus className="h-3 w-3" />
                일정등록
              </Button>
            </div>

            {/* 총 N건 */}
            <div className="text-sm text-muted-foreground mb-4">
              총 {totalItemCount}건
            </div>

            {totalItemCount === 0 ? (
              <div className="text-center py-8 text-muted-foreground">
                선택한 날짜에 일정이 없습니다.
              </div>
            ) : (
              <div className="space-y-3 max-h-[calc(100vh-400px)] overflow-y-auto pr-1">
                {/* 일정 목록 */}
                {selectedDateItems.schedules.map((schedule) => (
                  <div
                    key={schedule.id}
                    className="p-3 border rounded-lg hover:bg-gray-50 transition-colors cursor-pointer"
                    onClick={() => onScheduleClick?.(schedule)}
                  >
                    {/* 제목 */}
                    <div className="font-medium text-base mb-1">
                      {schedule.title}
                    </div>
                    {/* 부서명 | 날짜 | 시간 */}
                    <div className="text-sm text-muted-foreground">
                      {formatScheduleDetail(schedule)}
                    </div>
                  </div>
                ))}

                {/* 이슈 목록 */}
                {selectedDateItems.issues.map((issue) => (
                  <div
                    key={issue.id}
                    className="p-3 border border-red-200 rounded-lg hover:bg-red-50 transition-colors cursor-pointer"
                    onClick={() => {
                      if (issue.path) {
                        router.push(`/ko${issue.path}`);
                      }
                    }}
                  >
                    {/* 뱃지 + 제목 */}
                    <div className="flex items-start gap-2 mb-1">
                      <Badge
                        variant="secondary"
                        className={`shrink-0 text-xs ${ISSUE_BADGE_COLORS[issue.badge]}`}
                      >
                        {issue.badge}
                      </Badge>
                      <span className="font-medium text-sm flex-1">
                        {issue.content}
                      </span>
                    </div>
                    {/* 시간 + 상세보기 */}
                    <div className="flex items-center justify-between text-xs text-muted-foreground">
                      <span>{issue.time}</span>
                      {issue.path && (
                        <span className="flex items-center gap-1 text-blue-600 hover:underline">
                          상세보기
                          <ExternalLink className="h-3 w-3" />
                        </span>
                      )}
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>
      </CardContent>
    </Card>
  );
}