import { useState, useEffect, useCallback, useMemo } from 'react';
import {
  Calendar,
  Search,
  Trash2,
  Clock,
  CheckCircle,
  XCircle,
  RefreshCw,
  Plus,
  Edit,
  Copy,
  Filter
} from 'lucide-react';
import { DateRangePicker } from '@/components/DateRangePicker';
import { UserSelector } from '@/components/UserSelector';
import { comms } from '@/communication';
import { KuntaeModel, HolydayPermission, GroupUser, HolydayBalance } from '@/types';
import { KuntaeEditModal, KuntaeFormData } from '@/components/kuntae/KuntaeEditModal';
import { DevelopmentNotice } from '@/components/DevelopmentNotice';

export function Kuntae() {
  const [kuntaeList, setKuntaeList] = useState<KuntaeModel[]>([]);
  const [loading, setLoading] = useState(false);
  const [processing, setProcessing] = useState(false);
  // 검색 조건
  const [startDate, setStartDate] = useState('');
  const [endDate, setEndDate] = useState('');
  const [selectedUser, setSelectedUser] = useState('%');
  const [filterText, setFilterText] = useState(''); // 클라이언트 필터

  // 권한 및 사용자 목록
  const [permission, setPermission] = useState<HolydayPermission | null>(null);
  const [userList, setUserList] = useState<GroupUser[]>([]);

  // 모달 상태
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [modalMode, setModalMode] = useState<'add' | 'edit' | 'copy'>('add');
  const [selectedItem, setSelectedItem] = useState<KuntaeModel | null>(null);

  // 통계 (잔량 정보)
  const [balances, setBalances] = useState<HolydayBalance[]>([]);

  // 초기화
  useEffect(() => {
    const init = async () => {
      // 날짜 초기화 (현재 월)
      const now = new Date();
      const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
      const endOfMonth = new Date(now.getFullYear(), now.getMonth() + 1, 0);

      const sd = startOfMonth.toISOString().split('T')[0];
      const ed = endOfMonth.toISOString().split('T')[0];

      setStartDate(sd);
      setEndDate(ed);
      console.log("init");
      // 권한 조회
      try {
        const permResponse = await comms.getHolydayPermission();
        console.log('permResponse', permResponse);
        if (permResponse.Success) {
          // @ts-ignore - API 응답 타입 불일치 해결
          const permData = permResponse as any;
          setPermission(permData);

          // 기본값: 로그인된 사용자
          if (permData.CurrentUserId) {
            setSelectedUser(permData.CurrentUserId);
          }
        }
      } catch (error) {
        console.error('권한 조회 오류:', error);
      }
    };
    init();
  }, []);

  // 사용자 목록 로드 (컴포넌트 마운트 시 한 번만 로드하면 됨, 또는 기간과 무관하게 전체 로드 후 필터)
  // 여기서는 getUserList를 사용하므로 startDate/endDate 의존성 제거
  useEffect(() => {
    const loadUsers = async () => {
      try {
        const response = await comms.getUserList('');
        if (response) {
          const today = new Date().toISOString().split('T')[0];
          const filtered = response.filter(u => {
            // 1. 레벨 체크 (1 이상)
            if ((u.level || 0) < 1) return false;
            // 2. 퇴사자 제외
            if (u.outdate && u.outdate < today) return false;
            return true;
          });
          setUserList(filtered);
        }
      } catch (error) {
        console.error('사용자 목록 로드 오류:', error);
      }
    };
    loadUsers();
  }, []);

  // 데이터 및 잔량 로드
  const loadData = useCallback(async () => {
    if (!startDate || !endDate) return;

    // 권한 체크: 관리자(Level 5 이상)가 아닌 경우, 본인 외 조회 불가
    // 초기 로드 시점 등 permission이 아직 없을 수 있으므로 체크
    if (permission) {
      const isManager = (permission.Level || 0) >= 5;
      const currentUserId = permission.CurrentUserId;

      if (!isManager && selectedUser !== currentUserId) {
        alert('조회 권한이 없습니다. 본인 데이터로 조회합니다.');
        setSelectedUser(currentUserId);
        return; // setSelectedUser가 useEffect를 트리거하여 다시 loadData 실행됨
      }
    }

    setLoading(true);
    try {
      // 1. 목록 조회
      const listResponse = await comms.getHolydayList(startDate, endDate, selectedUser);
      if (listResponse.Success && listResponse.Data) {
        setKuntaeList(listResponse.Data);
      } else {
        setKuntaeList([]);
      }

      // 2. 잔량 조회 (연도 기준)
      const year = startDate.substring(0, 4);
      // 전체 사용자(%) 선택 시에는 로그인한 사용자 기준 잔량을 보여주거나, 비워두는 게 맞음
      // 여기서는 선택된 사용자가 있으면 그 사용자, 없으면 본인(권한 없으면 에러나겠지만 API에서 처리)
      const targetUid = selectedUser === '%' ? (permission?.CurrentUserId || '') : selectedUser;

      if (targetUid) {
        const balanceResponse = await comms.getHolydayBalance(year, targetUid);
        if (balanceResponse.Success && balanceResponse.Data) {
          setBalances(balanceResponse.Data);
        } else {
          setBalances([]);
        }
      }

    } catch (error) {
      console.error('데이터 로드 오류:', error);
      alert('데이터를 불러오는 중 오류가 발생했습니다.');
    } finally {
      setLoading(false);
    }
  }, [startDate, endDate, selectedUser, permission]);

  // 초기 로드 및 검색 조건 변경 시 로드
  useEffect(() => {
    loadData();
  }, [loadData]);

  // 필터링된 목록
  const filteredList = useMemo(() => {
    if (!filterText) return kuntaeList;
    const lowerText = filterText.toLowerCase();
    return kuntaeList.filter(item =>
      (item.cate && item.cate.toLowerCase().includes(lowerText)) ||
      (item.contents && item.contents.toLowerCase().includes(lowerText)) ||
      (item.UserName && item.UserName.toLowerCase().includes(lowerText))
    );
  }, [kuntaeList, filterText]);



  // 삭제
  const handleDelete = async (id: number) => {
    if (!confirm('정말로 이 근태 데이터를 삭제하시겠습니까?')) return;

    setProcessing(true);
    try {
      const response = await comms.deleteHolyday(id);
      if (response.Success) {
        alert('삭제되었습니다.');
        loadData();
      } else {
        alert(response.Message || '삭제에 실패했습니다.');
      }
    } catch (error) {
      console.error('삭제 오류:', error);
      alert('서버 연결에 실패했습니다.');
    } finally {
      setProcessing(false);
    }
  };

  // 모달 열기
  const openModal = (mode: 'add' | 'edit' | 'copy', item?: KuntaeModel) => {
    setModalMode(mode);
    setSelectedItem(item || null);
    setIsModalOpen(true);
  };

  // 저장 처리
  const handleSave = async (formData: KuntaeFormData) => {
    try {
      let response;
      if (modalMode === 'add' || modalMode === 'copy') {
        response = await comms.addHolyday(
          formData.cate,
          formData.sdate,
          formData.edate,
          formData.term,
          formData.crtime,
          formData.termDr,
          formData.drTime,
          formData.contents,
          formData.uid || (permission?.CurrentUserId || '')
        );
      } else {
        if (!formData.idx) return;
        response = await comms.editHolyday(
          formData.idx,
          formData.cate,
          formData.sdate,
          formData.edate,
          formData.term,
          formData.crtime,
          formData.termDr,
          formData.drTime,
          formData.contents
        );
      }

      if (response.Success) {
        alert(response.Message || '저장되었습니다.');
        loadData();
      } else {
        alert(response.Message || '저장에 실패했습니다.');
      }
    } catch (error) {
      console.error('저장 오류:', error);
      throw error;
    }
  };

  // 날짜 포맷
  const formatDate = (dateStr: string | null) => {
    if (!dateStr) return '-';
    return dateStr.split('T')[0];
  };

  return (
    <div className="space-y-6 animate-fade-in">
      {/* 개발중 알림 */}
      <DevelopmentNotice />

      {/* 상단 컨트롤 바 */}
      <div className="glass-effect rounded-2xl p-6 relative z-20">
        <div className="flex flex-col space-y-4">

          {/* 1행: 날짜, 사용자, 조회/등록 */}
          <div className="flex flex-col md:flex-row gap-4 items-end md:items-center justify-between">
            {/* 날짜 선택 */}
            <div className="flex items-center gap-2 w-full md:w-auto">
              <DateRangePicker
                startDate={startDate}
                endDate={endDate}
                onChange={(s, e) => {
                  setStartDate(s);
                  setEndDate(e);
                }}
                align="vertical"
              />
            </div>

            {/* 사용자 선택 */}
            <div className="w-full md:w-64">
              <UserSelector
                users={userList.map(u => ({
                  id: u.id,
                  name: u.name,
                  level: u.level,
                  outdate: u.outdate
                }))}
                selectedIds={selectedUser ? [selectedUser] : []}
                onChange={(ids) => setSelectedUser(ids[0] || '')}
                placeholder="사용자 선택"
                className="w-full"
              />
            </div>

            {/* 잔량 정보 (Compact) */}
            <div className="flex items-center gap-2 overflow-x-auto no-scrollbar hidden md:flex">
              {balances.length > 0 ? (
                balances.map((bal, idx) => {
                  const remainDays = bal.TotalGenDays - bal.TotalUseDays;
                  const remainHours = bal.TotalGenHours - bal.TotalUseHours;

                  let icon = <Clock className="w-4 h-4" />;
                  let color = "text-white";
                  if (bal.cate === '연차') {
                    icon = <Calendar className="w-4 h-4 text-primary-400" />;
                    color = "text-primary-400";
                  } else if (bal.cate === '대체') {
                    icon = <RefreshCw className="w-4 h-4 text-success-400" />;
                    color = "text-success-400";
                  } else if (bal.cate === '휴가') {
                    icon = <CheckCircle className="w-4 h-4 text-warning-400" />;
                    color = "text-warning-400";
                  }

                  return (
                    <div key={idx} className="flex items-center gap-2 bg-white/5 border border-white/10 rounded-lg px-3 py-1.5 whitespace-nowrap" title={`발생: ${bal.TotalGenDays} / 사용: ${bal.TotalUseDays}`}>
                      {icon}
                      <span className="text-sm text-white/70">{bal.cate}</span>
                      <span className={`text-sm font-bold ${color}`}>
                        {remainDays}일
                        {remainHours > 0 && <span className="ml-1 text-xs opacity-70">({remainHours}h)</span>}
                      </span>
                    </div>
                  );
                })
              ) : (
                <>
                  <div className="flex items-center gap-2 bg-white/5 border border-white/10 rounded-lg px-3 py-1.5 whitespace-nowrap">
                    <Calendar className="w-4 h-4 text-white/30" />
                    <span className="text-sm text-white/50">연차 -</span>
                  </div>
                  <div className="flex items-center gap-2 bg-white/5 border border-white/10 rounded-lg px-3 py-1.5 whitespace-nowrap">
                    <RefreshCw className="w-4 h-4 text-white/30" />
                    <span className="text-sm text-white/50">대체 -</span>
                  </div>
                </>
              )}
            </div>

            {/* 조회 및 등록 버튼 */}
            <div className="flex gap-2 w-full md:w-auto">
              <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"
              >
                {loading ? <RefreshCw className="w-4 h-4 mr-2 animate-spin" /> : <Search className="w-4 h-4 mr-2" />}
                조회
              </button>
              <button
                onClick={() => openModal('add')}
                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"
              >
                <Plus className="w-4 h-4 mr-2" />
                등록
              </button>
            </div>
          </div>




        </div>
      </div>



      {/* 데이터 테이블 */}
      <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">
              <Clock 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">{filteredList.length}</span>
              <span className="text-[var(--text-secondary)] text-xs">건</span>
              {kuntaeList.length !== filteredList.length && <span className="text-[var(--text-muted)] text-xs ml-1">(전체 {kuntaeList.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-[80px]">구분</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-[var(--text-secondary)] uppercase">시작일</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-[var(--text-secondary)] uppercase">종료일</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-[var(--text-secondary)] uppercase">사용(일)</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-[var(--text-secondary)] uppercase">사용(시간)</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-[var(--text-secondary)] uppercase">내용</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-[var(--text-secondary)] uppercase">성명</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-[var(--text-secondary)] uppercase">소스</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={9} className="px-4 py-8 text-center">
                    <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>
              ) : filteredList.length === 0 ? (
                <tr>
                  <td colSpan={9} className="px-4 py-8 text-center text-[var(--text-secondary)]">
                    {filterText ? '검색 결과가 없습니다.' : '조회된 데이터가 없습니다.'}
                  </td>
                </tr>
              ) : (
                filteredList.map((item) => (
                  <tr key={item.idx} className={`hover:bg-[var(--bg-paper)]/30 transition-colors ${item.extidx ? 'bg-black/20' : ''}`}>
                    <td className="px-4 py-3 text-[var(--text-primary)] text-sm">
                      <span className={`px-2 py-1 rounded text-xs ${item.cate === '연차' ? 'bg-primary-500/20 text-primary-300' :
                        item.cate === '대체' ? 'bg-success-500/20 text-success-300' :
                          'bg-[var(--bg-paper)] text-[var(--text-secondary)]'
                        }`}>
                        {item.cate || '-'}
                      </span>
                    </td>
                    <td className="px-4 py-3 text-[var(--text-primary)] text-sm">{formatDate(item.sdate)}</td>
                    <td className="px-4 py-3 text-[var(--text-primary)] text-sm">{formatDate(item.edate)}</td>
                    <td className="px-4 py-3 text-[var(--text-primary)] text-sm">{item.term > 0 ? item.term : '-'}</td>
                    <td className="px-4 py-3 text-[var(--text-primary)] text-sm">{item.crtime > 0 ? item.crtime : '-'}</td>
                    <td className="px-4 py-3 text-[var(--text-primary)]/80 text-sm max-w-xs truncate" title={item.contents}>
                      {item.contents || '-'}
                    </td>
                    <td className="px-4 py-3 text-[var(--text-primary)] text-sm">
                      {item.UserName || item.uid}
                    </td>
                    <td className="px-4 py-3 text-[var(--text-secondary)] text-xs">
                      {item.extcate ? `${item.extcate}` : '-'}
                    </td>
                    <td className="px-4 py-3 text-sm">
                      <div className="flex items-center space-x-2">
                        <button
                          onClick={() => openModal('edit', item)}
                          className={`text-primary-400 hover:text-primary-300 transition-colors ${item.extidx ? 'opacity-50 cursor-not-allowed' : ''}`}
                          title={item.extidx ? "외부 연동 데이터는 수정할 수 없습니다" : "수정"}
                          disabled={!!item.extidx}
                        >
                          <Edit className="w-4 h-4" />
                        </button>
                        <button
                          onClick={() => openModal('copy', item)}
                          className="text-success-400 hover:text-success-300 transition-colors"
                          title="복사"
                        >
                          <Copy className="w-4 h-4" />
                        </button>
                        <button
                          onClick={() => handleDelete(item.idx)}
                          className={`text-danger-400 hover:text-danger-300 transition-colors ${item.extidx || processing ? 'opacity-50 cursor-not-allowed' : ''}`}
                          title={item.extidx ? "외부 연동 데이터는 삭제할 수 없습니다" : "삭제"}
                          disabled={!!item.extidx || processing}
                        >
                          {processing ? <RefreshCw className="w-4 h-4 animate-spin" /> : <Trash2 className="w-4 h-4" />}
                        </button>
                      </div>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </div>

      {/* 추가/수정 모달 */}
      <KuntaeEditModal
        isOpen={isModalOpen}
        onClose={() => setIsModalOpen(false)}
        onSave={handleSave}
        initialData={selectedItem}
        mode={modalMode}
      />
    </div>
  );
}


