// 사용자 흐름 플로우차트 뷰어 컴포넌트
// 그레이스케일 와이어프레임 스타일 적용
import React, { useState } from 'react';
import {
  ArrowRight, ArrowDown, ChevronRight, ChevronDown, ChevronLeft,
  Play, Eye, FileText, Package, Truck, Factory, Users, DollarSign,
  ClipboardList, Box, ShieldCheck, CreditCard, Settings, Search,
  Plus, Edit, Copy, Save, Send, Printer, Trash2, CheckCircle,
  AlertTriangle, AlertCircle, Download, X, Calendar, GitBranch,
  BarChart3, Monitor, Layers, Calculator, Home, Filter
} from 'lucide-react';
import {
  mainUserFlows,
  menuFlows,
  screenFlows,
  flowCategories,
  getFlowsByCategory,
} from '../configs/userFlowPatterns';

// 아이콘 매핑
const iconMap = {
  DollarSign, Factory, ShieldCheck, CreditCard, Box, Package, Truck,
  Users, FileText, ClipboardList, Settings, Plus, Edit, Copy, Save,
  Send, Printer, Trash2, CheckCircle, AlertTriangle, AlertCircle,
  Download, Eye, Play, ArrowRight, Calendar, GitBranch, BarChart3,
  Monitor, Layers, Calculator, Home, Search, X, Filter
};

const getIcon = (iconName) => iconMap[iconName] || FileText;

// 플로우 스텝 컴포넌트 - 그레이스케일
const FlowStep = ({ step, index, total, isActive, onClick }) => {
  const isDecision = step.type === 'decision';
  const isLoop = step.type === 'loop';

  return (
    <div className="flex items-center">
      <div
        onClick={onClick}
        className={`relative cursor-pointer transition-all hover:scale-105 ${
          isActive ? 'ring-2 ring-offset-2 ring-gray-600' : ''
        }`}
      >
        {/* 스텝 번호 */}
        <div className="absolute -top-2 -left-2 w-6 h-6 rounded-full bg-gray-700 text-white text-xs flex items-center justify-center font-bold z-10">
          {index + 1}
        </div>

        {/* 스텝 박스 */}
        <div className={`
          ${isDecision ? 'rotate-45 w-28 h-28' : 'w-36 min-h-[100px]'}
          bg-white border-2 border-gray-400 rounded-lg p-3
          ${isLoop ? 'border-dashed' : ''}
        `}>
          <div className={isDecision ? '-rotate-45' : ''}>
            <div className="font-bold text-sm text-gray-800 mb-1">{step.label}</div>
            <div className="text-xs text-gray-500 mb-1">{step.menu}</div>
            <div className="text-xs text-gray-600">{step.action}</div>
            {step.type && (
              <div className={`mt-2 text-xs px-2 py-0.5 rounded ${
                isDecision ? 'bg-gray-200 text-gray-700' :
                isLoop ? 'bg-gray-100 text-gray-600' : ''
              }`}>
                {isDecision ? '분기점' : isLoop ? '반복' : ''}
              </div>
            )}
          </div>
        </div>
      </div>

      {/* 화살표 (마지막이 아닌 경우) */}
      {index < total - 1 && (
        <div className="flex items-center mx-2">
          <div className="w-8 h-0.5 bg-gray-500"></div>
          <ArrowRight className="w-5 h-5 text-gray-600" />
        </div>
      )}
    </div>
  );
};

// 분기 라인 컴포넌트 - 그레이스케일
const BranchLine = ({ branch }) => {
  return (
    <div className="flex items-center gap-2 text-sm text-gray-700 ml-8 mt-2">
      <div className="w-4 h-4 border-l-2 border-b-2 border-gray-400 rounded-bl"></div>
      <span className="px-2 py-0.5 bg-gray-200 text-gray-700 rounded text-xs">
        {branch.condition}
      </span>
      <ArrowRight className="w-4 h-4" />
      <span className="text-gray-600">{branch.label}</span>
    </div>
  );
};

