/**
 * AllMenuFeatureDocPanel - 전체 메뉴 기능정의서 패널
 * 순수 와이어프레임 스타일: 선만 사용, 배경색 최소화, 검정 텍스트
 */
import React, { useState, useMemo, useRef } from 'react';
import { COMPREHENSIVE_MENU_FEATURES } from '../configs/comprehensiveMenuFeatures';

// 항목 타입 한글 매핑
const typeLabels = {
  button: '버튼',
  input: '입력',
  select: '선택',
  'search-select': '검색선택',
  'multi-select': '다중선택',
  table: '테이블',
  'editable-table': '수정테이블',
  card: '카드',
  column: '컬럼',
  checkbox: '체크박스',
  date: '날짜',
  number: '숫자',
  textarea: '텍스트영역',
  display: '표시',
  text: '텍스트',
  badge: '뱃지',
  tab: '탭',
  'tree-node': '트리노드',
  'row-action': '행작업',
};

// 기능 항목 상세 컴포넌트
const FeatureItemDetail = ({ item, globalBadgeNumber }) => {
  const [expanded, setExpanded] = useState(false);
  const typeLabel = typeLabels[item.type] || item.type;

  return (
    <div style={{ borderBottom: '1px solid #ccc', paddingBottom: '8px', marginBottom: '8px' }}>
      <div
        onClick={() => setExpanded(!expanded)}
        style={{ display: 'flex', alignItems: 'center', gap: '8px', cursor: 'pointer', padding: '4px 0' }}
      >
        <span style={{
          minWidth: '24px',
          height: '24px',
          borderRadius: '50%',
          border: '2px solid #000',
          color: '#000',
          fontSize: '11px',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          fontWeight: 'bold'
        }}>
          {globalBadgeNumber}
        </span>
        <span style={{ padding: '2px 6px', border: '1px solid #000', fontSize: '11px', color: '#000' }}>
          {typeLabel}
        </span>
        <span style={{ flex: 1, fontWeight: '500', color: '#000', fontSize: '13px' }}>{item.label}</span>
        {item.required && <span style={{ color: '#000', fontSize: '11px', fontWeight: 'bold' }}>*필수</span>}
        <span style={{ color: '#000', fontSize: '12px' }}>{expanded ? '[-]' : '[+]'}</span>
      </div>

      {expanded && (
        <div style={{ marginLeft: '32px', paddingTop: '8px', fontSize: '12px', color: '#000', borderLeft: '1px solid #ccc', paddingLeft: '12px' }}>
          <div>ID: <span style={{ fontFamily: 'monospace' }}>{item.id}</span></div>
          {item.placeholder && <div>플레이스홀더: "{item.placeholder}"</div>}
          {item.pattern && <div>패턴: <span style={{ fontFamily: 'monospace' }}>{item.pattern}</span></div>}
          {item.options && <div>옵션: {item.options.join(', ')}</div>}
          {item.action && <div>동작: {item.action}</div>}
          {item.description && <div>설명: {item.description}</div>}
          {item.columns && <div>컬럼: {item.columns.join(', ')}</div>}
        </div>
      )}
    </div>
  );
};

// 섹션 컴포넌트
const SectionBlock = ({ section, globalBadgeStart }) => {
  const [expanded, setExpanded] = useState(true);
  const itemCount = section.items?.length || 0;

  return (
    <div style={{ marginBottom: '12px', marginLeft: '16px' }}>
      <div
        onClick={() => setExpanded(!expanded)}
        style={{ display: 'flex', alignItems: 'center', gap: '8px', cursor: 'pointer', padding: '4px 0', borderBottom: '1px solid #999' }}
      >
        <span style={{ color: '#000', fontSize: '12px' }}>{expanded ? '▼' : '▶'}</span>
        <span style={{ fontWeight: '600', color: '#000', fontSize: '13px' }}>{section.title}</span>
        <span style={{ fontSize: '11px', color: '#000' }}>({itemCount}개)</span>
      </div>

      {expanded && section.items && (
        <div style={{ marginTop: '8px' }}>
          {section.items.map((item, idx) => (
            <FeatureItemDetail key={item.id} item={item} globalBadgeNumber={globalBadgeStart + idx} />
          ))}
        </div>
      )}
    </div>
  );
};

