import { useState, useEffect, useMemo } from 'react';
import { X, ChevronRight, ChevronDown, Search } from 'lucide-react';
import { createPortal } from 'react-dom';
import { comms } from '@/communication';
import { JobTypeItem } from '@/types';

interface JobTypeSelectModalProps {
  isOpen: boolean;
  currentProcess?: string;
  currentJobgrp?: string;
  currentType?: string;
  onClose: () => void;
  onSelect: (process: string, jobgrp: string, type: string) => void;
}

interface TreeNode {
  name: string;
  children?: TreeNode[];
  item?: JobTypeItem;
}

export function JobTypeSelectModal({
  isOpen,
  currentProcess,
  currentJobgrp,
  currentType,
  onClose,
  onSelect,
}: JobTypeSelectModalProps) {
  const [jobTypes, setJobTypes] = useState<JobTypeItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [searchKey, setSearchKey] = useState('');
  const [expandedNodes, setExpandedNodes] = useState<Set<string>>(new Set());
  const [selectedPath, setSelectedPath] = useState<string>('');

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

  // 데이터 로드
  useEffect(() => {
    if (!isOpen) return;

    const loadJobTypes = async () => {
      setLoading(true);
      try {
        const response = await comms.getJobTypes('');
        if (response.Success && response.Data) {
          setJobTypes(response.Data);

          // 모든 노드 확장
          const allExpanded = new Set<string>();
          response.Data.forEach((item) => {
            const process = item.process || 'N/A';
            const jobgrp = item.jobgrp || 'N/A';
            allExpanded.add(process);
            allExpanded.add(`${process}|${jobgrp}`);
          });
          setExpandedNodes(allExpanded);

          // 현재 선택된 항목이 있으면 선택 표시
          if (currentType) {
            setSelectedPath(`${currentProcess || 'N/A'}|${currentJobgrp || 'N/A'}|${currentType}`);
          }
        }
      } catch (error) {
        console.error('업무형태 로드 오류:', error);
      } finally {
        setLoading(false);
      }
    };

    loadJobTypes();
  }, [isOpen, currentProcess, currentJobgrp, currentType]);

  // 트리 구조 생성
  const treeData = useMemo(() => {
    const processMap = new Map<string, Map<string, JobTypeItem[]>>();

    // 검색 필터 적용
    const filteredTypes = searchKey
      ? jobTypes.filter(
          (item) =>
            item.type?.toLowerCase().includes(searchKey.toLowerCase()) ||
            item.jobgrp?.toLowerCase().includes(searchKey.toLowerCase()) ||
            item.process?.toLowerCase().includes(searchKey.toLowerCase())
        )
      : jobTypes;

    // 그룹핑
    filteredTypes.forEach((item) => {
      const process = item.process || 'N/A';
      const jobgrp = item.jobgrp || 'N/A';

      if (!processMap.has(process)) {
        processMap.set(process, new Map());
      }
      const grpMap = processMap.get(process)!;
      if (!grpMap.has(jobgrp)) {
        grpMap.set(jobgrp, []);
      }
      grpMap.get(jobgrp)!.push(item);
    });

    // 트리 노드 생성
    const tree: TreeNode[] = [];
    processMap.forEach((grpMap, processName) => {
      const processNode: TreeNode = {
        name: processName,
        children: [],
      };

      grpMap.forEach((items, grpName) => {
        const grpNode: TreeNode = {
          name: grpName,
          children: items.map((item) => ({
            name: item.type,
            item,
          })),
        };
        processNode.children!.push(grpNode);
      });

      tree.push(processNode);
    });

    // 정렬
    tree.sort((a, b) => a.name.localeCompare(b.name));
    tree.forEach((p) => {
      p.children?.sort((a, b) => a.name.localeCompare(b.name));
      p.children?.forEach((g) => {
        g.children?.sort((a, b) => a.name.localeCompare(b.name));
      });
    });

    return tree;
  }, [jobTypes, searchKey]);

  // 검색 시 모든 노드 확장
  useEffect(() => {
    if (searchKey && treeData.length > 0) {
      const allExpanded = new Set<string>();
      treeData.forEach((processNode) => {
        allExpanded.add(processNode.name);
        processNode.children?.forEach((grpNode) => {
          allExpanded.add(`${processNode.name}|${grpNode.name}`);
        });
      });
      setExpandedNodes(allExpanded);
    }
  }, [searchKey, treeData]);

  // 노드 토글
  const toggleNode = (path: string) => {
    setExpandedNodes((prev) => {
      const newSet = new Set(prev);
      if (newSet.has(path)) {
        newSet.delete(path);
      } else {
        newSet.add(path);
      }
      return newSet;
    });
  };

  // 항목 더블클릭
  const handleDoubleClick = (item: JobTypeItem) => {
    // 원본 값 그대로 전달 (N/A 변환은 상위에서 처리)
    onSelect(item.process || '', item.jobgrp || '', item.type);
    onClose();
  };

  // 선택 버튼 클릭
  const handleSelectClick = () => {
    if (selectedPath) {
      const parts = selectedPath.split('|');
      if (parts.length === 3) {
        // N/A 값은 빈 문자열로 변환하여 전달 (상위에서 처리)
        const process = parts[0] === 'N/A' ? '' : parts[0];
        const jobgrp = parts[1] === 'N/A' ? '' : parts[1];
        onSelect(process, jobgrp, parts[2]);
        onClose();
      }
    }
  };

  if (!isOpen) return null;

  return createPortal(
    <div
      className="fixed inset-0 bg-black/50 backdrop-blur-sm z-[60]"
      onMouseDown={onClose}
    >
      <div className="flex items-center justify-center min-h-screen p-4">
        <div
          className="glass-effect rounded-2xl w-full max-w-2xl animate-slide-up max-h-[85vh] flex flex-col"
          onMouseDown={(e) => e.stopPropagation()}
        >
          {/* 헤더 */}
          <div className="px-6 py-4 border-b border-white/10 flex items-center justify-between">
            <h2 className="text-xl font-semibold text-white">업무형태 선택</h2>
            <button
              onClick={onClose}
              className="text-white/70 hover:text-white transition-colors"
            >
              <X className="w-6 h-6" />
            </button>
          </div>

          {/* 검색 */}
          <div className="px-6 py-3 border-b border-white/10">
            <div className="relative">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-white/50" />
              <input
                type="text"
                value={searchKey}
                onChange={(e) => setSearchKey(e.target.value)}
                placeholder="검색어를 입력하세요..."
                className="w-full bg-white/10 border border-white/20 rounded-lg pl-10 pr-4 py-2 text-white placeholder-white/50 focus:outline-none focus:ring-2 focus:ring-primary-400"
                autoFocus
              />
            </div>
          </div>

          {/* 트리뷰 */}
          <div className="flex-1 overflow-y-auto p-4">
            {loading ? (
              <div className="text-white/50 text-center py-8">로딩 중...</div>
            ) : treeData.length === 0 ? (
              <div className="text-white/50 text-center py-8">
                {searchKey ? '검색 결과가 없습니다' : '업무형태가 없습니다'}
              </div>
            ) : (
              <div className="space-y-1">
                {treeData.map((processNode) => (
                  <div key={processNode.name} className="border border-white/10 rounded-lg overflow-hidden mb-2">
                    {/* 공정 레벨 */}
                    <button
                      className="flex items-center w-full px-3 py-2 text-left bg-white/5 hover:bg-white/10 transition-colors"
                      onClick={() => toggleNode(processNode.name)}
                    >
                      {expandedNodes.has(processNode.name) ? (
                        <ChevronDown className="w-4 h-4 mr-2 text-primary-400" />
                      ) : (
                        <ChevronRight className="w-4 h-4 mr-2 text-white/50" />
                      )}
                      <span className="font-semibold text-primary-300">{processNode.name}</span>
                      <span className="ml-2 text-xs text-white/40">
                        ({processNode.children?.reduce((acc, g) => acc + (g.children?.length || 0), 0) || 0}건)
                      </span>
                    </button>

                    {/* 업무분류 레벨 */}
                    {expandedNodes.has(processNode.name) && processNode.children && (
                      <div className="border-t border-white/10">
                        {processNode.children.map((grpNode) => {
                          const grpPath = `${processNode.name}|${grpNode.name}`;
                          return (
                            <div key={grpPath} className="border-b border-white/5 last:border-b-0">
                              <button
                                className="flex items-center w-full px-4 py-1.5 text-left bg-white/5 hover:bg-white/10 transition-colors"
                                onClick={() => toggleNode(grpPath)}
                              >
                                {expandedNodes.has(grpPath) ? (
                                  <ChevronDown className="w-3 h-3 mr-2 text-white/50" />
                                ) : (
                                  <ChevronRight className="w-3 h-3 mr-2 text-white/40" />
                                )}
                                <span className="text-white/80">{grpNode.name}</span>
                                <span className="ml-2 text-xs text-white/40">
                                  ({grpNode.children?.length || 0})
                                </span>
                              </button>

                              {/* 업무형태 레벨 */}
                              {expandedNodes.has(grpPath) && grpNode.children && (
                                <div className="bg-black/20 py-1">
                                  {grpNode.children.map((typeNode) => {
                                    const typePath = `${grpPath}|${typeNode.name}`;
                                    const isSelected = selectedPath === typePath;
                                    return (
                                      <button
                                        key={typePath}
                                        className={`w-full px-8 py-1.5 text-left transition-colors ${
                                          isSelected
                                            ? 'bg-primary-500/40 text-primary-200'
                                            : 'text-white/70 hover:bg-white/10 hover:text-white'
                                        }`}
                                        onClick={() => setSelectedPath(typePath)}
                                        onDoubleClick={() => typeNode.item && handleDoubleClick(typeNode.item)}
                                      >
                                        • {typeNode.name}
                                      </button>
                                    );
                                  })}
                                </div>
                              )}
                            </div>
                          );
                        })}
                      </div>
                    )}
                  </div>
                ))}
              </div>
            )}
          </div>

          {/* 선택된 항목 표시 (WinForms과 동일: type ← jobgrp) */}
          {selectedPath && (
            <div className="px-6 py-3 border-t border-white/10 bg-primary-500/10">
              <div className="text-sm">
                <span className="text-white/50">선택: </span>
                <span className="text-primary-300 font-medium">
                  {(() => {
                    const parts = selectedPath.split('|');
                    // parts[0]=process, parts[1]=jobgrp, parts[2]=type
                    const type = parts[2] || '';
                    const jobgrp = parts[1] || '';
                    if (jobgrp && jobgrp !== 'N/A') {
                      return `${type} ← ${jobgrp}`;
                    }
                    return type;
                  })()}
                </span>
              </div>
            </div>
          )}

          {/* 푸터 */}
          <div className="px-6 py-4 border-t border-white/10 flex justify-end space-x-3">
            <button
              onClick={onClose}
              className="bg-white/20 hover:bg-white/30 text-white px-4 py-2 rounded-lg transition-colors"
            >
              취소
            </button>
            <button
              onClick={handleSelectClick}
              disabled={!selectedPath}
              className="bg-primary-500 hover:bg-primary-600 text-white px-6 py-2 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
            >
              선택
            </button>
          </div>
        </div>
      </div>
    </div>,
    document.body
  );
}