// 메인 플로우 카드 컴포넌트 - 그레이스케일
const FlowCard = ({ flow, isExpanded, onToggle, onStepClick }) => {
  const category = flowCategories.find(c => c.id === flow.category);
  const CategoryIcon = getIcon(category?.icon || 'FileText');

  return (
    <div className="bg-white border border-gray-300 rounded-lg overflow-hidden mb-4">
      {/* 헤더 */}
      <div
        onClick={onToggle}
        className="flex items-center justify-between p-4 cursor-pointer hover:bg-gray-50 transition-colors"
      >
        <div className="flex items-center gap-3">
          <div className="w-10 h-10 bg-gray-700 rounded-lg flex items-center justify-center">
            <CategoryIcon className="w-5 h-5 text-white" />
          </div>
          <div>
            <h3 className="font-bold text-gray-800">{flow.name}</h3>
            <p className="text-sm text-gray-500">{flow.description}</p>
          </div>
        </div>
        <div className="flex items-center gap-2">
          <span className="px-3 py-1 rounded-full text-xs font-medium bg-gray-200 text-gray-700">
            {flow.steps.length}단계
          </span>
          {isExpanded ? <ChevronDown className="w-5 h-5 text-gray-600" /> : <ChevronRight className="w-5 h-5 text-gray-600" />}
        </div>
      </div>

      {/* 플로우 다이어그램 */}
      {isExpanded && (
        <div className="p-6 bg-gray-50 border-t border-gray-200">
          {/* 스텝들 */}
          <div className="flex flex-wrap items-start gap-4 overflow-x-auto pb-4">
            {flow.steps.map((step, idx) => (
              <FlowStep
                key={step.id}
                step={step}
                index={idx}
                total={flow.steps.length}
                onClick={() => onStepClick(step)}
              />
            ))}
          </div>

          {/* 분기 정보 */}
          {flow.branches && flow.branches.length > 0 && (
            <div className="mt-4 pt-4 border-t border-gray-300">
              <h4 className="text-sm font-medium text-gray-700 mb-2">분기 조건</h4>
              {flow.branches.map((branch, idx) => (
                <BranchLine key={idx} branch={branch} />
              ))}
            </div>
          )}
        </div>
      )}
    </div>
  );
};