// 화면 블록 컴포넌트
const ScreenBlock = ({ screenKey, screen, globalBadgeStart }) => {
  const [expanded, setExpanded] = useState(false);
  const totalItems = useMemo(() => {
    return screen.sections?.reduce((sum, section) => sum + (section.items?.length || 0), 0) || 0;
  }, [screen.sections]);

  let currentBadge = globalBadgeStart;
  const screenTypeLabel = screenKey === 'list' ? '목록' : screenKey === 'register' ? '등록' : screenKey === 'detail' ? '상세' : screenKey;

  return (
    <div style={{ marginBottom: '8px', marginLeft: '16px', borderLeft: '2px solid #666', paddingLeft: '12px' }}>
      <div
        onClick={() => setExpanded(!expanded)}
        style={{ display: 'flex', alignItems: 'center', gap: '8px', cursor: 'pointer', padding: '6px 0' }}
      >
        <span style={{ color: '#000', fontSize: '12px' }}>{expanded ? '▼' : '▶'}</span>
        <span style={{ fontWeight: '500', color: '#000', fontSize: '13px' }}>{screen.title}</span>
        <span style={{ fontSize: '11px', color: '#666' }}>({screenTypeLabel}, {totalItems}개 항목)</span>
      </div>

      {expanded && (
        <div style={{ marginTop: '4px' }}>
          {screen.sections?.map((section) => {
            const sectionStart = currentBadge;
            currentBadge += section.items?.length || 0;
            return <SectionBlock key={section.id} section={section} globalBadgeStart={sectionStart} />;
          })}
        </div>
      )}
    </div>
  );
};

// 페이지 블록 컴포넌트
const PageBlock = ({ pageKey, page, globalBadgeStart }) => {
  const [expanded, setExpanded] = useState(false);
  const totalItems = useMemo(() => {
    if (!page.screens) return 0;
    return Object.values(page.screens).reduce((sum, screen) => {
      return sum + (screen.sections?.reduce((s, sec) => s + (sec.items?.length || 0), 0) || 0);
    }, 0);
  }, [page.screens]);

  let currentBadge = globalBadgeStart;

  return (
    <div style={{ marginBottom: '8px', marginLeft: '12px', borderLeft: '2px solid #999', paddingLeft: '12px' }}>
      <div
        onClick={() => setExpanded(!expanded)}
        style={{ display: 'flex', alignItems: 'center', gap: '8px', cursor: 'pointer', padding: '8px 0', borderBottom: '1px dashed #ccc' }}
      >
        <span style={{ color: '#000', fontSize: '12px' }}>{expanded ? '▼' : '▶'}</span>
        <span style={{ fontWeight: '600', color: '#000', fontSize: '14px' }}>{page.label}</span>
        <span style={{ fontSize: '11px', color: '#666' }}>({Object.keys(page.screens || {}).length}개 화면, {totalItems}개 항목)</span>
      </div>

      {expanded && (
        <div style={{ marginTop: '4px' }}>
          {page.screens && Object.entries(page.screens).map(([screenKey, screen]) => {
            const screenStart = currentBadge;
            const screenItems = screen.sections?.reduce((s, sec) => s + (sec.items?.length || 0), 0) || 0;
            currentBadge += screenItems;
            return <ScreenBlock key={screenKey} screenKey={screenKey} screen={screen} globalBadgeStart={screenStart} />;
          })}
        </div>
      )}
    </div>
  );
};

