import { useState, useEffect, useCallback } from 'react';
import {
  Calendar,
  Search,
  Filter,
  XCircle,
  RefreshCw,
  Plus,
} from 'lucide-react';
import { comms } from '../communication';
import { HolidayRequest, HolidayRequestSummary, GroupUser } from '../types';
import { HolidayRequestDialog } from '../components/holiday/HolidayRequestDialog';
import { DevelopmentNotice } from '@/components/DevelopmentNotice';
import { DateRangePicker } from '@/components/DateRangePicker';
import { UserSelector } from '@/components/UserSelector';

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 [balance, setBalance] = useState({ days: 0, times: 0 });

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

  // 사용자 목록
  const [users, setUsers] = useState<GroupUser[]>([]);

  // 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 };
        const userId = user.Id || '';
        const level = user.Level || 0;

        setCurrentUserId(userId);
        setCurrentUserName(user.NameK || user.Name || '');
        setUserLevel(level);

        // 기본 선택: 본인
        setSelectedUserId(userId);

        // 레벨 5 이상인 경우 사용자 목록 로드 (전체 조회 가능)
        if (level >= 5) {
          loadUsers();
        } else {
          // 권한이 없으면 본인만 선택 가능 (UI 콤보박스 비활성화)
          setUsers([{ id: userId, name: user.NameK || user.Name || userId } as GroupUser]);
        }
      }
    } catch (error) {
      console.error('Failed to load user info:', error);
    }
  };

  const loadUsers = async () => {
    try {
      const userList = await comms.getUserList('');
      if (userList && userList.length > 0) {
        setUsers(userList);
      }
    } 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);
        }
        console.log(summary, balance); // dummy use to avoid lint error while keeping states for future
      }


      // Fetch Balance
      // If viewing all, show current user's balance. If viewing specific user, show that user's balance.
      const targetUid = userId === '%' ? currentUserId : userId;
      if (targetUid) {
        const year = startDate.substring(0, 4);
        const balanceResp = await comms.getHolydayBalance(year, targetUid);
        if (balanceResp.Success && balanceResp.Data) {
          let d = 0, t = 0;
          balanceResp.Data.forEach(item => {
            d += (item.TotalGenDays - item.TotalUseDays);
            t += (item.TotalGenHours - item.TotalUseHours);
          });
          setBalance({ days: d, times: t });
        } else {
          setBalance({ days: 0, times: 0 });
        }
      }

    } catch (error) {
      console.error('Failed to load holiday requests:', error);
      alert('데이터를 불러오는 중 오류가 발생했습니다.');
    } finally {
      setLoading(false);
    }
  }, [startDate, endDate, selectedUserId, userLevel, currentUserId]);



  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 ? '승인' : '미승인';
  };

  // 카운팅: 미래 휴가 (예정일 + 건수)
  /*
    const scheduledStats = requests.reduce((acc, req) => {
      if (!req.sdate) return acc;
      const today = new Date();
      today.setHours(0, 0, 0, 0);
      const startDate = new Date(req.sdate);
      // 오늘 이후에 시작하는 휴가
      if (startDate > today) {
        return {
          count: acc.count + 1,
          days: acc.days + (req.HolyDays || 0)
        };
      }
      return acc;
    }, { count: 0, days: 0 });
  */

  const isFuture = (dateStr?: string) => {
    if (!dateStr) return false;
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    const startDate = new Date(dateStr);
    return startDate > today;
  };

  const filteredRequests = requests.filter(req => {
    if (!filterText) return true;
    const searchLower = filterText.toLowerCase();
    return (
      (req.name || '').toLowerCase().includes(searchLower) ||
      (req.uid || '').toLowerCase().includes(searchLower) ||
      (req.HolyReason || '').toLowerCase().includes(searchLower) ||
      (req.HolyLocation || '').toLowerCase().includes(searchLower) ||
      getCategoryName(req.cate).toLowerCase().includes(searchLower)
    );
  });

  return (
    <div className="space-y-6 animate-fade-in">
      <div className="max-w-[1920px] mx-auto space-y-6">
        <DevelopmentNotice />
        {/* 상단 컨트롤 바 */}
        <div className="glass-effect rounded-2xl p-6 relative z-20">
          <div className="flex flex-col space-y-4">

            <div className="flex flex-col md:flex-row gap-4 items-end md:items-center justify-between">
              {/* Date Move & Pick */}
              <div className="flex items-center gap-4 w-full md:w-auto flex-wrap">
                <DateRangePicker
                  startDate={startDate}
                  endDate={endDate}
                  onChange={(start, end) => {
                    setStartDate(start);
                    setEndDate(end);
                  }}
                  align="vertical"
                />

                <div className="w-full md:w-64">
                  <UserSelector
                    users={users}
                    selectedIds={selectedUserId === '%' ? [] : [selectedUserId]}
                    onChange={(ids) => setSelectedUserId(ids[0] || '%')}
                    placeholder="신청자 선택"
                    className="w-full"
                  />
                </div>

                <div className="h-10 flex items-end">
                  <button
                    onClick={loadData}
                    disabled={loading}
                    className="flex-1 md:flex-none bg-white/10 hover:bg-white/20 text-white px-4 py-2 rounded-lg transition-colors flex items-center justify-center disabled:opacity-50 h-[60px]"
                  >
                    {loading ? <RefreshCw className="w-4 h-4 mr-2 animate-spin" /> : <Search className="w-4 h-4 mr-2" />}
                    조회
                  </button>
                </div>
              </div>

              <div className="flex gap-2 w-full md:w-auto">
                {/* Add Request */}
                <button
                  onClick={() => {
                    setSelectedRequest(null);
                    setIsDialogOpen(true);
                  }}
                  className="flex-1 md:flex-none bg-primary-500 hover:bg-primary-600 text-white px-4 py-2 rounded-lg transition-colors flex items-center justify-center font-bold"
                >
                  <Plus className="w-5 h-5 mr-1" />
                  휴가 신청
                </button>
              </div>

            </div>
          </div>
        </div>
      </div>

      {/* List Table */}
      <div className="glass-effect rounded-2xl overflow-hidden shadow-2xl transition-all duration-300">
        <div className="px-6 py-4 flex flex-col md:flex-row items-center justify-between gap-4">
          <div className="flex items-center gap-3">
            <div className="p-2 bg-primary-500/20 rounded-lg">
              <Calendar className="w-5 h-5 text-primary-400" />
            </div>
            <h3 className="text-lg font-bold text-[var(--text-primary)] tracking-tight">
              신청 내역
            </h3>
          </div>

          <div className="flex items-center gap-4 w-full md:w-auto">
            {/* 검색 필터 */}
            <div className="relative flex-1 md:w-64 group">
              <Filter className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-[var(--text-secondary)] group-focus-within:text-primary-400 transition-colors" />
              <input
                type="text"
                value={filterText}
                onChange={(e) => setFilterText(e.target.value)}
                placeholder="검색..."
                className="w-full bg-[var(--bg-paper)] border border-[var(--border-color)] rounded-xl pl-10 pr-10 py-2 text-[var(--text-primary)] focus:outline-none focus:ring-2 focus:ring-primary-500/50 transition-all text-sm placeholder-[var(--text-muted)]"
              />
              {filterText && (
                <button
                  onClick={() => setFilterText('')}
                  className="absolute right-3 top-1/2 transform -translate-y-1/2 text-[var(--text-secondary)] hover:text-[var(--text-primary)] transition-colors"
                >
                  <XCircle className="w-4 h-4" />
                </button>
              )}
            </div>
            <div className="flex items-center gap-1 bg-[var(--bg-paper)] px-3 py-1.5 rounded-lg border border-[var(--border-color)]">
              <span className="text-[var(--text-primary)] font-bold text-sm">{filteredRequests.length}</span>
              <span className="text-[var(--text-secondary)] text-xs">건</span>
              {requests.length !== filteredRequests.length && <span className="text-[var(--text-muted)] text-xs ml-1">(전체 {requests.length})</span>}
            </div>
          </div>
        </div>

        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="bg-[var(--bg-paper)]/50">
              <tr>
                <th className="px-4 py-3 text-left text-xs font-medium text-[var(--text-secondary)] uppercase w-[50px]">No</th>
                {/* <th className="px-4 py-3 text-left text-xs font-medium text-[var(--text-secondary)] uppercase">부서</th> <- Removed */}
                <th className="px-4 py-3 text-left text-xs font-medium text-[var(--text-secondary)] uppercase w-[100px]">신청자</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-[var(--text-secondary)] uppercase w-[80px]">종류</th>
                <th className="px-4 py-3 text-center text-xs font-medium text-[var(--text-secondary)] uppercase w-[80px]">상태</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-[var(--text-secondary)] uppercase w-[140px]">시작일</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-[var(--text-secondary)] uppercase w-[140px]">종료일</th>
                <th className="px-4 py-3 text-center text-xs font-medium text-[var(--text-secondary)] uppercase w-[60px]">일수</th>
                <th className="px-4 py-3 text-center text-xs font-medium text-[var(--text-secondary)] uppercase w-[60px]">시간</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-[var(--text-secondary)] uppercase w-[100px]">행선지</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-[var(--text-secondary)] uppercase">사유</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-[var(--border-color)]">
              {loading ? (
                <tr>
                  <td colSpan={10} className="px-4 py-8 text-center bg-transparent">
                    <div className="flex items-center justify-center">
                      <RefreshCw className="w-5 h-5 mr-2 animate-spin text-[var(--text-secondary)]" />
                      <span className="text-[var(--text-secondary)]">데이터를 불러오는 중...</span>
                    </div>
                  </td>
                </tr>
              ) : filteredRequests.length === 0 ? (
                <tr>
                  <td colSpan={10} className="px-4 py-8 text-center text-[var(--text-secondary)] bg-transparent">
                    {filterText ? '검색 결과가 없습니다.' : '조회된 데이터가 없습니다.'}
                  </td>
                </tr>
              ) : (
                filteredRequests.map((req, index) => {
                  // 미래 휴가 배경색 처리
                  const isFutureRequest = isFuture(req.sdate);

                  return (
                    <tr
                      key={req.idx}
                      onClick={() => {
                        // 승인되지 않았거나(1이 아님), 본인이거나, 관리자(Lev >=5)인 경우만 상세 보기 가능
                        if (req.conf !== 1 || req.uid === currentUserId || userLevel >= 5) {
                          setSelectedRequest(req);
                          setIsDialogOpen(true);
                        }
                      }}
                      className={`
                          ${index % 2 === 0 ? 'bg-[var(--bg-paper)]/30' : ''} 
                          hover:bg-[var(--bg-paper)]/50 transition-colors cursor-pointer
                          ${(req.conf === 1 && req.uid !== currentUserId && userLevel < 5) ? 'opacity-50 grayscale cursor-not-allowed' : ''}
                        `}
                    >
                      <td className="px-4 py-3 text-[var(--text-secondary)] text-sm">{index + 1}</td>
                      <td className="px-4 py-3 text-[var(--text-primary)] text-sm font-medium">{req.name || '-'}</td>
                      <td className="px-4 py-3 text-sm">
                        <span className={`px-2 py-1 rounded text-xs ${req.cate === '1' ? 'bg-primary-500/20 text-primary-300' : // 연차
                          req.cate === '2' ? 'bg-blue-500/20 text-blue-300' : // 반차
                            req.cate === '5' ? 'bg-green-500/20 text-green-300' : // 외출 (Green으로 변경 요청 있었음)
                              'bg-[var(--bg-paper)] text-[var(--text-secondary)]'
                          }`}>
                          {getCategoryName(req.cate)}
                        </span>
                      </td>
                      <td className="px-4 py-3 text-center">
                        <span className={`px-2 py-1 rounded text-xs font-semibold ${req.conf === 1
                          ? 'bg-success-500/20 text-success-300'
                          : 'bg-danger-500/20 text-danger-300'
                          }`}>
                          {getConfirmStatusText(req.conf)}
                        </span>
                      </td>
                      <td className="px-4 py-3 text-[var(--text-primary)] text-sm">
                        {formatDateShort(req.sdate)}
                        {isFutureRequest && <span className="ml-2 text-[10px] bg-blue-500 text-white px-1.5 py-0.5 rounded-full">예정</span>}
                      </td>
                      <td className="px-4 py-3 text-[var(--text-primary)] text-sm">{formatDateShort(req.edate)}</td>
                      <td className="px-4 py-3 text-center text-[var(--text-primary)] text-sm">{req.HolyDays || 0}</td>
                      <td className="px-4 py-3 text-center text-[var(--text-primary)] text-sm">{req.HolyTimes || 0}</td>
                      <td className="px-4 py-3 text-[var(--text-primary)] text-sm max-w-[150px] truncate">{req.HolyLocation || '-'}</td>
                      <td className="px-4 py-3 text-[var(--text-secondary)] text-sm max-w-xs truncate" title={req.HolyReason || ''}>
                        {req.HolyReason || '-'}
                      </td>
                    </tr>
                  );
                })
              )}
            </tbody>
          </table>
        </div>
      </div>

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

// 통계 카드 컴포넌트 (Local)
/*
interface StatCardProps {
  title: string;
  value: string | number;
  icon: React.ReactNode;
  color: string;
}
*/

/*
function StatCard({ title, value, icon, color }: StatCardProps) {
  return (
    <div className="glass-effect rounded-xl p-4 card-hover">
      <div className="flex items-center">
        <div className={`p-3 rounded-lg ${color.replace('text-', 'bg-').replace('-400', '-500/20')}`}>
          {icon}
        </div>
        <div className="ml-4">
          <p className="text-sm font-medium text-white/70">{title}</p>
          <p className={`text-xl font-bold ${color}`}>{value}</p>
        </div>
      </div>
    </div>
  );
}
*/
