import { useState, useEffect, useCallback } from 'react';
import { createPortal } from 'react-dom';
import { Search, X, Folder, FileText, Check } from 'lucide-react';
import { comms } from '@/communication';
import { ProjectSearchItem } from '@/types';

interface ProjectSearchDialogProps {
  isOpen: boolean;
  onClose: () => void;
  onSelect: (project: { idx: number; name: string }) => void;
  initialSearchKey?: string;
}

export function ProjectSearchDialog({
  isOpen,
  onClose,
  onSelect,
  initialSearchKey = '',
}: ProjectSearchDialogProps) {
  const [projects, setProjects] = useState<ProjectSearchItem[]>([]);
  const [searchKey, setSearchKey] = useState('');
  const [loading, setLoading] = useState(false);
  const [selectedProject, setSelectedProject] = useState<ProjectSearchItem | null>(null);

  // 프로젝트 검색
  const searchProjects = useCallback(async (keyword: string) => {
    if (!keyword.trim()) {
      setProjects([]);
      return;
    }

    setLoading(true);
    try {
      const result = await comms.searchProjects(keyword);
      if (result.Success && result.Data) {
        setProjects(result.Data);
      } else {
        setProjects([]);
      }
    } catch (error) {
      console.error('프로젝트 검색 실패:', error);
      setProjects([]);
    } finally {
      setLoading(false);
    }
  }, []);

  // 다이얼로그 열릴 때 초기화
  useEffect(() => {
    if (isOpen) {
      setSearchKey(initialSearchKey);
      setSelectedProject(null);
      if (initialSearchKey) {
        searchProjects(initialSearchKey);
      } else {
        setProjects([]);
      }
    }
  }, [isOpen, initialSearchKey, searchProjects]);

  // 검색어 변경 시 검색 (디바운스)
  useEffect(() => {
    const timer = setTimeout(() => {
      if (searchKey.trim()) {
        searchProjects(searchKey);
      } else {
        setProjects([]);
      }
    }, 300);
    return () => clearTimeout(timer);
  }, [searchKey, searchProjects]);

  // 선택 확정
  const handleConfirm = () => {
    if (selectedProject) {
      onSelect({ idx: selectedProject.idx, name: selectedProject.name });
      onClose();
    }
  };

  // ESC 키로 닫기
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'Escape' && isOpen) {
        onClose();
      }
    };
    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [isOpen, onClose]);

  if (!isOpen) return null;

  return createPortal(
    <div
      className="fixed inset-0 bg-black/60 flex items-center justify-center z-[60]"
      onMouseDown={onClose}
    >
      <div
        className="glass-effect rounded-xl w-full max-w-2xl max-h-[80vh] overflow-hidden flex flex-col"
        onMouseDown={(e) => e.stopPropagation()}
      >
        {/* 헤더 */}
        <div className="p-4 border-b border-white/10 flex items-center justify-between shrink-0">
          <div className="flex items-center gap-2">
            <Folder className="w-5 h-5 text-primary-400" />
            <h2 className="text-lg font-semibold text-white">프로젝트/항목 검색</h2>
          </div>
          <button
            onClick={onClose}
            className="text-white/60 hover:text-white transition-colors"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* 검색 */}
        <div className="p-4 border-b border-white/10 shrink-0">
          <div className="relative">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-white/50" />
            <input
              type="text"
              value={searchKey}
              onChange={(e) => setSearchKey(e.target.value)}
              placeholder="프로젝트명 또는 번호로 검색..."
              autoFocus
              className="w-full pl-10 pr-4 py-2 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/50 focus:outline-none focus:ring-2 focus:ring-primary-400"
            />
          </div>
        </div>

        {/* 프로젝트 목록 */}
        <div className="flex-1 overflow-y-auto p-2">
          {loading ? (
            <div className="text-center py-8">
              <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-primary-400 mx-auto mb-2"></div>
              <p className="text-white/50">검색 중...</p>
            </div>
          ) : projects.length === 0 ? (
            <div className="text-center py-8 text-white/50">
              {searchKey ? '검색 결과가 없습니다' : '검색어를 입력하세요'}
            </div>
          ) : (
            <div className="space-y-1">
              {projects.map((project, index) => (
                <button
                  key={`${project.source}-${project.idx}-${index}`}
                  onClick={() => setSelectedProject(project)}
                  onDoubleClick={() => {
                    setSelectedProject(project);
                    onSelect({ idx: project.idx, name: project.name });
                    onClose();
                  }}
                  className={`w-full text-left px-4 py-3 rounded-lg transition-colors flex items-center gap-3 ${
                    selectedProject?.idx === project.idx && selectedProject?.name === project.name
                      ? 'bg-primary-500/30 border border-primary-400/50'
                      : 'bg-white/5 hover:bg-white/10 border border-transparent'
                  }`}
                >
                  {/* 아이콘 */}
                  <div className={`shrink-0 ${project.source === 'project' ? 'text-blue-400' : 'text-gray-400'}`}>
                    {project.source === 'project' ? (
                      <Folder className="w-5 h-5" />
                    ) : (
                      <FileText className="w-5 h-5" />
                    )}
                  </div>

                  {/* 정보 */}
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2">
                      {project.idx > 0 && (
                        <span className="text-xs text-white/40 font-mono">[{project.idx}]</span>
                      )}
                      <span className="font-medium text-white truncate">{project.name}</span>
                      {project.status && (
                        <span className={`text-xs px-1.5 py-0.5 rounded ${
                          project.status === '진행' ? 'bg-green-500/20 text-green-400' :
                          project.status === '준비' ? 'bg-yellow-500/20 text-yellow-400' :
                          'bg-gray-500/20 text-gray-400'
                        }`}>
                          {project.status}
                        </span>
                      )}
                    </div>
                    <div className="text-xs text-white/50 mt-0.5 truncate">
                      {project.source === 'project' ? (
                        <>
                          {project.userManager && `담당: ${project.userManager}`}
                          {project.userMain && ` | 챔피언: ${project.userMain}`}
                        </>
                      ) : (
                        <>
                          과거 등록 항목
                          {project.lastDate && ` | 최근: ${project.lastDate}`}
                        </>
                      )}
                    </div>
                  </div>

                  {/* 선택 체크 */}
                  {selectedProject?.idx === project.idx && selectedProject?.name === project.name && (
                    <Check className="w-5 h-5 text-primary-400 shrink-0" />
                  )}
                </button>
              ))}
            </div>
          )}
        </div>

        {/* 푸터 */}
        <div className="p-4 border-t border-white/10 flex items-center justify-between shrink-0">
          <span className="text-sm text-white/50">
            {projects.length}건
            {selectedProject && ` | 선택: ${selectedProject.name}`}
          </span>
          <div className="flex gap-2">
            <button
              onClick={onClose}
              className="px-4 py-2 bg-white/10 hover:bg-white/20 rounded-lg text-white transition-colors"
            >
              취소
            </button>
            <button
              onClick={handleConfirm}
              disabled={!selectedProject}
              className="px-4 py-2 bg-primary-500 hover:bg-primary-600 disabled:opacity-50 disabled:cursor-not-allowed rounded-lg text-white transition-colors"
            >
              선택
            </button>
          </div>
        </div>
      </div>
    </div>,
    document.body
  );
}
