import React, { useState, useEffect } from 'react';
import {
  FileText, Download, Filter, X, Eye, Printer, Search, ChevronDown, ChevronRight
} from 'lucide-react';
import { filterAdminBadges, extractBadgesByFilter, generateBadgeStatistics } from '../utils/featureBadgeStorage';

/**
 * 전체 기능정의서 조회 및 관리 컴포넌트
 * - 모든 화면의 기능정의서 뱃지 조회
 * - 어드민 전용 뱃지 필터링 (파란색/연두색 제외)
 * - 메뉴별/화면별 필터링
 * - PDF 출력 기능
 */
const AllFeatureBadgesViewer = ({
  allBadges = {},
  isAdmin = false,
  onClose
}) => {
  const [filterMode, setFilterMode] = useState('all'); // 'all' | 'menu' | 'screen'
  const [selectedMenu, setSelectedMenu] = useState('');
  const [selectedScreen, setSelectedScreen] = useState('');
  const [searchTerm, setSearchTerm] = useState('');
  const [expandedScreens, setExpandedScreens] = useState({});

  // 어드민이 아닌 경우 파란색/연두색 뱃지 제외
  const displayBadges = isAdmin ? allBadges : filterAdminBadges(allBadges);

  // 필터링된 뱃지 데이터
  const filteredBadges = extractBadgesByFilter(displayBadges, filterMode, selectedMenu || selectedScreen);

  // 통계 생성
  const stats = generateBadgeStatistics(filteredBadges);

  // 검색 필터 적용
  const searchFilteredBadges = searchTerm
    ? Object.keys(filteredBadges).reduce((acc, screenKey) => {
        const screenBadges = filteredBadges[screenKey].filter(badge =>
          badge.label?.toLowerCase().includes(searchTerm.toLowerCase()) ||
          badge.description?.toLowerCase().includes(searchTerm.toLowerCase())
        );
        if (screenBadges.length > 0) {
          acc[screenKey] = screenBadges;
        }
        return acc;
      }, {})
    : filteredBadges;

  // 화면 아코디언 토글
  const toggleScreen = (screenKey) => {
    setExpandedScreens(prev => ({
      ...prev,
      [screenKey]: !prev[screenKey]
    }));
  };

  // 전체 펼치기/접기
  const expandAll = () => {
    const allExpanded = {};
    Object.keys(searchFilteredBadges).forEach(key => {
      allExpanded[key] = true;
    });
    setExpandedScreens(allExpanded);
  };

  const collapseAll = () => {
    setExpandedScreens({});
  };

  // PDF 출력 함수
  const handlePrintPDF = () => {
    window.print();
  };

  // 화면명 포맷팅
  const formatScreenName = (screenKey) => {
    const parts = screenKey.split('-');
    return parts.map(part => part.charAt(0).toUpperCase() + part.slice(1)).join(' > ');
  };

  // 뱃지 색상 표시
  const getBadgeColorClass = (color) => {
    const colorMap = {
      red: 'bg-red-500',
      blue: 'bg-blue-500',
      green: 'bg-green-500',
      purple: 'bg-purple-500',
      orange: 'bg-orange-500',
      gray: 'bg-gray-500'
    };
    return colorMap[color] || 'bg-red-500';
  };

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 z-[10000] flex items-center justify-center">
      <div className="bg-white w-full max-w-6xl h-[90vh] rounded-xl shadow-2xl flex flex-col">
        {/* 헤더 */}
        <div className="border-b px-6 py-4 flex items-center justify-between bg-gradient-to-r from-blue-50 to-white">
          <div className="flex items-center gap-3">
            <FileText className="w-6 h-6 text-blue-600" />
            <div>
              <h2 className="text-xl font-bold text-gray-900">전체 기능정의서 조회</h2>
              <p className="text-sm text-gray-500 mt-0.5">
                {!isAdmin && '(어드민 전용 뱃지 제외)'} • 총 {stats.screenCount}개 화면 • {stats.totalBadges}개 뱃지
              </p>
            </div>
          </div>
          <div className="flex items-center gap-2">
            <button
              onClick={handlePrintPDF}
              className="flex items-center gap-1 px-3 py-2 text-sm border rounded-lg hover:bg-gray-50"
            >
              <Printer className="w-4 h-4" /> PDF 출력
            </button>
            <button
              onClick={onClose}
              className="p-2 hover:bg-gray-100 rounded-lg"
            >
              <X className="w-5 h-5" />
            </button>
          </div>
        </div>

        {/* 필터 및 검색 영역 */}
        <div className="border-b px-6 py-4 bg-gray-50 space-y-3">
          {/* 필터 모드 선택 */}
          <div className="flex items-center gap-2">
            <Filter className="w-4 h-4 text-gray-500" />
            <span className="text-sm font-medium text-gray-700">필터:</span>
            <div className="flex gap-2">
              <button
                onClick={() => setFilterMode('all')}
                className={`px-3 py-1 text-sm rounded-lg ${filterMode === 'all' ? 'bg-blue-600 text-white' : 'bg-white border hover:bg-gray-50'}`}
              >
                전체
              </button>
              <button
                onClick={() => setFilterMode('menu')}
                className={`px-3 py-1 text-sm rounded-lg ${filterMode === 'menu' ? 'bg-blue-600 text-white' : 'bg-white border hover:bg-gray-50'}`}
              >
                메뉴별
              </button>
              <button
                onClick={() => setFilterMode('screen')}
                className={`px-3 py-1 text-sm rounded-lg ${filterMode === 'screen' ? 'bg-blue-600 text-white' : 'bg-white border hover:bg-gray-50'}`}
              >
                화면별
              </button>
            </div>
          </div>

          {/* 검색 */}
          <div className="relative">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
            <input
              type="text"
              placeholder="기능 제목 또는 설명 검색..."
              className="w-full pl-10 pr-4 py-2 border rounded-lg text-sm"
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
            />
          </div>

          {/* 펼치기/접기 버튼 */}
          <div className="flex items-center gap-2">
            <button
              onClick={expandAll}
              className="text-sm text-blue-600 hover:underline"
            >
              전체 펼치기
            </button>
            <span className="text-gray-300">|</span>
            <button
              onClick={collapseAll}
              className="text-sm text-blue-600 hover:underline"
            >
              전체 접기
            </button>
          </div>
        </div>

        {/* 뱃지 목록 */}
        <div className="flex-1 overflow-y-auto p-6 space-y-4">
          {Object.keys(searchFilteredBadges).length === 0 ? (
            <div className="text-center py-12 text-gray-500">
              <FileText className="w-12 h-12 mx-auto mb-3 text-gray-300" />
              <p>조회된 기능정의서가 없습니다.</p>
            </div>
          ) : (
            Object.keys(searchFilteredBadges).map(screenKey => {
              const screenBadges = searchFilteredBadges[screenKey];
              const isExpanded = expandedScreens[screenKey];

              return (
                <div key={screenKey} className="border rounded-lg bg-white">
                  {/* 화면 헤더 */}
                  <button
                    onClick={() => toggleScreen(screenKey)}
                    className="w-full px-4 py-3 flex items-center justify-between hover:bg-gray-50"
                  >
                    <div className="flex items-center gap-2">
                      {isExpanded ? (
                        <ChevronDown className="w-4 h-4 text-gray-500" />
                      ) : (
                        <ChevronRight className="w-4 h-4 text-gray-500" />
                      )}
                      <span className="font-medium text-gray-900">{formatScreenName(screenKey)}</span>
                      <span className="text-xs bg-blue-100 text-blue-700 px-2 py-0.5 rounded-full">
                        {screenBadges.length}개
                      </span>
                    </div>
                  </button>

                  {/* 뱃지 목록 */}
                  {isExpanded && (
                    <div className="border-t p-4 space-y-3">
                      {screenBadges.map((badge, idx) => (
                        <div key={badge.id || idx} className="border-l-4 pl-4 py-2" style={{ borderColor: getBadgeColor(badge.color) }}>
                          <div className="flex items-start gap-2">
                            <div className={`flex-shrink-0 w-6 h-6 rounded-full ${getBadgeColorClass(badge.color)} text-white text-xs font-bold flex items-center justify-center`}>
                              {badge.number || idx + 1}
                            </div>
                            <div className="flex-1 min-w-0">
                              {badge.label && (
                                <h4 className="font-medium text-gray-900 mb-1">{badge.label}</h4>
                              )}
                              <p className="text-sm text-gray-700 whitespace-pre-wrap break-words">{badge.description}</p>
                              {badge.uiInfo && (
                                <div className="mt-2 flex gap-2 text-xs">
                                  {badge.uiInfo.componentType && (
                                    <span className="bg-gray-100 px-2 py-0.5 rounded">
                                      {badge.uiInfo.componentType}
                                    </span>
                                  )}
                                  {badge.uiInfo.interaction && (
                                    <span className="bg-gray-100 px-2 py-0.5 rounded">
                                      {badge.uiInfo.interaction}
                                    </span>
                                  )}
                                </div>
                              )}
                              <div className="mt-2 text-xs text-gray-500">
                                작성자: {badge.author || '익명'} • {badge.createdAt ? new Date(badge.createdAt).toLocaleDateString() : ''}
                              </div>
                            </div>
                          </div>
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              );
            })
          )}
        </div>

        {/* 하단 통계 */}
        <div className="border-t px-6 py-3 bg-gray-50">
          <div className="flex items-center justify-between text-sm text-gray-600">
            <div className="flex items-center gap-4">
              <span>총 화면: {stats.screenCount}개</span>
              <span>총 뱃지: {stats.totalBadges}개</span>
              <span>평균 뱃지/화면: {stats.averageBadgesPerScreen}개</span>
            </div>
            <div className="flex items-center gap-2">
              {Object.entries(stats.colorStats).map(([color, count]) => (
                <span key={color} className="flex items-center gap-1">
                  <span className={`w-3 h-3 rounded-full ${getBadgeColorClass(color)}`}></span>
                  <span className="text-xs">{count}</span>
                </span>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

// 헬퍼 함수
const getBadgeColor = (color) => {
  const colorMap = {
    red: '#ef4444',
    blue: '#3b82f6',
    green: '#10b981',
    purple: '#a855f7',
    orange: '#f97316',
    gray: '#6b7280'
  };
  return colorMap[color] || '#ef4444';
};

export default AllFeatureBadgesViewer;