// 메뉴별 플로우 카드 - 그레이스케일
const MenuFlowCard = ({ menuId, menuData, isExpanded, onToggle }) => {
  return (
    <div className="bg-white border border-gray-300 rounded-lg overflow-hidden mb-4">
      <div
        onClick={onToggle}
        className="flex items-center justify-between p-4 cursor-pointer hover:bg-gray-50"
      >
        <div>
          <h3 className="font-bold text-gray-800">{menuData.name}</h3>
          <p className="text-sm text-gray-500">{menuData.description}</p>
        </div>
        <div className="flex items-center gap-2">
          <span className="px-3 py-1 rounded-full text-xs font-medium bg-gray-200 text-gray-700">
            {menuData.flows.length}개 흐름
          </span>
          {isExpanded ? <ChevronDown className="w-5 h-5 text-gray-600" /> : <ChevronRight className="w-5 h-5 text-gray-600" />}
        </div>
      </div>

      {isExpanded && (
        <div className="p-4 bg-gray-50 border-t border-gray-200 space-y-3">
          {menuData.flows.map((flow) => (
            <div key={flow.id} className="bg-white p-4 rounded-lg border border-gray-300">
              <h4 className="font-medium text-gray-800 mb-2">{flow.name}</h4>
              <div className="flex items-center gap-2 text-sm text-gray-600 flex-wrap">
                {flow.flow.split(' → ').map((step, idx, arr) => (
                  <React.Fragment key={idx}>
                    <span className="px-2 py-1 bg-gray-100 text-gray-700 border border-gray-300 rounded">{step}</span>
                    {idx < arr.length - 1 && <ArrowRight className="w-4 h-4 text-gray-400" />}
                  </React.Fragment>
                ))}
              </div>
              <div className="mt-2 text-xs text-gray-400">
                관련 화면: {flow.screens.join(', ')}
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
};

// 화면별 액션 카드 - 그레이스케일
const ScreenActionCard = ({ screenId, screenData }) => {
  return (
    <div className="bg-white border border-gray-300 rounded-lg p-4">
      <h4 className="font-medium text-gray-800 mb-3">{screenData.name}</h4>
      <div className="grid grid-cols-2 gap-2">
        {screenData.actions.map((action, idx) => {
          const ActionIcon = getIcon(action.icon);
          return (
            <div
              key={idx}
              className="flex items-center gap-2 px-3 py-2 bg-gray-50 border border-gray-200 rounded-lg text-sm hover:bg-gray-100 transition-colors"
            >
              <ActionIcon className="w-4 h-4 text-gray-500" />
              <span className="text-gray-700">{action.action}</span>
              {action.next && (
                <>
                  <ArrowRight className="w-3 h-3 text-gray-400 ml-auto" />
                  <span className="text-xs text-gray-600 font-mono">{action.next}</span>
                </>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
};

// 메인 컴포넌트 - 그레이스케일
const UserFlowChartViewer = ({ onNavigate }) => {
  const [activeTab, setActiveTab] = useState('patterns'); // patterns, menu, screen
  const [selectedCategory, setSelectedCategory] = useState('all');
  const [expandedFlows, setExpandedFlows] = useState([]);
  const [expandedMenus, setExpandedMenus] = useState([]);
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedStep, setSelectedStep] = useState(null);

  // 필터링된 플로우
  const filteredFlows = mainUserFlows.filter(flow => {
    const matchCategory = selectedCategory === 'all' || flow.category === selectedCategory;
    const matchSearch = !searchQuery ||
      flow.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      flow.description.toLowerCase().includes(searchQuery.toLowerCase());
    return matchCategory && matchSearch;
  });

  const toggleFlow = (flowId) => {
    setExpandedFlows(prev =>
      prev.includes(flowId) ? prev.filter(id => id !== flowId) : [...prev, flowId]
    );
  };

  const toggleMenu = (menuId) => {
    setExpandedMenus(prev =>
      prev.includes(menuId) ? prev.filter(id => id !== menuId) : [...prev, menuId]
    );
  };

  const handleStepClick = (step) => {
    setSelectedStep(step);
  };

  return (
    <div className="p-6 bg-gray-50 min-h-screen">
      {/* 헤더 - 그레이스케일 */}
      <div className="mb-6">
        <h1 className="text-2xl font-bold text-gray-800 flex items-center gap-3">
          <GitBranch className="w-8 h-8 text-gray-600" />
          업무 플로우차트
        </h1>
        <p className="text-gray-500 mt-1">SAM MES 시스템 사용자 흐름 패턴 및 화면별 프로세스</p>
      </div>

      {/* 탭 네비게이션 - 그레이스케일 */}
      <div className="bg-white rounded-lg border border-gray-300 p-1 mb-6 inline-flex">
        <button
          onClick={() => setActiveTab('patterns')}
          className={`px-6 py-2.5 rounded-lg text-sm font-medium transition-colors ${
            activeTab === 'patterns' ? 'bg-black text-white' : 'text-gray-600 hover:bg-gray-100'
          }`}
        >
          주요 패턴 (20가지)
        </button>
        <button
          onClick={() => setActiveTab('menu')}
          className={`px-6 py-2.5 rounded-lg text-sm font-medium transition-colors ${
            activeTab === 'menu' ? 'bg-black text-white' : 'text-gray-600 hover:bg-gray-100'
          }`}
        >
          메뉴별 플로우
        </button>
        <button
          onClick={() => setActiveTab('screen')}
          className={`px-6 py-2.5 rounded-lg text-sm font-medium transition-colors ${
            activeTab === 'screen' ? 'bg-black text-white' : 'text-gray-600 hover:bg-gray-100'
          }`}
        >
          화면별 액션
        </button>
      </div>

      {/* 주요 패턴 탭 */}
      {activeTab === 'patterns' && (
        <>
          {/* 필터 - 그레이스케일 */}
          <div className="bg-white rounded-lg border border-gray-300 p-4 mb-6">
            <div className="flex flex-wrap items-center gap-4">
              {/* 검색 */}
              <div className="relative flex-1 min-w-[200px]">
                <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                <input
                  type="text"
                  placeholder="흐름 검색..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-gray-400 focus:border-gray-400"
                />
              </div>

              {/* 카테고리 필터 - 그레이스케일 */}
              <div className="flex items-center gap-2">
                <Filter className="w-4 h-4 text-gray-400" />
                <button
                  onClick={() => setSelectedCategory('all')}
                  className={`px-3 py-1.5 rounded-lg text-sm transition-colors ${
                    selectedCategory === 'all' ? 'bg-black text-white' : 'bg-gray-100 text-gray-600 border border-gray-300 hover:bg-gray-200'
                  }`}
                >
                  전체
                </button>
                {flowCategories.map((cat) => {
                  const CatIcon = getIcon(cat.icon);
                  return (
                    <button
                      key={cat.id}
                      onClick={() => setSelectedCategory(cat.id)}
                      className={`px-3 py-1.5 rounded-lg text-sm flex items-center gap-1.5 transition-colors ${
                        selectedCategory === cat.id
                          ? 'bg-black text-white'
                          : 'bg-gray-100 text-gray-600 border border-gray-300 hover:bg-gray-200'
                      }`}
                    >
                      <CatIcon className="w-4 h-4" />
                      {cat.name}
                    </button>
                  );
                })}
              </div>
            </div>
          </div>

          {/* 통계 - 그레이스케일 */}
          <div className="grid grid-cols-5 gap-4 mb-6">
            {flowCategories.map((cat) => {
              const count = mainUserFlows.filter(f => f.category === cat.id).length;
              const CatIcon = getIcon(cat.icon);
              return (
                <div
                  key={cat.id}
                  className={`bg-white border border-gray-300 rounded-lg p-4 cursor-pointer hover:bg-gray-50 ${
                    selectedCategory === cat.id ? 'ring-2 ring-gray-800' : ''
                  }`}
                  onClick={() => setSelectedCategory(cat.id)}
                >
                  <div className="flex items-center gap-3">
                    <div className="w-10 h-10 bg-gray-700 rounded-lg flex items-center justify-center">
                      <CatIcon className="w-5 h-5 text-white" />
                    </div>
                    <div>
                      <div className="text-2xl font-bold text-gray-800">{count}</div>
                      <div className="text-sm text-gray-500">{cat.name}</div>
                    </div>
                  </div>
                </div>
              );
            })}
          </div>

          {/* 플로우 목록 */}
          <div className="space-y-4">
            {filteredFlows.map((flow) => (
              <FlowCard
                key={flow.id}
                flow={flow}
                isExpanded={expandedFlows.includes(flow.id)}
                onToggle={() => toggleFlow(flow.id)}
                onStepClick={handleStepClick}
              />
            ))}
          </div>

          {filteredFlows.length === 0 && (
            <div className="text-center py-12 text-gray-500">
              검색 결과가 없습니다.
            </div>
          )}
        </>
      )}

      {/* 메뉴별 플로우 탭 */}
      {activeTab === 'menu' && (
        <div className="space-y-4">
          {Object.entries(menuFlows).map(([menuId, menuData]) => (
            <MenuFlowCard
              key={menuId}
              menuId={menuId}
              menuData={menuData}
              isExpanded={expandedMenus.includes(menuId)}
              onToggle={() => toggleMenu(menuId)}
            />
          ))}
        </div>
      )}

      {/* 화면별 액션 탭 */}
      {activeTab === 'screen' && (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {Object.entries(screenFlows).map(([screenId, screenData]) => (
            <ScreenActionCard
              key={screenId}
              screenId={screenId}
              screenData={screenData}
            />
          ))}
        </div>
      )}

      {/* 선택된 스텝 상세 모달 - 그레이스케일 */}
      {selectedStep && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50" onClick={() => setSelectedStep(null)}>
          <div className="bg-white rounded-lg border border-gray-300 p-6 max-w-md w-full mx-4" onClick={e => e.stopPropagation()}>
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-lg font-bold text-gray-800">{selectedStep.label}</h3>
              <button onClick={() => setSelectedStep(null)} className="p-1 hover:bg-gray-100 rounded">
                <X className="w-5 h-5" />
              </button>
            </div>
            <div className="space-y-3">
              <div>
                <div className="text-sm text-gray-500">메뉴 위치</div>
                <div className="text-gray-800">{selectedStep.menu}</div>
              </div>
              <div>
                <div className="text-sm text-gray-500">수행 작업</div>
                <div className="text-gray-800">{selectedStep.action}</div>
              </div>
              <div>
                <div className="text-sm text-gray-500">화면 ID</div>
                <div className="text-gray-700 font-mono">{selectedStep.screen}</div>
              </div>
              {selectedStep.type && (
                <div>
                  <div className="text-sm text-gray-500">스텝 유형</div>
                  <div className="inline-block px-2 py-1 rounded text-sm bg-gray-200 text-gray-700">
                    {selectedStep.type === 'decision' ? '분기점 (조건 분기)' : '반복 스텝'}
                  </div>
                </div>
              )}
            </div>
            {onNavigate && (
              <button
                onClick={() => {
                  onNavigate(selectedStep.screen);
                  setSelectedStep(null);
                }}
                className="w-full mt-4 px-4 py-2 bg-black text-white rounded-lg hover:bg-gray-800 flex items-center justify-center gap-2"
              >
                <Eye className="w-4 h-4" />
                화면으로 이동
              </button>
            )}
          </div>
        </div>
      )}
    </div>
  );
};

export default UserFlowChartViewer;
