import { useState, useEffect, useCallback } from 'react';
import {
  Calendar,
  Save,
  RefreshCw,
  ChevronLeft,
  ChevronRight,
  Loader2,
} from 'lucide-react';
import { comms } from '@/communication';
import { HolidayItem } from '@/types';

interface DayInfo extends HolidayItem {
  dayOfWeek: number;
  dayName: string;
}

export function MonthlyWorkPage() {
  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);
  const [month, setMonth] = useState(() => {
    const now = new Date();
    return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`;
  });
  const [holidays, setHolidays] = useState<DayInfo[]>([]);
  const [hasChanges, setHasChanges] = useState(false);

  const dayNames = ['일', '월', '화', '수', '목', '금', '토'];

  const loadData = useCallback(async () => {
    setLoading(true);
    try {
      // 먼저 초기화 시도 (데이터 없으면 생성)
      await comms.initializeHoliday(month);

      // 데이터 로드
      const response = await comms.getHolidayList(month);
      if (response.Success && response.Data) {
        const data = response.Data.map(item => {
          const date = new Date(item.pdate);
          return {
            ...item,
            dayOfWeek: date.getDay(),
            dayName: dayNames[date.getDay()],
          };
        });
        setHolidays(data);
        setHasChanges(false);
      }
    } catch (error) {
      console.error('데이터 로드 오류:', error);
      alert('데이터를 불러오는 중 오류가 발생했습니다.');
    } finally {
      setLoading(false);
    }
  }, [month]);

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

  const handleMonthChange = (delta: number) => {
    const [year, mon] = month.split('-').map(Number);
    const newDate = new Date(year, mon - 1 + delta, 1);
    setMonth(`${newDate.getFullYear()}-${String(newDate.getMonth() + 1).padStart(2, '0')}`);
  };

  const handleToggleFree = (idx: number) => {
    setHolidays(prev => prev.map(h =>
      h.idx === idx ? { ...h, free: !h.free } : h
    ));
    setHasChanges(true);
  };

  const handleMemoChange = (idx: number, memo: string) => {
    setHolidays(prev => prev.map(h =>
      h.idx === idx ? { ...h, memo } : h
    ));
    setHasChanges(true);
  };

  const handleSave = async () => {
    setSaving(true);
    try {
      const dataToSave = holidays.map(({ idx, pdate, free, memo }) => ({
        idx, pdate, free, memo
      }));
      const response = await comms.saveHolidays(month, dataToSave as HolidayItem[]);
      if (response.Success) {
        setHasChanges(false);
      } else {
        alert(response.Message || '저장에 실패했습니다.');
      }
    } catch (error) {
      console.error('저장 오류:', error);
      alert('저장 중 오류가 발생했습니다.');
    } finally {
      setSaving(false);
    }
  };

  // 통계 계산
  const workDays = holidays.filter(h => !h.free).length;
  const freeDays = holidays.filter(h => h.free).length;

  return (
    <div className="space-y-6">
      {/* 헤더 */}
      <div className="glass-effect rounded-2xl p-6">
        <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
          <div className="flex items-center space-x-3">
            <div className="p-3 bg-primary-500/20 rounded-xl">
              <Calendar className="w-6 h-6 text-primary-400" />
            </div>
            <div>
              <h1 className="text-2xl font-bold text-white">월별근무표</h1>
              <p className="text-white/60 text-sm">휴일 및 근무일 관리</p>
            </div>
          </div>

          <div className="flex items-center space-x-4">
            {/* 월 선택 */}
            <div className="flex items-center space-x-2 bg-white/10 rounded-lg px-3 py-2">
              <button
                onClick={() => handleMonthChange(-1)}
                className="p-1 hover:bg-white/10 rounded transition-colors"
              >
                <ChevronLeft className="w-5 h-5 text-white" />
              </button>
              <input
                type="month"
                value={month}
                onChange={(e) => setMonth(e.target.value)}
                className="bg-transparent text-white text-center w-32 focus:outline-none"
              />
              <button
                onClick={() => handleMonthChange(1)}
                className="p-1 hover:bg-white/10 rounded transition-colors"
              >
                <ChevronRight className="w-5 h-5 text-white" />
              </button>
            </div>

            {/* 버튼들 */}
            <button
              onClick={loadData}
              disabled={loading}
              className="flex items-center space-x-2 px-4 py-2 bg-white/10 hover:bg-white/20 rounded-lg text-white transition-colors disabled:opacity-50"
            >
              <RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
              <span className="hidden sm:inline">새로고침</span>
            </button>

            <button
              onClick={handleSave}
              disabled={saving || !hasChanges}
              className="flex items-center space-x-2 px-4 py-2 bg-primary-500 hover:bg-primary-600 rounded-lg text-white transition-colors disabled:opacity-50"
            >
              {saving ? (
                <Loader2 className="w-4 h-4 animate-spin" />
              ) : (
                <Save className="w-4 h-4" />
              )}
              <span>저장</span>
            </button>
          </div>
        </div>

        {/* 통계 */}
        <div className="mt-4 flex items-center space-x-6 text-sm">
          <span className="text-white/70">
            근무일: <span className="text-white font-semibold">{workDays}일</span>
          </span>
          <span className="text-white/70">
            휴일: <span className="text-danger-400 font-semibold">{freeDays}일</span>
          </span>
          <span className="text-white/70">
            총: <span className="text-white font-semibold">{holidays.length}일</span>
          </span>
        </div>
      </div>

      {/* 테이블 */}
      <div className="glass-effect rounded-2xl overflow-hidden">
        {loading ? (
          <div className="flex items-center justify-center py-20">
            <Loader2 className="w-8 h-8 text-white animate-spin" />
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead className="bg-white/10">
                <tr>
                  <th className="px-4 py-3 text-left text-xs font-medium text-white/70 uppercase w-32">날짜</th>
                  <th className="px-4 py-3 text-center text-xs font-medium text-white/70 uppercase w-20">요일</th>
                  <th className="px-4 py-3 text-center text-xs font-medium text-white/70 uppercase w-24">휴일</th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-white/70 uppercase">메모</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-white/5">
                {holidays.map((day) => (
                  <tr
                    key={day.idx}
                    className={`hover:bg-white/5 transition-colors ${
                      day.dayOfWeek === 0 ? 'bg-danger-500/10' :
                      day.dayOfWeek === 6 ? 'bg-primary-500/10' : ''
                    }`}
                  >
                    <td className="px-4 py-3 text-white text-sm">
                      {day.pdate}
                    </td>
                    <td className={`px-4 py-3 text-center text-sm font-medium ${
                      day.dayOfWeek === 0 ? 'text-danger-400' :
                      day.dayOfWeek === 6 ? 'text-primary-400' : 'text-white/70'
                    }`}>
                      {day.dayName}
                    </td>
                    <td className="px-4 py-3 text-center">
                      <button
                        onClick={() => handleToggleFree(day.idx)}
                        className={`w-8 h-8 rounded-lg transition-colors ${
                          day.free
                            ? 'bg-danger-500/20 text-danger-400 hover:bg-danger-500/30'
                            : 'bg-white/10 text-white/40 hover:bg-white/20'
                        }`}
                      >
                        {day.free ? 'O' : '-'}
                      </button>
                    </td>
                    <td className="px-4 py-3">
                      <input
                        type="text"
                        value={day.memo || ''}
                        onChange={(e) => handleMemoChange(day.idx, e.target.value)}
                        placeholder="메모 입력..."
                        className="w-full bg-white/5 border border-white/10 rounded-lg px-3 py-1.5 text-white text-sm focus:outline-none focus:border-primary-500"
                      />
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
}