// 메뉴 그룹 컴포넌트
const MenuGroupBlock = ({ menuKey, menu, globalBadgeStart }) => {
  const [expanded, setExpanded] = useState(false);
  const totalItems = useMemo(() => {
    if (!menu.pages) return 0;
    return Object.values(menu.pages).reduce((sum, page) => {
      if (!page.screens) return sum;
      return sum + Object.values(page.screens).reduce((s, screen) => {
        return s + (screen.sections?.reduce((ss, sec) => ss + (sec.items?.length || 0), 0) || 0);
      }, 0);
    }, 0);
  }, [menu.pages]);

  let currentBadge = globalBadgeStart;

  return (
    <div style={{ marginBottom: '16px', borderBottom: '2px solid #000', paddingBottom: '12px' }}>
      <div
        onClick={() => setExpanded(!expanded)}
        style={{ display: 'flex', alignItems: 'center', gap: '12px', cursor: 'pointer', padding: '8px 0' }}
      >
        <span style={{ color: '#000', fontSize: '14px', fontWeight: 'bold' }}>{expanded ? '▼' : '▶'}</span>
        <span style={{ fontWeight: 'bold', fontSize: '16px', color: '#000' }}>{menu.label}</span>
        <span style={{ fontSize: '12px', color: '#000' }}>({Object.keys(menu.pages || {}).length}개 페이지, {totalItems}개 항목)</span>
      </div>

      {expanded && (
        <div style={{ marginTop: '8px' }}>
          {menu.pages && Object.entries(menu.pages).map(([pageKey, page]) => {
            const pageStart = currentBadge;
            const pageItems = page.screens ? Object.values(page.screens).reduce((s, screen) => {
              return s + (screen.sections?.reduce((ss, sec) => ss + (sec.items?.length || 0), 0) || 0);
            }, 0) : 0;
            currentBadge += pageItems;
            return <PageBlock key={pageKey} pageKey={pageKey} page={page} globalBadgeStart={pageStart} />;
          })}
        </div>
      )}
    </div>
  );
};

