// ============================================================
// 기능정의문서 패널 컴포넌트
// 현재 화면의 UI별 기능을 번호 붙여서 스크롤 가능하게 표시
// 상세 인터랙션/상태값 표시 지원
// ============================================================
import React, { useState, useMemo } from 'react';
import {
  X,
  ChevronDown,
  ChevronRight,
  FileText,
  MousePointer,
  AlertCircle,
  Database,
  ArrowRight,
  CheckCircle2,
  Zap,
  List,
  Hash,
  Play,
  RefreshCw,
  Eye,
} from 'lucide-react';

// 요소 타입 한글 변환
const elementTypeLabels = {
  button: '버튼',
  input: '입력',
  select: '선택',
  table: '테이블',
  card: '카드',
  checkbox: '체크박스',
  column: '컬럼',
  text: '텍스트',
  display: '표시',
  date: '날짜',
  number: '숫자',
  textarea: '텍스트영역',
  link: '링크',
  badge: '뱃지',
  tab: '탭',
  modal: '모달',
  'row-action': '행 액션',
  section: '섹션',
};

// 메인 기능정의문서 패널 - 번호 붙여서 스크롤 표시
const FeatureDocPanel = ({ isOpen, onClose, screenFeatures, currentScreenName, onBadgeHover }) => {
  const [expandedItems, setExpandedItems] = useState({});
  const [hoveredNumber, setHoveredNumber] = useState(null);

  // 모든 요소에 순차 번호 부여
  const numberedElements = useMemo(() => {
    if (!screenFeatures?.sections) return [];

    const elements = [];
    let globalIndex = 1;

    screenFeatures.sections.forEach((section, sectionIdx) => {
      // 섹션 헤더 추가
      elements.push({
        type: 'section-header',
        sectionIndex: sectionIdx + 1,
        title: section.title,
        description: section.description,
        layout: section.layout,
        condition: section.condition,
        elementCount: section.elements?.length || 0,
      });

      // 섹션 내 요소들
      section.elements?.forEach((element) => {
        elements.push({
          type: 'element',
          number: globalIndex++,
          sectionIndex: sectionIdx + 1,
          elementType: element.type,
          ...element,
        });

        // 하위 요소가 있으면 추가
        if (element.elements && element.elements.length > 0) {
          element.elements.forEach((subElement) => {
            elements.push({
              type: 'sub-element',
              number: globalIndex++,
              sectionIndex: sectionIdx + 1,
              parentLabel: element.label,
              elementType: subElement.type,
              ...subElement,
            });
          });
        }
      });
    });

    return elements;
  }, [screenFeatures]);

  const toggleExpand = (key) => {
    setExpandedItems(prev => ({
      ...prev,
      [key]: !prev[key]
    }));
  };

  // 마우스 호버 시 뱃지 하이라이트
  const handleItemHover = (number) => {
    setHoveredNumber(number);
    if (onBadgeHover) {
      onBadgeHover(number);
    }
  };

  const handleItemLeave = () => {
    setHoveredNumber(null);
    if (onBadgeHover) {
      onBadgeHover(null);
    }
  };

  if (!isOpen) return null;

  // 화면 데이터가 없는 경우
  if (!screenFeatures) {
    return (
      <div className="w-80 bg-white border-r flex flex-col h-full shadow-lg">
        <div className="flex items-center justify-between p-3 border-b bg-indigo-600 text-white">
          <div className="flex items-center gap-2">
            <FileText className="w-4 h-4" />
            <span className="font-bold text-sm">기능정의문서</span>
          </div>
          <button onClick={onClose} className="p-1 hover:bg-white/20 rounded">
            <X className="w-4 h-4" />
          </button>
        </div>

        <div className="flex-1 flex items-center justify-center p-6">
          <div className="text-center">
            <AlertCircle className="w-10 h-10 text-gray-300 mx-auto mb-2" />
            <p className="text-sm text-gray-500">현재 화면의</p>
            <p className="text-sm text-gray-500">기능정의가 없습니다.</p>
            <p className="text-xs text-gray-400 mt-2">화면: {currentScreenName || '-'}</p>
          </div>
        </div>
      </div>
    );
  }

  // action 객체를 렌더링하는 함수
  const renderAction = (action) => {
    if (!action) return null;

    // action이 문자열인 경우 (구버전 호환)
    if (typeof action === 'string') {
      return (
        <div className="flex items-start gap-1.5 text-xs">
          <span className="text-green-500 font-medium w-12 flex-shrink-0">동작</span>
          <span className="text-gray-700">{action}</span>
        </div>
      );
    }

    // action이 객체인 경우 (신버전)
    return (
      <div className="space-y-1">
        {action.trigger && (
          <div className="flex items-start gap-1.5 text-xs">
            <span className="text-blue-500 font-medium w-12 flex-shrink-0">트리거</span>
            <span className="text-gray-700">{action.trigger}</span>
          </div>
        )}
        {action.behavior && (
          <div className="flex items-start gap-1.5 text-xs">
            <span className="text-green-500 font-medium w-12 flex-shrink-0">동작</span>
            <span className="text-gray-700">{action.behavior}</span>
          </div>
        )}
        {action.result && (
          <div className="flex items-start gap-1.5 text-xs">
            <span className="text-purple-500 font-medium w-12 flex-shrink-0">결과</span>
            <span className="text-gray-700">{action.result}</span>
          </div>
        )}
        {action.api && (
          <div className="flex items-start gap-1.5 text-xs">
            <span className="text-orange-500 font-medium w-12 flex-shrink-0">API</span>
            <span className="text-gray-700 font-mono text-[11px] bg-orange-50 px-1 rounded">{action.api}</span>
          </div>
        )}
        {action.navigation && (
          <div className="flex items-start gap-1.5 text-xs">
            <span className="text-cyan-500 font-medium w-12 flex-shrink-0">이동</span>
            <span className="text-gray-700 font-mono text-[11px] bg-cyan-50 px-1 rounded">{action.navigation}</span>
          </div>
        )}
      </div>
    );
  };

  // states 배열을 렌더링하는 함수
  const renderStates = (states) => {
    if (!states || !Array.isArray(states) || states.length === 0) return null;

    return (
      <div className="mt-1.5 space-y-1">
        <div className="flex items-center gap-1 text-xs text-gray-500 font-medium">
          <RefreshCw className="w-3 h-3" />
          <span>상태 변화</span>
        </div>
        <div className="ml-4 space-y-1">
          {states.map((st, idx) => (
            <div key={idx} className="flex items-start gap-1.5 text-xs bg-gray-50 p-1.5 rounded">
              <span className={`px-1.5 py-0.5 rounded font-medium flex-shrink-0 ${
                st.state === '기본' ? 'bg-gray-200 text-gray-600' :
                st.state === '호버' ? 'bg-blue-100 text-blue-600' :
                st.state === '활성' ? 'bg-green-100 text-green-600' :
                st.state === '선택됨' ? 'bg-indigo-100 text-indigo-600' :
                st.state === '비활성' ? 'bg-gray-100 text-gray-400' :
                st.state === '에러' ? 'bg-red-100 text-red-600' :
                st.state === '로딩' ? 'bg-yellow-100 text-yellow-600' :
                'bg-purple-100 text-purple-600'
              }`}>
                {st.state}
              </span>
              <div className="flex-1">
                {st.condition && (
                  <p className="text-gray-500 text-[10px]">조건: {st.condition}</p>
                )}
                {st.display && (
                  <p className="text-gray-700 text-[10px]">{st.display}</p>
                )}
              </div>
            </div>
          ))}
        </div>
      </div>
    );
  };

  return (
    <div className="w-80 bg-white border-r flex flex-col h-full shadow-lg">
      {/* 헤더 */}
      <div className="flex items-center justify-between p-3 border-b bg-indigo-600 text-white flex-shrink-0">
        <div className="flex items-center gap-2">
          <FileText className="w-4 h-4" />
          <span className="font-bold text-sm">기능정의문서</span>
        </div>
        <button onClick={onClose} className="p-1 hover:bg-white/20 rounded">
          <X className="w-4 h-4" />
        </button>
      </div>

      {/* 화면 정보 */}
      <div className="p-3 bg-gray-50 border-b flex-shrink-0">
        <h2 className="font-bold text-base text-gray-900">{screenFeatures.screenName}</h2>
        <p className="text-xs text-gray-500 mt-0.5">{screenFeatures.menuPath}</p>
        <div className="flex items-center gap-2 mt-2">
          <span className={`text-xs px-2 py-0.5 rounded font-medium ${
            screenFeatures.screenType === 'list' ? 'bg-blue-100 text-blue-700' :
            screenFeatures.screenType === 'form' ? 'bg-green-100 text-green-700' :
            'bg-purple-100 text-purple-700'
          }`}>
            {screenFeatures.screenType === 'list' ? '목록 화면' :
             screenFeatures.screenType === 'form' ? '등록/수정 화면' : '상세 화면'}
          </span>
          <span className="text-xs text-gray-400">
            {numberedElements.filter(e => e.type !== 'section-header').length}개 기능
          </span>
        </div>
        {screenFeatures.description && (
          <p className="text-xs text-gray-600 mt-2 p-2 bg-white rounded border leading-relaxed">
            {screenFeatures.description}
          </p>
        )}
      </div>

      {/* 기능 목록 - 번호 붙여서 스크롤 */}
      <div className="flex-1 overflow-y-auto">
        {numberedElements.map((item, idx) => {
          // 섹션 헤더
          if (item.type === 'section-header') {
            return (
              <div key={`section-${item.sectionIndex}`} className="sticky top-0 z-10">
                <div className="px-3 py-2 bg-gray-100 border-b border-t flex items-center gap-2">
                  <span className="w-5 h-5 rounded bg-indigo-600 text-white text-xs flex items-center justify-center font-bold">
                    {item.sectionIndex}
                  </span>
                  <span className="font-semibold text-sm text-gray-800">{item.title}</span>
                  <span className="text-xs text-gray-400 ml-auto">{item.elementCount}개</span>
                </div>
                {item.description && (
                  <div className="px-3 py-1.5 bg-gray-50 border-b text-xs text-gray-600">
                    {item.description}
                  </div>
                )}
              </div>
            );
          }

          // 요소 항목
          const isSubElement = item.type === 'sub-element';
          const isExpanded = expandedItems[`item-${item.number}`];
          const hasDetails = item.description || item.action || item.validation ||
                           item.dataSource || item.condition || item.options || item.style ||
                           (item.states && item.states.length > 0);
          const isHovered = hoveredNumber === item.number;

          return (
            <div
              key={`item-${item.number}`}
              className={`border-b transition-colors ${isSubElement ? 'bg-gray-50/50' : 'bg-white'} ${isHovered ? 'bg-indigo-50 ring-1 ring-indigo-300' : ''}`}
              onMouseEnter={() => handleItemHover(item.number)}
              onMouseLeave={handleItemLeave}
            >
              {/* 기본 정보 행 */}
              <div
                className={`flex items-start gap-2 px-3 py-2 cursor-pointer hover:bg-blue-50/50 ${isSubElement ? 'pl-8' : ''}`}
                onClick={() => hasDetails && toggleExpand(`item-${item.number}`)}
              >
                {/* 번호 */}
                <span className={`w-6 h-6 rounded-full flex items-center justify-center text-xs font-bold flex-shrink-0 transition-all ${
                  isHovered
                    ? 'bg-indigo-600 text-white ring-2 ring-indigo-300 scale-110'
                    : isSubElement
                      ? 'bg-gray-200 text-gray-600'
                      : 'bg-indigo-100 text-indigo-700'
                }`}>
                  {item.number}
                </span>

                {/* 내용 */}
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-1.5 flex-wrap">
                    <span className="font-medium text-sm text-gray-900">
                      {item.label || item.id}
                    </span>
                    <span className="text-[10px] px-1.5 py-0.5 rounded bg-gray-100 text-gray-500">
                      {elementTypeLabels[item.elementType] || item.elementType || item.type}
                    </span>
                    {item.required && (
                      <span className="text-[10px] px-1.5 py-0.5 rounded bg-red-100 text-red-600">필수</span>
                    )}
                    {item.readOnly && (
                      <span className="text-[10px] px-1.5 py-0.5 rounded bg-gray-100 text-gray-500">읽기전용</span>
                    )}
                  </div>
                  {isSubElement && item.parentLabel && (
                    <p className="text-[10px] text-gray-400 mt-0.5">상위: {item.parentLabel}</p>
                  )}
                </div>

                {/* 확장 아이콘 */}
                {hasDetails && (
                  <div className="flex-shrink-0">
                    {isExpanded ? (
                      <ChevronDown className="w-4 h-4 text-gray-400" />
                    ) : (
                      <ChevronRight className="w-4 h-4 text-gray-400" />
                    )}
                  </div>
                )}
              </div>

              {/* 상세 정보 (확장 시) */}
              {isExpanded && hasDetails && (
                <div className={`px-3 pb-3 space-y-1.5 ${isSubElement ? 'pl-12' : 'pl-11'}`}>
                  {item.description && (
                    <div className="flex items-start gap-1.5 text-xs">
                      <span className="text-blue-500 font-medium w-12 flex-shrink-0">설명</span>
                      <span className="text-gray-700">{item.description}</span>
                    </div>
                  )}

                  {/* action 렌더링 (문자열 또는 객체) */}
                  {renderAction(item.action)}

                  {item.validation && (
                    <div className="flex items-start gap-1.5 text-xs">
                      <span className="text-orange-500 font-medium w-12 flex-shrink-0">유효성</span>
                      <span className="text-gray-700">{item.validation}</span>
                    </div>
                  )}
                  {item.dataSource && (
                    <div className="flex items-start gap-1.5 text-xs">
                      <span className="text-purple-500 font-medium w-12 flex-shrink-0">데이터</span>
                      <span className="text-gray-700 font-mono text-[11px] bg-gray-100 px-1 rounded">{item.dataSource}</span>
                    </div>
                  )}
                  {item.condition && (
                    <div className="flex items-start gap-1.5 text-xs">
                      <span className="text-yellow-600 font-medium w-12 flex-shrink-0">조건</span>
                      <span className="text-gray-700 font-mono text-[11px] bg-yellow-50 px-1 rounded">{item.condition}</span>
                    </div>
                  )}
                  {item.options && (
                    <div className="flex items-start gap-1.5 text-xs">
                      <span className="text-indigo-500 font-medium w-12 flex-shrink-0">옵션</span>
                      <span className="text-gray-700">{Array.isArray(item.options) ? item.options.join(', ') : item.options}</span>
                    </div>
                  )}
                  {item.style && (
                    <div className="flex items-start gap-1.5 text-xs">
                      <span className="text-pink-500 font-medium w-12 flex-shrink-0">스타일</span>
                      <span className="text-gray-700 font-mono text-[11px]">{item.style}</span>
                    </div>
                  )}
                  {item.placeholder && (
                    <div className="flex items-start gap-1.5 text-xs">
                      <span className="text-gray-400 font-medium w-12 flex-shrink-0">힌트</span>
                      <span className="text-gray-500 italic">"{item.placeholder}"</span>
                    </div>
                  )}
                  {item.columns && (
                    <div className="flex items-start gap-1.5 text-xs">
                      <span className="text-orange-400 font-medium w-12 flex-shrink-0">컬럼</span>
                      <span className="text-gray-700">{item.columns.join(' | ')}</span>
                    </div>
                  )}
                  {item.format && (
                    <div className="flex items-start gap-1.5 text-xs">
                      <span className="text-teal-500 font-medium w-12 flex-shrink-0">포맷</span>
                      <span className="text-gray-700 font-mono">{item.format}</span>
                    </div>
                  )}
                  {item.position && typeof item.position === 'object' && (
                    <div className="flex items-start gap-1.5 text-xs">
                      <span className="text-cyan-500 font-medium w-12 flex-shrink-0">위치</span>
                      <span className="text-gray-700 font-mono text-[11px] bg-cyan-50 px-1 rounded">
                        {item.position.area || ''} {item.position.selector && `(${item.position.selector})`}
                      </span>
                    </div>
                  )}
                  {item.unit && (
                    <div className="flex items-start gap-1.5 text-xs">
                      <span className="text-gray-400 font-medium w-12 flex-shrink-0">단위</span>
                      <span className="text-gray-700">{item.unit}</span>
                    </div>
                  )}

                  {/* states 배열 렌더링 */}
                  {renderStates(item.states)}
                </div>
              )}
            </div>
          );
        })}
      </div>

      {/* 푸터 */}
      <div className="p-2 border-t bg-gray-50 text-[10px] text-gray-400 text-center flex-shrink-0">
        SAM MES 기능정의문서 | {screenFeatures.screenId || screenFeatures.screenName}
      </div>
    </div>
  );
};

export default FeatureDocPanel;
