'use client';

import { useState, useEffect, useCallback, useMemo } from 'react';
import { CalendarDays, ChevronLeft, ChevronRight, Plus, Upload } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Card, CardContent } from '@/components/ui/card';
import { PageLayout } from '@/components/organisms/PageLayout';
import { PageHeader } from '@/components/organisms/PageHeader';
import { StatCards } from '@/components/organisms/StatCards';
import { TableEmptyState } from '@/components/organisms';
import { useColumnSettings } from '@/hooks/useColumnSettings';
import { useCalendarScheduleStore } from '@/stores/useCalendarScheduleStore';
import { ColumnSettingsPopover } from '@/components/molecules/ColumnSettingsPopover';
import { YearCalendar } from './YearCalendar';
import { CalendarDetailDialog } from './CalendarDetailDialog';
import { BulkRegistrationDialog } from './BulkRegistrationDialog';
import { getCalendarSchedules, getCalendarStats } from './actions';
import {
  SCHEDULE_TYPE_OPTIONS,
  SCHEDULE_TYPE_LABELS,
  SCHEDULE_TYPE_BADGE_COLORS,
} from './types';
import type { CalendarSchedule, CalendarStats } from './types';
import { formatDate, getLocalDateString } from '@/lib/utils/date';
import type { TableColumn } from '@/components/templates/UniversalListPage/types';

const LIST_COLUMNS: TableColumn[] = [
  { key: 'no', label: 'No.', className: 'text-center w-[60px]' },
  { key: 'type', label: '유형', className: 'w-[100px]', copyable: true },
  { key: 'name', label: '일정명', copyable: true },
  { key: 'startDate', label: '시작일', className: 'w-[120px]', copyable: true },
  { key: 'endDate', label: '종료일', className: 'w-[120px]', copyable: true },
  { key: 'days', label: '일수', className: 'text-center w-[70px]', copyable: true },
  { key: 'isRecurring', label: '반복', className: 'text-center w-[70px]' },
  { key: 'memo', label: '메모', copyable: true },
];

