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

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<HolydayUser[]>([]);

  // 모달 상태
  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);

      // 권한 조회
      try {
        const permResponse = await comms.getHolydayPermission();
        if (permResponse.Success && permResponse.Data) {
          // @ts-ignore - API 응답 타입 불일치 해결
          setPermission(permResponse.Data);
        }
      } catch (error) {
        console.error('권한 조회 오류:', error);
      }
    };
    init();
  }, []);

  // 사용자 목록 로드 (기간 변경 시)
  useEffect(() => {
    const loadUsers = async () => {
      if (!startDate || !endDate) return;
      try {
        const response = await comms.getHolydayUserList(startDate, endDate);
        // @ts-ignore - API 응답이 배열로 옴
        if (Array.isArray(response)) {
          setUserList(response);
        } else if (response.Success && response.Data) {
          // @ts-ignore
          setUserList(response.Data);
        }
      } catch (error) {
        console.error('사용자 목록 로드 오류:', error);
      }
    };
    loadUsers();
  }, [startDate, endDate]);

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

    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 moveMonth = (offset: number) => {
    const current = new Date(startDate);
    current.setMonth(current.getMonth() + offset);

    const startOfMonth = new Date(current.getFullYear(), current.getMonth(), 1);
    const endOfMonth = new Date(current.getFullYear(), current.getMonth() + 1, 0);

    setStartDate(startOfMonth.toISOString().split('T')[0]);
    setEndDate(endOfMonth.toISOString().split('T')[0]);
  };

  // 삭제
  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">
      {/* 상단 컨트롤 바 */}
      <div className="glass-effect rounded-2xl p-6">
        <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">
              <button
                onClick={() => moveMonth(-1)}
                className="p-2 rounded-lg hover:bg-white/10 text-white/70 hover:text-white transition-colors"
              >
                <ChevronLeft className="w-5 h-5" />
              </button>

              <div className="grid grid-cols-2 gap-2">
                <input
                  type="date"
                  value={startDate}
                  onChange={(e) => setStartDate(e.target.value)}
                  className="bg-white/20 border border-white/30 rounded-lg px-3 py-2 text-white focus:outline-none focus:ring-2 focus:ring-primary-400 text-sm"
                />
                <input
                  type="date"
                  value={endDate}
                  onChange={(e) => setEndDate(e.target.value)}
                  className="bg-white/20 border border-white/30 rounded-lg px-3 py-2 text-white focus:outline-none focus:ring-2 focus:ring-primary-400 text-sm"
                />
              </div>

              <button
                onClick={() => moveMonth(1)}
                className="p-2 rounded-lg hover:bg-white/10 text-white/70 hover:text-white transition-colors"
              >
                <ChevronRight className="w-5 h-5" />
              </button>
            </div>

            {/* 사용자 선택 (관리자용) */}
            {permission?.CanManage && (
              <div className="w-full md:w-64">
                <div className="relative">
                  <User className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-white/50" />
                  <select
                    value={selectedUser}
                    onChange={(e) => setSelectedUser(e.target.value)}
                    className="w-full bg-white/20 border border-white/30 rounded-lg pl-10 pr-4 py-2 text-white focus:outline-none focus:ring-2 focus:ring-primary-400 appearance-none"
                  >
                    <option value="%" className="bg-[#1e1e2e]">전체 사용자</option>
                    {userList.map(user => (
                      <option key={user.uid} value={user.uid} className="bg-[#1e1e2e]">
                        {user.UserName} ({user.uid})
                      </option>
                    ))}
                  </select>
                </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>

          {/* 2행: 검색 필터 */}
          <div className="flex items-center gap-2">
            <div className="relative flex-1 max-w-md">
              <Filter className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-white/50" />
              <input
                type="text"
                value={filterText}
                onChange={(e) => setFilterText(e.target.value)}
                placeholder="구분, 내용, 성명으로 검색..."
                className="w-full bg-white/10 border border-white/20 rounded-lg pl-10 pr-4 py-2 text-white focus:outline-none focus:ring-2 focus:ring-primary-400 text-sm placeholder-white/30"
              />
              {filterText && (
                <button
                  onClick={() => setFilterText('')}
                  className="absolute right-3 top-1/2 transform -translate-y-1/2 text-white/50 hover:text-white"
                >
                  <XCircle className="w-4 h-4" />
                </button>
              )}
            </div>
          </div>
        </div>
      </div>

      {/* 통계 카드 (잔량 정보) */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        {balances.length > 0 ? (
          balances.map((bal, idx) => {
            // 잔량 계산
            const remainDays = bal.TotalGenDays - bal.TotalUseDays;
            const remainHours = bal.TotalGenHours - bal.TotalUseHours;

            // 아이콘 및 색상 결정
            let icon = <Clock className="w-6 h-6" />;
            let color = "text-white";

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

            return (
              <StatCard
                key={idx}
                title={`${bal.cate} 잔량`}
                value={`${remainDays}일 ${remainHours > 0 ? `(${remainHours}h)` : ''}`}
                subValue={`발생: ${bal.TotalGenDays} / 사용: ${bal.TotalUseDays}`}
                icon={icon}
                color={color}
              />
            );
          })
        ) : (
          // 데이터 없을 때 기본 카드 표시
          <>
            <StatCard title="연차 잔량" value="-" icon={<Calendar className="w-6 h-6 text-white/30" />} color="text-white/30" />
            <StatCard title="대체 잔량" value="-" icon={<RefreshCw className="w-6 h-6 text-white/30" />} color="text-white/30" />
          </>
        )}
      </div>

      {/* 데이터 테이블 */}
      <div className="glass-effect rounded-2xl overflow-hidden">
        <div className="px-6 py-4 border-b border-white/10 flex justify-between items-center">
          <h3 className="text-lg font-semibold text-white">근태 상세 내역</h3>
          <span className="text-white/50 text-sm">
            총 {filteredList.length}건
            {kuntaeList.length !== filteredList.length && ` (전체 ${kuntaeList.length}건 중)`}
          </span>
        </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">구분</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-white/70 uppercase">시작일</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-white/70 uppercase">종료일</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-white/70 uppercase">사용(일)</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-white/70 uppercase">사용(시간)</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-white/70 uppercase">내용</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-white/70 uppercase">성명</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-white/70 uppercase">소스</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/10">
              {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-white/50" />
                      <span className="text-white/50">데이터를 불러오는 중...</span>
                    </div>
                  </td>
                </tr>
              ) : filteredList.length === 0 ? (
                <tr>
                  <td colSpan={9} className="px-4 py-8 text-center text-white/50">
                    {filterText ? '검색 결과가 없습니다.' : '조회된 데이터가 없습니다.'}
                  </td>
                </tr>
              ) : (
                filteredList.map((item) => (
                  <tr key={item.idx} className={`hover:bg-white/5 transition-colors ${item.extidx ? 'bg-black/20' : ''}`}>
                    <td className="px-4 py-3 text-white 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-white/10 text-white/70'
                        }`}>
                        {item.cate || '-'}
                      </span>
                    </td>
                    <td className="px-4 py-3 text-white text-sm">{formatDate(item.sdate)}</td>
                    <td className="px-4 py-3 text-white text-sm">{formatDate(item.edate)}</td>
                    <td className="px-4 py-3 text-white text-sm">{item.term > 0 ? item.term : '-'}</td>
                    <td className="px-4 py-3 text-white text-sm">{item.crtime > 0 ? item.crtime : '-'}</td>
                    <td className="px-4 py-3 text-white/80 text-sm max-w-xs truncate" title={item.contents}>
                      {item.contents || '-'}
                    </td>
                    <td className="px-4 py-3 text-white text-sm">
                      {item.UserName || item.uid}
                    </td>
                    <td className="px-4 py-3 text-white/50 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 ? 'opacity-50 cursor-not-allowed' : ''}`}
                          title={item.extidx ? "외부 연동 데이터는 삭제할 수 없습니다" : "삭제"}
                          disabled={!!item.extidx}
                        >
                          <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>
  );
}

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

function StatCard({ title, value, subValue, 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>
          {subValue && <p className="text-xs text-white/40 mt-1">{subValue}</p>}
        </div>
      </div>
    </div>
  );
}