// 메인 컴포넌트
const AllMenuFeatureDocPanel = ({ isOpen, onClose }) => {
  const [searchTerm, setSearchTerm] = useState('');
  const scrollRef = useRef(null);

  // 전체 통계 계산
  const stats = useMemo(() => {
    let totalMenus = 0, totalPages = 0, totalScreens = 0, totalSections = 0, totalItems = 0;
    Object.values(COMPREHENSIVE_MENU_FEATURES).forEach(menu => {
      totalMenus++;
      if (menu.pages) {
        Object.values(menu.pages).forEach(page => {
          totalPages++;
          if (page.screens) {
            Object.values(page.screens).forEach(screen => {
              totalScreens++;
              if (screen.sections) {
                screen.sections.forEach(section => {
                  totalSections++;
                  totalItems += section.items?.length || 0;
                });
              }
            });
          }
        });
      }
    });
    return { totalMenus, totalPages, totalScreens, totalSections, totalItems };
  }, []);

  // 검색 필터링된 데이터 생성
  const filteredData = useMemo(() => {
    if (!searchTerm.trim()) return COMPREHENSIVE_MENU_FEATURES;

    const term = searchTerm.toLowerCase();
    const result = {};

    Object.entries(COMPREHENSIVE_MENU_FEATURES).forEach(([menuKey, menu]) => {
      const filteredPages = {};

      if (menu.pages) {
        Object.entries(menu.pages).forEach(([pageKey, page]) => {
          const filteredScreens = {};

          if (page.screens) {
            Object.entries(page.screens).forEach(([screenKey, screen]) => {
              const filteredSections = [];

              if (screen.sections) {
                screen.sections.forEach(section => {
                  const filteredItems = section.items?.filter(item =>
                    item.label?.toLowerCase().includes(term) ||
                    item.id?.toLowerCase().includes(term) ||
                    item.type?.toLowerCase().includes(term) ||
                    item.description?.toLowerCase().includes(term)
                  ) || [];

                  if (filteredItems.length > 0) {
                    filteredSections.push({ ...section, items: filteredItems });
                  }
                });
              }

              if (filteredSections.length > 0) {
                filteredScreens[screenKey] = { ...screen, sections: filteredSections };
              }
            });
          }

          if (Object.keys(filteredScreens).length > 0) {
            filteredPages[pageKey] = { ...page, screens: filteredScreens };
          }
        });
      }

      if (Object.keys(filteredPages).length > 0) {
        result[menuKey] = { ...menu, pages: filteredPages };
      }
    });

    return result;
  }, [searchTerm]);

  // 글로벌 뱃지 시작 번호 계산
  const getGlobalBadgeStart = (menuKey) => {
    let startBadge = 1;
    for (const [key, menu] of Object.entries(filteredData)) {
      if (key === menuKey) return startBadge;
      if (menu.pages) {
        for (const page of Object.values(menu.pages)) {
          if (page.screens) {
            for (const screen of Object.values(page.screens)) {
              if (screen.sections) {
                for (const section of screen.sections) {
                  startBadge += section.items?.length || 0;
                }
              }
            }
          }
        }
      }
    }
    return startBadge;
  };

  // 필터된 결과 개수
  const filteredCount = useMemo(() => {
    let count = 0;
    Object.values(filteredData).forEach(menu => {
      if (menu.pages) {
        Object.values(menu.pages).forEach(page => {
          if (page.screens) {
            Object.values(page.screens).forEach(screen => {
              if (screen.sections) {
                screen.sections.forEach(section => {
                  count += section.items?.length || 0;
                });
              }
            });
          }
        });
      }
    });
    return count;
  }, [filteredData]);

  if (!isOpen) return null;

  return (
    <>
      {/* 백드롭 */}
      <div onClick={onClose} style={{ position: 'fixed', inset: 0, backgroundColor: 'rgba(0,0,0,0.2)', zIndex: 10001 }} />

      {/* 패널 */}
      <div style={{
        position: 'fixed',
        top: 0,
        bottom: 0,
        left: 0,
        width: '500px',
        backgroundColor: '#fff',
        zIndex: 10002,
        display: 'flex',
        flexDirection: 'column',
        borderRight: '2px solid #000'
      }}>
        {/* 헤더 */}
        <div style={{ padding: '16px', borderBottom: '2px solid #000', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div>
            <div style={{ fontSize: '18px', fontWeight: 'bold', color: '#000' }}>전체 메뉴 기능정의서</div>
            <div style={{ fontSize: '12px', color: '#666', marginTop: '4px' }}>메뉴 &gt; 페이지 &gt; 화면 &gt; 섹션 &gt; 항목</div>
          </div>
          <button onClick={onClose} style={{ background: 'none', border: '2px solid #000', padding: '4px 12px', cursor: 'pointer', fontSize: '14px', color: '#000' }}>
            닫기
          </button>
        </div>

        {/* 통계 */}
        <div style={{ padding: '12px 16px', borderBottom: '1px solid #ccc', display: 'flex', gap: '16px', fontSize: '12px', color: '#000' }}>
          <span>메뉴 {stats.totalMenus}</span>
          <span>|</span>
          <span>페이지 {stats.totalPages}</span>
          <span>|</span>
          <span>화면 {stats.totalScreens}</span>
          <span>|</span>
          <span>섹션 {stats.totalSections}</span>
          <span>|</span>
          <span style={{ fontWeight: 'bold' }}>항목 {stats.totalItems}</span>
        </div>

        {/* 검색 */}
        <div style={{ padding: '12px 16px', borderBottom: '1px solid #ccc' }}>
          <input
            type="text"
            placeholder="항목명, ID, 타입 검색..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            style={{
              width: '100%',
              padding: '8px 12px',
              border: '1px solid #000',
              fontSize: '13px',
              color: '#000',
              backgroundColor: '#fff',
              boxSizing: 'border-box',
              outline: 'none'
            }}
          />
          {searchTerm && (
            <div style={{ marginTop: '8px', fontSize: '12px', color: '#000' }}>
              검색 결과: {filteredCount}개 항목
            </div>
          )}
        </div>

        {/* 컨텐츠 */}
        <div ref={scrollRef} style={{ flex: 1, overflowY: 'auto', padding: '16px', backgroundColor: '#fff' }}>
          {Object.keys(filteredData).length === 0 ? (
            <div style={{ textAlign: 'center', padding: '40px', color: '#666' }}>
              검색 결과가 없습니다.
            </div>
          ) : (
            Object.entries(filteredData).map(([menuKey, menu]) => (
              <MenuGroupBlock key={menuKey} menuKey={menuKey} menu={menu} globalBadgeStart={getGlobalBadgeStart(menuKey)} />
            ))
          )}
        </div>

        {/* 푸터 */}
        <div style={{ padding: '12px 16px', borderTop: '2px solid #000', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <span style={{ fontSize: '12px', color: '#000' }}>
            {searchTerm ? `${filteredCount} / ${stats.totalItems}개 항목` : `전체 ${stats.totalItems}개 항목`}
          </span>
          <button style={{ background: 'none', border: '1px solid #000', padding: '6px 12px', cursor: 'pointer', fontSize: '12px', color: '#000' }}>
            내보내기
          </button>
        </div>
      </div>
    </>
  );
};

export default AllMenuFeatureDocPanel;
