import { useState, useEffect, useCallback } from 'react';
import { Calendar, Search, User, RefreshCw, ChevronLeft, ChevronRight, Plus } from 'lucide-react';
import { comms } from '../communication';
import { HolidayRequest, HolidayRequestSummary } from '../types';
import { HolidayRequestDialog } from '../components/holiday/HolidayRequestDialog';

export default function HolidayRequestPage() {
  const [loading, setLoading] = useState(false);
  const [requests, setRequests] = useState<HolidayRequest[]>([]);
  const [summary, setSummary] = useState<HolidayRequestSummary>({
    ApprovedDays: 0,
    ApprovedTimes: 0,
    PendingDays: 0,
    PendingTimes: 0
  });

  // 필터 상태
  const [startDate, setStartDate] = useState('');
  const [endDate, setEndDate] = useState('');
  const [selectedUserId, setSelectedUserId] = useState('%');
  const [userLevel, setUserLevel] = useState(0);
  const [currentUserId, setCurrentUserId] = useState('');
  const [currentUserName, setCurrentUserName] = useState('');

  // 사용자 목록
  const [users, setUsers] = useState<Array<{id: string, name: string}>>([]);

  // Dialog State
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [selectedRequest, setSelectedRequest] = useState<HolidayRequest | null>(null);

  useEffect(() => {
    // 초기 날짜 설정: 1개월 전 ~ 1개월 후
    const today = new Date();
    const oneMonthAgo = new Date(today);
    oneMonthAgo.setMonth(today.getMonth() - 1);
    const oneMonthLater = new Date(today);
    oneMonthLater.setMonth(today.getMonth() + 1);

    setStartDate(formatDate(oneMonthAgo));
    setEndDate(formatDate(oneMonthLater));

    // 사용자 정보 로드
    loadUserInfo();
  }, []);

  useEffect(() => {
    if (startDate && endDate && currentUserId) {
      loadData();
    }
  }, [startDate, endDate, selectedUserId, currentUserId]);

  const formatDate = (date: Date) => {
    return date.toISOString().split('T')[0];
  };

  const formatDateShort = (dateStr?: string) => {
    if (!dateStr) return '-';
    const d = dateStr.substring(0, 10);
    if (d.length < 10) return d;
    return `${d.substring(2, 4)}-${d.substring(5, 7)}-${d.substring(8, 10)}`;
  };

  const loadUserInfo = async () => {
    try {
      // 사용자 정보 조회
      const loginStatus = await comms.checkLoginStatus();
      if (loginStatus.Success && loginStatus.IsLoggedIn && loginStatus.User) {
        const user = loginStatus.User as { Level?: number; Id?: string; NameK?: string; Name?: string };
        setCurrentUserId(user.Id || '');
        setCurrentUserName(user.NameK || user.Name || '');
        setUserLevel(user.Level || 0);

        // 사용자 목록 로드
        loadUsers(user.Level || 0);
      }
    } catch (error) {
      console.error('Failed to load user info:', error);
    }
  };

  const loadUsers = async (level: number) => {
    try {
      // 레벨 5 이상만 사용자 목록 조회 가능
      if (level >= 5) {
        const userList = await comms.getUserList('');
        if (userList && userList.length > 0) {
          const mappedUsers = userList.map((u: any) => ({
            id: u.id || u.Id,
            name: u.name || u.NameK || u.id
          }));
          setUsers([{ id: '%', name: '전체' }, ...mappedUsers]);
        }
      }
    } catch (error) {
      console.error('Failed to load users:', error);
    }
  };

  const loadData = useCallback(async () => {
    if (!startDate || !endDate) return;
    
    setLoading(true);
    try {
      const userId = userLevel < 5 ? currentUserId : selectedUserId;
      const response = await comms.getHolidayRequestList(startDate, endDate, userId, userLevel);
      
      if (response.Success && response.Data) {
        setRequests(response.Data);
        // Summary는 별도 필드로 올 수 있음
        const data = response as any;
        if (data.Summary) {
          setSummary(data.Summary);
        }
      }
    } catch (error) {
      console.error('Failed to load holiday requests:', error);
      alert('데이터를 불러오는 중 오류가 발생했습니다.');
    } finally {
      setLoading(false);
    }
  }, [startDate, endDate, selectedUserId, userLevel, currentUserId]);

  // 월 이동
  const moveMonth = (offset: number) => {
    const current = new Date(startDate);
    current.setMonth(current.getMonth() + offset);
    const year = current.getFullYear();
    const month = current.getMonth();
    
    const newStart = new Date(year, month, 1);
    const newEnd = new Date(year, month + 1, 0);
    
    setStartDate(formatDate(newStart));
    setEndDate(formatDate(newEnd));
  };

  const getCategoryName = (cate: string) => {
    const categories: { [key: string]: string } = {
      '1': '연차',
      '2': '반차',
      '3': '병가',
      '4': '경조사',
      '5': '외출',
      '6': '기타'
    };
    return categories[cate] || cate;
  };

  const getConfirmStatusText = (conf: number) => {
    return conf === 1 ? '승인' : '미승인';
  };

  return (
    <div className="flex flex-col h-full bg-gradient-to-br from-slate-50 via-blue-50/30 to-slate-50">
      {/* 헤더 */}
      <div className="glass-effect-solid border-b border-white/20">
        <div className="flex items-center justify-between px-6 py-4">
          <div className="flex items-center space-x-3">
            <div className="p-2 bg-gradient-to-br from-blue-500 to-blue-600 rounded-xl shadow-lg">
              <Calendar className="w-5 h-5 text-white" />
            </div>
            <div>
              <h1 className="text-xl font-bold text-white">휴가/외출 신청</h1>
              <p className="text-sm text-white/70">Holiday Request Management</p>
            </div>
          </div>
          <div className="flex items-center gap-2">
            <button
              onClick={() => {
                setSelectedRequest(null);
                setIsDialogOpen(true);
              }}
              className="flex items-center gap-2 px-4 py-2 bg-blue-500 hover:bg-blue-600 text-white rounded-lg transition-all shadow-lg hover:shadow-blue-500/30"
            >
              <Plus className="w-4 h-4" />
              <span className="text-sm font-medium">신청</span>
            </button>
            <button
              onClick={loadData}
              disabled={loading}
              className="flex items-center gap-2 px-4 py-2 glass-effect-solid hover:bg-white/20 rounded-lg transition-all text-white disabled:opacity-50"
            >
              <RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
              <span className="text-sm font-medium">새로고침</span>
            </button>
          </div>
        </div>
      </div>

      {/* 필터 영역 */}
      <div className="glass-effect-solid border-b border-white/20">
        <div className="px-6 py-4">
          <div className="flex items-center gap-4 flex-wrap">
            {/* 월 이동 버튼 */}
            <div className="flex items-center gap-2">
              <button
                onClick={() => moveMonth(-1)}
                className="p-2 glass-effect hover:bg-white/30 rounded-lg transition-all"
              >
                <ChevronLeft className="w-4 h-4 text-white" />
              </button>
              <div className="flex items-center gap-2">
                <Calendar className="w-4 h-4 text-white/80" />
                <input
                  type="date"
                  value={startDate}
                  onChange={(e) => setStartDate(e.target.value)}
                  className="px-3 py-2 glass-effect text-white text-sm rounded-lg focus:ring-2 focus:ring-blue-400/50 focus:outline-none"
                />
                <span className="text-white/60">~</span>
                <input
                  type="date"
                  value={endDate}
                  onChange={(e) => setEndDate(e.target.value)}
                  className="px-3 py-2 glass-effect text-white text-sm rounded-lg focus:ring-2 focus:ring-blue-400/50 focus:outline-none"
                />
              </div>
              <button
                onClick={() => moveMonth(1)}
                className="p-2 glass-effect hover:bg-white/30 rounded-lg transition-all"
              >
                <ChevronRight className="w-4 h-4 text-white" />
              </button>
            </div>

            {/* 담당자 선택 (레벨 5 이상만) */}
            {userLevel >= 5 && (
              <div className="flex items-center gap-2">
                <User className="w-4 h-4 text-white/80" />
                <select
                  value={selectedUserId}
                  onChange={(e) => setSelectedUserId(e.target.value)}
                  className="px-3 py-2 glass-effect text-white text-sm rounded-lg focus:ring-2 focus:ring-blue-400/50 focus:outline-none"
                >
                  {users.map(user => (
                    <option key={user.id} value={user.id}>{user.name}</option>
                  ))}
                </select>
              </div>
            )}

            {/* 조회 버튼 */}
            <button
              onClick={loadData}
              disabled={loading}
              className="flex items-center gap-2 px-4 py-2 bg-gradient-to-r from-blue-500 to-blue-600 hover:from-blue-600 hover:to-blue-700 text-white text-sm font-medium rounded-lg shadow-lg transition-all disabled:opacity-50"
            >
              <Search className="w-4 h-4" />
              조회
            </button>
          </div>

          {/* 합계 표시 */}
          <div className="mt-4 flex gap-6 text-sm">
            <div className="glass-effect px-4 py-2 rounded-lg">
              <span className="font-medium text-white/90">합계(일) = </span>
              <span className="text-blue-300 font-semibold">승인: {summary.ApprovedDays}</span>
              <span className="mx-1 text-white/60">/</span>
              <span className={summary.PendingDays === 0 ? 'text-white/90' : 'text-red-400 font-semibold'}>
                미승인: {summary.PendingDays}
              </span>
            </div>
            <div className="glass-effect px-4 py-2 rounded-lg">
              <span className="font-medium text-white/90">합계(시간) = </span>
              <span className="text-blue-300 font-semibold">승인: {summary.ApprovedTimes}</span>
              <span className="mx-1 text-white/60">/</span>
              <span className={summary.PendingTimes === 0 ? 'text-white/90' : 'text-red-400 font-semibold'}>
                미승인: {summary.PendingTimes}
              </span>
            </div>
          </div>
        </div>
      </div>

      {/* 테이블 */}
      <div className="flex-1 overflow-auto px-6 py-4">
        <div className="glass-effect-solid rounded-xl overflow-hidden">
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b border-white/10">
                  <th className="px-4 py-3 text-left font-semibold text-white/90">No</th>
                  <th className="px-4 py-3 text-left font-semibold text-white/90">신청일</th>
                  <th className="px-4 py-3 text-left font-semibold text-white/90">부서</th>
                  <th className="px-4 py-3 text-left font-semibold text-white/90">신청자</th>
                  <th className="px-4 py-3 text-left font-semibold text-white/90">종류</th>
                  <th className="px-4 py-3 text-left font-semibold text-white/90">시작일</th>
                  <th className="px-4 py-3 text-left font-semibold text-white/90">종료일</th>
                  <th className="px-4 py-3 text-center font-semibold text-white/90">일수</th>
                  <th className="px-4 py-3 text-center font-semibold text-white/90">시간</th>
                  <th className="px-4 py-3 text-left font-semibold text-white/90">사유</th>
                  <th className="px-4 py-3 text-center font-semibold text-white/90">승인</th>
                </tr>
              </thead>
              <tbody>
                {loading ? (
                  <tr>
                    <td colSpan={11} className="px-4 py-12 text-center">
                      <div className="flex items-center justify-center gap-3">
                        <RefreshCw className="w-5 h-5 text-blue-400 animate-spin" />
                        <span className="text-white/60">데이터를 불러오는 중...</span>
                      </div>
                    </td>
                  </tr>
                ) : requests.length === 0 ? (
                  <tr>
                    <td colSpan={11} className="px-4 py-12 text-center">
                      <div className="flex flex-col items-center justify-center gap-3">
                        <Calendar className="w-12 h-12 text-white/30" />
                        <span className="text-white/60">조회된 데이터가 없습니다.</span>
                      </div>
                    </td>
                  </tr>
                ) : (
                  requests.map((req, index) => (
                    <tr 
                      key={req.idx} 
                      className="border-b border-white/5 hover:bg-white/5 transition-colors cursor-pointer"
                      onClick={() => {
                        setSelectedRequest(req);
                        setIsDialogOpen(true);
                      }}
                    >
                      <td className="px-4 py-3 text-white/70">{index + 1}</td>
                      <td className="px-4 py-3 text-white/90">{formatDateShort(req.wdate)}</td>
                      <td className="px-4 py-3 text-white/80">{req.dept || ''}</td>
                      <td className="px-4 py-3 text-white font-medium">{req.name || ''}</td>
                      <td className="px-4 py-3">
                        <span className="px-2 py-1 bg-blue-500/20 text-blue-300 rounded text-xs font-medium">
                          {getCategoryName(req.cate)}
                        </span>
                      </td>
                      <td className="px-4 py-3 text-white/90">{formatDateShort(req.sdate)}</td>
                      <td className="px-4 py-3 text-white/90">{formatDateShort(req.edate)}</td>
                      <td className="px-4 py-3 text-center text-white/90">{req.HolyDays || 0}</td>
                      <td className="px-4 py-3 text-center text-white/90">{req.HolyTimes || 0}</td>
                      <td className="px-4 py-3 text-white/70 max-w-xs truncate" title={req.HolyReason || ''}>
                        {req.HolyReason || '-'}
                      </td>
                      <td className="px-4 py-3 text-center">
                        <span className={`px-2 py-1 rounded text-xs font-semibold ${
                          req.conf === 1 
                            ? 'bg-green-500/20 text-green-300' 
                            : 'bg-red-500/20 text-red-300'
                        }`}>
                          {getConfirmStatusText(req.conf)}
                        </span>
                      </td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>
        </div>
      </div>

      {/* 다이얼로그 */}
      <HolidayRequestDialog
        isOpen={isDialogOpen}
        onClose={() => setIsDialogOpen(false)}
        onSave={() => {
          setIsDialogOpen(false);
          loadData();
        }}
        initialData={selectedRequest}
        currentUserName={currentUserName}
        currentUserId={currentUserId}
        userLevel={userLevel}
      />
    </div>
  );
}