export function CalendarManagement() {
  const [year, setYear] = useState(() => new Date().getFullYear());
  const [tab, setTab] = useState('calendar');
  const [typeFilter, setTypeFilter] = useState('all');

  const [schedules, setSchedules] = useState<CalendarSchedule[]>([]);
  const [stats, setStats] = useState<CalendarStats>({ totalCount: 0, totalHolidayDays: 0, publicHolidayCount: 0 });
  const [, setIsLoading] = useState(true);

  // Dialog states
  const [detailOpen, setDetailOpen] = useState(false);
  const [detailMode, setDetailMode] = useState<'create' | 'edit'>('create');
  const [selectedSchedule, setSelectedSchedule] = useState<CalendarSchedule | null>(null);
  const [defaultDate, setDefaultDate] = useState('');
  const [bulkOpen, setBulkOpen] = useState(false);

  // Column settings
  const {
    visibleColumns,
    allColumnsWithVisibility,
    toggleColumnVisibility,
    resetSettings,
    hasHiddenColumns,
  } = useColumnSettings({
    pageId: 'calendar-management',
    columns: LIST_COLUMNS,
    alwaysVisibleKeys: ['no', 'name'],
  });

  const loadData = useCallback(async () => {
    setIsLoading(true);
    try {
      const [schedulesResult, statsResult] = await Promise.all([
        getCalendarSchedules(year),
        getCalendarStats(year),
      ]);
      const loadedSchedules = schedulesResult.success && schedulesResult.data ? schedulesResult.data : [];
      setSchedules(loadedSchedules);
      if (statsResult.success && statsResult.data) {
        setStats(statsResult.data);
      }
      // 캐시 무효화 후 새 데이터 설정 → 다른 컴포넌트에서 stale 데이터 방지
      const store = useCalendarScheduleStore.getState();
      store.invalidateYear(year);
      store.setSchedulesForYear(year, loadedSchedules);
    } catch {
      // 조회 실패 시 빈 상태 유지
    } finally {
      setIsLoading(false);
    }
  }, [year]);

  useEffect(() => {
    loadData();
  }, [loadData]);

  const filteredSchedules = useMemo(() => {
    if (typeFilter === 'all') return schedules;
    return schedules.filter((s) => s.type === typeFilter);
  }, [schedules, typeFilter]);

  const handleDateClick = useCallback((date: Date) => {
    setDefaultDate(getLocalDateString(date));
    setSelectedSchedule(null);
    setDetailMode('create');
    setDetailOpen(true);
  }, []);

  const handleRowClick = useCallback((schedule: CalendarSchedule) => {
    setSelectedSchedule(schedule);
    setDetailMode('edit');
    setDetailOpen(true);
  }, []);

  const handleCreateClick = useCallback(() => {
    setSelectedSchedule(null);
    setDefaultDate('');
    setDetailMode('create');
    setDetailOpen(true);
  }, []);

  const statCards = useMemo(() => [
    { label: '등록 건수', value: `${stats.totalCount}건` },
    { label: '총 휴일 일수', value: `${stats.totalHolidayDays}일` },
    { label: '공휴일', value: `${stats.publicHolidayCount}건` },
  ], [stats]);

  const renderCell = useCallback((schedule: CalendarSchedule, col: TableColumn, index: number) => {
    switch (col.key) {
      case 'no':
        return index + 1;
      case 'type':
        return (
          <Badge className={SCHEDULE_TYPE_BADGE_COLORS[schedule.type]} variant="secondary">
            {SCHEDULE_TYPE_LABELS[schedule.type]}
          </Badge>
        );
      case 'name':
        return <span className="font-medium">{schedule.name}</span>;
      case 'startDate':
        return formatDate(schedule.startDate);
      case 'endDate':
        return formatDate(schedule.endDate);
      case 'days':
        return schedule.days;
      case 'isRecurring':
        return schedule.isRecurring ? 'O' : '-';
      case 'memo':
        return <span className="text-muted-foreground truncate max-w-[200px]">{schedule.memo || '-'}</span>;
      default:
        return '-';
    }
  }, []);

  return (
    <PageLayout>
      <PageHeader
        title="달력 관리"
        description="달력을 관리합니다"
        icon={CalendarDays}
      />

      <div className="space-y-4">
        {/* 탭 + 버튼 영역 */}
        <div className="flex items-center justify-between flex-wrap gap-2">
          <Tabs value={tab} onValueChange={setTab}>
            <TabsList>
              <TabsTrigger value="calendar">달력</TabsTrigger>
              <TabsTrigger value="list">목록</TabsTrigger>
            </TabsList>
          </Tabs>

          <div className="flex items-center gap-2">
            <Button variant="outline" size="sm" onClick={() => setBulkOpen(true)}>
              <Upload className="h-4 w-4 mr-1" />
              대량 등록
            </Button>
            <Button size="sm" onClick={handleCreateClick}>
              <Plus className="h-4 w-4 mr-1" />
              달력 일정 등록
            </Button>
          </div>
        </div>

        {/* 연도 네비게이션 */}
        <div className="flex items-center justify-center gap-4">
          <Button variant="ghost" size="icon" onClick={() => setYear((y) => y - 1)}>
            <ChevronLeft className="h-5 w-5" />
          </Button>
          <span className="text-lg font-semibold">{year}년</span>
          <Button variant="ghost" size="icon" onClick={() => setYear((y) => y + 1)}>
            <ChevronRight className="h-5 w-5" />
          </Button>
        </div>

        {/* 통계 */}
        <StatCards stats={statCards} />

        {/* 탭 컨텐츠 */}
        {tab === 'calendar' ? (
          <YearCalendar
            year={year}
            schedules={schedules}
            onDateClick={handleDateClick}
          />
        ) : (
          <Card>
            <CardContent className="pt-6">
              {/* 테이블 헤더: 건수 + 필터 + 컬럼 설정 */}
              <div className="flex flex-wrap gap-2 justify-between items-center mb-4">
                <div className="flex items-center gap-2 text-sm">
                  <span className="text-muted-foreground">
                    전체 {filteredSchedules.length}건
                  </span>
                </div>
                <div className="flex items-center gap-2">
                  <Select value={typeFilter} onValueChange={setTypeFilter}>
                    <SelectTrigger className="min-w-[120px] w-auto h-8">
                      <SelectValue placeholder="유형 선택" />
                    </SelectTrigger>
                    <SelectContent>
                      {SCHEDULE_TYPE_OPTIONS.map((opt) => (
                        <SelectItem key={opt.value} value={opt.value}>
                          {opt.label}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                  <ColumnSettingsPopover
                    columns={allColumnsWithVisibility}
                    onToggle={toggleColumnVisibility}
                    onReset={resetSettings}
                    hasHiddenColumns={hasHiddenColumns}
                  />
                </div>
              </div>

              {/* 테이블 */}
              <div className="rounded-md border overflow-x-auto">
                <Table className="min-w-[700px]">
                  <TableHeader>
                    <TableRow>
                      {visibleColumns.map((col) => (
                        <TableHead key={col.key} className={col.className}>
                          {col.label}
                        </TableHead>
                      ))}
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {filteredSchedules.length === 0 ? (
                      <TableEmptyState colSpan={visibleColumns.length} message="등록된 일정이 없습니다." />
                    ) : (
                      filteredSchedules.map((schedule, index) => (
                        <TableRow
                          key={schedule.id}
                          className="cursor-pointer hover:bg-muted/50"
                          onClick={() => handleRowClick(schedule)}
                        >
                          {visibleColumns.map((col) => (
                            <TableCell key={col.key} className={col.className}>
                              {renderCell(schedule, col, index)}
                            </TableCell>
                          ))}
                        </TableRow>
                      ))
                    )}
                  </TableBody>
                </Table>
              </div>
            </CardContent>
          </Card>
        )}
      </div>

      {/* 다이얼로그 */}
      <CalendarDetailDialog
        open={detailOpen}
        onOpenChange={setDetailOpen}
        mode={detailMode}
        schedule={selectedSchedule}
        defaultDate={defaultDate}
        onSuccess={loadData}
      />

      <BulkRegistrationDialog
        open={bulkOpen}
        onOpenChange={setBulkOpen}
        onSuccess={loadData}
        schedules={schedules}
      />
    </PageLayout>
  );
}
