// 업무 플로우차트 컴포넌트 - 메뉴 정의 기반 자동 생성
import React, { useState, useMemo } from 'react';
import {
  ArrowRight, ArrowDown, ChevronRight, ChevronDown,
  DollarSign, Factory, ShieldCheck, Truck, CreditCard, Box, Package,
  Users, FileText, ClipboardList, Settings, Layers, GitBranch,
  Play, Info, ZoomIn, ZoomOut, Maximize2, Download
} from 'lucide-react';
import { menuGroups } from '../configs/menuDefinitions';
import {
  businessProcesses,
  endToEndFlows,
  screenDataFlows,
  getScreenInfo,
  getConnectedScreens,
  getMenuGroupFlows,
  processStates,
} from '../configs/businessFlowConfig';

// 아이콘 매핑
const iconMap = {
  DollarSign, Factory, ShieldCheck, Truck, CreditCard, Box, Package,
  Users, FileText, ClipboardList, Settings, Layers, GitBranch,
};

// 색상 매핑
const colorMap = {
  blue: { bg: 'bg-blue-500', light: 'bg-blue-50', border: 'border-blue-200', text: 'text-blue-700' },
  green: { bg: 'bg-green-500', light: 'bg-green-50', border: 'border-green-200', text: 'text-green-700' },
  purple: { bg: 'bg-purple-500', light: 'bg-purple-50', border: 'border-purple-200', text: 'text-purple-700' },
  orange: { bg: 'bg-orange-500', light: 'bg-orange-50', border: 'border-orange-200', text: 'text-orange-700' },
  indigo: { bg: 'bg-indigo-500', light: 'bg-indigo-50', border: 'border-indigo-200', text: 'text-indigo-700' },
  teal: { bg: 'bg-teal-500', light: 'bg-teal-50', border: 'border-teal-200', text: 'text-teal-700' },
  red: { bg: 'bg-red-500', light: 'bg-red-50', border: 'border-red-200', text: 'text-red-700' },
  gray: { bg: 'bg-gray-500', light: 'bg-gray-50', border: 'border-gray-200', text: 'text-gray-700' },
};

// 메뉴 그룹 색상
const menuGroupColors = {
  master: 'gray',
  sales: 'blue',
  logistics: 'orange',
  production: 'green',
  quality: 'purple',
  inventory: 'teal',
  accounting: 'indigo',
  system: 'gray',
};

const BusinessFlowChart = ({ onNavigate }) => {
  const [activeView, setActiveView] = useState('e2e'); // e2e, process, menu, detail
  const [selectedProcess, setSelectedProcess] = useState(null);
  const [selectedScreen, setSelectedScreen] = useState(null);
  const [selectedE2E, setSelectedE2E] = useState('order-to-cash');
  const [expandedGroups, setExpandedGroups] = useState(['sales', 'production', 'quality']);

  // 메뉴 그룹 플로우 데이터
  const menuGroupFlows = useMemo(() => getMenuGroupFlows(), []);

  // 그룹 확장/축소 토글
  const toggleGroup = (groupId) => {
    setExpandedGroups(prev =>
      prev.includes(groupId)
        ? prev.filter(id => id !== groupId)
        : [...prev, groupId]
    );
  };

  // 화면 클릭 핸들러
  const handleScreenClick = (screenId) => {
    setSelectedScreen(screenId);
    setActiveView('detail');
  };

  // 뷰 탭
  const viewTabs = [
    { id: 'e2e', label: 'End-to-End 흐름', icon: GitBranch },
    { id: 'process', label: '업무 프로세스', icon: Layers },
    { id: 'menu', label: '메뉴별 연결', icon: Settings },
    { id: 'detail', label: '상세 연결', icon: Info, hidden: !selectedScreen },
  ];

  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-blue-600" />
          업무 플로우차트
        </h1>
        <p className="text-gray-500 mt-1">
          메뉴 정의 기반 자동 생성 - 비즈니스 로직 흐름 시각화
        </p>
      </div>

      {/* 뷰 탭 */}
      <div className="flex gap-2 mb-6 overflow-x-auto pb-2">
        {viewTabs.filter(t => !t.hidden).map(tab => {
          const Icon = tab.icon;
          return (
            <button
              key={tab.id}
              onClick={() => setActiveView(tab.id)}
              className={`flex items-center gap-2 px-4 py-2.5 rounded-lg text-sm font-medium whitespace-nowrap transition-all ${
                activeView === tab.id
                  ? 'bg-blue-600 text-white shadow-lg'
                  : 'bg-white text-gray-600 border border-gray-200 hover:bg-gray-50'
              }`}
            >
              <Icon className="w-4 h-4" />
              {tab.label}
            </button>
          );
        })}
      </div>

      {/* End-to-End 흐름 뷰 */}
      {activeView === 'e2e' && (
        <div className="space-y-6">
          {/* E2E 프로세스 선택 */}
          <div className="bg-white rounded-xl shadow-lg p-6">
            <h2 className="text-lg font-semibold text-gray-800 mb-4">전체 업무 흐름 선택</h2>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              {endToEndFlows.map(flow => {
                const color = colorMap[flow.color];
                return (
                  <button
                    key={flow.id}
                    onClick={() => setSelectedE2E(flow.id)}
                    className={`p-4 rounded-xl border-2 text-left transition-all ${
                      selectedE2E === flow.id
                        ? `${color.light} ${color.border} shadow-md`
                        : 'bg-white border-gray-200 hover:border-gray-300'
                    }`}
                  >
                    <div className={`font-bold ${color.text} mb-1`}>{flow.name}</div>
                    <div className="text-sm text-gray-500">{flow.description}</div>
                  </button>
                );
              })}
            </div>
          </div>

          {/* 선택된 E2E 플로우 시각화 */}
          {selectedE2E && (
            <div className="bg-white rounded-xl shadow-lg p-6">
              <h2 className="text-lg font-semibold text-gray-800 mb-4">
                {endToEndFlows.find(f => f.id === selectedE2E)?.name}
              </h2>
              <E2EFlowDiagram
                flow={endToEndFlows.find(f => f.id === selectedE2E)}
                onScreenClick={handleScreenClick}
              />
            </div>
          )}
        </div>
      )}

      {/* 업무 프로세스 뷰 */}
      {activeView === 'process' && (
        <div className="space-y-6">
          {businessProcesses.map(process => {
            const color = colorMap[process.color];
            const Icon = iconMap[process.icon] || Settings;
            const isSelected = selectedProcess === process.id;

            return (
              <div
                key={process.id}
                className={`bg-white rounded-xl shadow-lg overflow-hidden transition-all ${
                  isSelected ? 'ring-2 ring-blue-500' : ''
                }`}
              >
                <div
                  className={`p-4 cursor-pointer ${color.light} border-b ${color.border}`}
                  onClick={() => setSelectedProcess(isSelected ? null : process.id)}
                >
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-3">
                      <div className={`p-2 rounded-lg ${color.bg}`}>
                        <Icon className="w-5 h-5 text-white" />
                      </div>
                      <div>
                        <h3 className={`font-bold ${color.text}`}>{process.name}</h3>
                        <p className="text-sm text-gray-500">{process.description}</p>
                      </div>
                    </div>
                    <ChevronDown className={`w-5 h-5 text-gray-400 transition-transform ${
                      isSelected ? 'rotate-180' : ''
                    }`} />
                  </div>
                </div>

                {isSelected && (
                  <div className="p-6">
                    <ProcessFlowSteps
                      steps={process.steps}
                      color={color}
                      onScreenClick={handleScreenClick}
                    />
                  </div>
                )}
              </div>
            );
          })}
        </div>
      )}

      {/* 메뉴별 연결 뷰 */}
      {activeView === 'menu' && (
        <div className="bg-white rounded-xl shadow-lg p-6">
          <h2 className="text-lg font-semibold text-gray-800 mb-4">메뉴 그룹별 화면 연결</h2>
          <div className="space-y-4">
            {menuGroups.filter(g => g.id !== 'system' && g.id !== 'master').map(group => {
              const color = colorMap[menuGroupColors[group.id]] || colorMap.gray;
              const isExpanded = expandedGroups.includes(group.id);
              const Icon = iconMap[group.icon] || Settings;

              return (
                <div key={group.id} className={`border rounded-xl ${color.border} overflow-hidden`}>
                  <button
                    className={`w-full p-4 flex items-center justify-between ${color.light}`}
                    onClick={() => toggleGroup(group.id)}
                  >
                    <div className="flex items-center gap-3">
                      <Icon className={`w-5 h-5 ${color.text}`} />
                      <span className={`font-semibold ${color.text}`}>{group.label}</span>
                      <span className="text-sm text-gray-500">
                        ({group.subMenus.length}개 메뉴)
                      </span>
                    </div>
                    <ChevronDown className={`w-5 h-5 ${color.text} transition-transform ${
                      isExpanded ? 'rotate-180' : ''
                    }`} />
                  </button>

                  {isExpanded && (
                    <div className="p-4 bg-white">
                      <MenuGroupFlow
                        group={group}
                        color={color}
                        onScreenClick={handleScreenClick}
                      />
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        </div>
      )}

      {/* 상세 연결 뷰 */}
      {activeView === 'detail' && selectedScreen && (
        <ScreenDetailView
          screenId={selectedScreen}
          onScreenClick={handleScreenClick}
          onNavigate={onNavigate}
          onClose={() => {
            setSelectedScreen(null);
            setActiveView('e2e');
          }}
        />
      )}

      {/* 범례 */}
      <div className="mt-6 bg-white rounded-xl shadow-lg p-4">
        <h3 className="font-semibold text-gray-700 mb-3">범례</h3>
        <div className="flex flex-wrap gap-4 text-sm">
          {Object.entries(menuGroupColors).filter(([k]) => k !== 'master' && k !== 'system').map(([key, colorKey]) => {
            const color = colorMap[colorKey];
            const group = menuGroups.find(g => g.id === key);
            return (
              <div key={key} className="flex items-center gap-2">
                <div className={`w-4 h-4 rounded ${color.bg}`} />
                <span className="text-gray-600">{group?.label || key}</span>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
};

// E2E 플로우 다이어그램
const E2EFlowDiagram = ({ flow, onScreenClick }) => {
  if (!flow) return null;

  // 단계별 그룹화
  const phases = [...new Set(flow.steps.map(s => s.phase))];
  const phaseColors = {
    '판매': 'blue',
    '생산': 'green',
    '품질': 'purple',
    '물류': 'orange',
    '회계': 'indigo',
    '자재': 'teal',
    '구매': 'teal',
    '기준정보': 'gray',
  };

  return (
    <div className="overflow-x-auto">
      <div className="min-w-[1000px]">
        {/* 페이즈 헤더 */}
        <div className="flex mb-4">
          {phases.map((phase, idx) => {
            const color = colorMap[phaseColors[phase]] || colorMap.gray;
            const stepsInPhase = flow.steps.filter(s => s.phase === phase);
            return (
              <div
                key={phase}
                className={`flex-1 px-4 py-2 text-center font-semibold ${color.light} ${color.text} ${
                  idx === 0 ? 'rounded-l-lg' : ''
                } ${idx === phases.length - 1 ? 'rounded-r-lg' : ''}`}
                style={{ minWidth: `${stepsInPhase.length * 120}px` }}
              >
                {phase}
              </div>
            );
          })}
        </div>

        {/* 플로우 단계 */}
        <div className="flex items-center gap-2 py-4">
          {flow.steps.map((step, idx) => {
            const color = colorMap[phaseColors[step.phase]] || colorMap.gray;
            const screenInfo = getScreenInfo(step.screenId);

            return (
              <React.Fragment key={step.screenId}>
                <button
                  onClick={() => onScreenClick(step.screenId)}
                  className={`flex-shrink-0 w-28 p-3 rounded-xl border-2 ${color.border} ${color.light} hover:shadow-md transition-all cursor-pointer text-center`}
                >
                  <div className={`font-semibold text-sm ${color.text}`}>{step.label}</div>
                  <div className="text-xs text-gray-500 mt-1 truncate">
                    {screenInfo?.groupLabel || ''}
                  </div>
                </button>
                {idx < flow.steps.length - 1 && (
                  <ArrowRight className="w-5 h-5 text-gray-400 flex-shrink-0" />
                )}
              </React.Fragment>
            );
          })}
        </div>

        {/* 설명 */}
        <div className="mt-4 p-4 bg-gray-50 rounded-lg">
          <p className="text-sm text-gray-600">{flow.description}</p>
        </div>
      </div>
    </div>
  );
};

// 프로세스 플로우 단계
const ProcessFlowSteps = ({ steps, color, onScreenClick }) => {
  return (
    <div className="flex items-center gap-4 overflow-x-auto py-2">
      {steps.map((step, idx) => {
        const screenInfo = getScreenInfo(step.screenId);
        const states = processStates[step.screenId];

        return (
          <React.Fragment key={step.screenId}>
            <button
              onClick={() => onScreenClick(step.screenId)}
              className={`flex-shrink-0 min-w-[140px] p-4 rounded-xl border-2 ${
                step.required ? color.border : 'border-dashed border-gray-300'
              } ${color.light} hover:shadow-md transition-all cursor-pointer`}
            >
              <div className={`font-semibold ${color.text} mb-1`}>
                {screenInfo?.label || step.screenId}
              </div>
              <div className="text-xs text-gray-600">{step.action}</div>
              {step.trigger && (
                <div className="mt-2 text-xs text-gray-400">
                  트리거: {step.trigger}
                </div>
              )}
              {states && (
                <div className="mt-2 flex flex-wrap gap-1">
                  {states.slice(0, 3).map(state => (
                    <span key={state} className="text-xs px-1.5 py-0.5 bg-white rounded">
                      {state}
                    </span>
                  ))}
                  {states.length > 3 && (
                    <span className="text-xs text-gray-400">+{states.length - 3}</span>
                  )}
                </div>
              )}
            </button>
            {idx < steps.length - 1 && (
              <ChevronRight className={`w-6 h-6 ${color.text} flex-shrink-0`} />
            )}
          </React.Fragment>
        );
      })}
    </div>
  );
};

// 메뉴 그룹 플로우
const MenuGroupFlow = ({ group, color, onScreenClick }) => {
  return (
    <div className="space-y-3">
      {group.subMenus.map((menu, idx) => {
        // 중첩 메뉴인 경우
        if (menu.subMenus) {
          return (
            <div key={menu.id} className="space-y-2">
              <div className={`font-medium ${color.text} pl-2 border-l-4 ${color.border}`}>
                {menu.label}
              </div>
              <div className="grid grid-cols-2 md:grid-cols-4 gap-2 ml-4">
                {menu.subMenus.map(subMenu => (
                  <MenuScreenButton
                    key={subMenu.id}
                    screen={subMenu}
                    color={color}
                    onClick={() => onScreenClick(subMenu.id)}
                  />
                ))}
              </div>
            </div>
          );
        }

        // 일반 메뉴인 경우
        const flow = screenDataFlows[menu.id];
        return (
          <div key={menu.id} className="flex items-center gap-2 flex-wrap">
            <MenuScreenButton
              screen={menu}
              color={color}
              onClick={() => onScreenClick(menu.id)}
              highlight={true}
            />
            {flow?.outputs?.length > 0 && (
              <>
                <ArrowRight className="w-4 h-4 text-gray-400" />
                <div className="flex gap-2 flex-wrap">
                  {flow.outputs.map(outputId => {
                    const outputInfo = getScreenInfo(outputId);
                    return (
                      <button
                        key={outputId}
                        onClick={() => onScreenClick(outputId)}
                        className="px-3 py-1.5 text-sm bg-gray-100 hover:bg-gray-200 rounded-lg transition-colors"
                      >
                        {outputInfo?.label || outputId}
                      </button>
                    );
                  })}
                </div>
              </>
            )}
          </div>
        );
      })}
    </div>
  );
};

// 메뉴 화면 버튼
const MenuScreenButton = ({ screen, color, onClick, highlight }) => {
  const flow = screenDataFlows[screen.id];
  const hasConnections = flow?.inputs?.length > 0 || flow?.outputs?.length > 0;

  return (
    <button
      onClick={onClick}
      className={`px-3 py-2 rounded-lg text-sm font-medium transition-all ${
        highlight
          ? `${color.light} ${color.text} ${color.border} border-2`
          : 'bg-gray-50 text-gray-700 border border-gray-200 hover:border-gray-300'
      } ${hasConnections ? 'shadow-sm' : ''}`}
    >
      {screen.label}
      {screen.type && (
        <span className="ml-1 text-xs text-gray-400">({screen.type})</span>
      )}
    </button>
  );
};

// 화면 상세 뷰
const ScreenDetailView = ({ screenId, onScreenClick, onNavigate, onClose }) => {
  const screenInfo = getScreenInfo(screenId);
  const connections = getConnectedScreens(screenId);
  const states = processStates[screenId];
  const color = colorMap[menuGroupColors[screenInfo?.group]] || colorMap.gray;

  if (!screenInfo) {
    return (
      <div className="bg-white rounded-xl shadow-lg p-6 text-center">
        <p className="text-gray-500">화면 정보를 찾을 수 없습니다.</p>
        <button
          onClick={onClose}
          className="mt-4 px-4 py-2 bg-gray-100 rounded-lg hover:bg-gray-200"
        >
          돌아가기
        </button>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* 화면 기본 정보 */}
      <div className={`bg-white rounded-xl shadow-lg overflow-hidden`}>
        <div className={`p-6 ${color.light}`}>
          <div className="flex items-center justify-between">
            <div>
              <div className="text-sm text-gray-500 mb-1">
                {screenInfo.groupLabel} &gt; {screenInfo.parentLabel || screenInfo.label}
              </div>
              <h2 className={`text-2xl font-bold ${color.text}`}>{screenInfo.label}</h2>
              {screenInfo.desc && (
                <p className="text-gray-600 mt-1">{screenInfo.desc}</p>
              )}
            </div>
            <div className="flex gap-2">
              {onNavigate && (
                <button
                  onClick={() => onNavigate(screenId)}
                  className={`px-4 py-2 ${color.bg} text-white rounded-lg hover:opacity-90 flex items-center gap-2`}
                >
                  <Play className="w-4 h-4" />
                  화면 이동
                </button>
              )}
              <button
                onClick={onClose}
                className="px-4 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300"
              >
                닫기
              </button>
            </div>
          </div>
        </div>

        <div className="p-6">
          {/* 상태값 */}
          {states && (
            <div className="mb-6">
              <h3 className="font-semibold text-gray-700 mb-3">상태값</h3>
              <div className="flex flex-wrap gap-2">
                {states.map(state => (
                  <span
                    key={state}
                    className={`px-3 py-1.5 rounded-full text-sm ${color.light} ${color.text}`}
                  >
                    {state}
                  </span>
                ))}
              </div>
            </div>
          )}

          {/* 데이터 흐름 */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            {/* 입력 화면 */}
            <div>
              <h3 className="font-semibold text-gray-700 mb-3 flex items-center gap-2">
                <ArrowRight className="w-4 h-4 rotate-180" />
                입력 데이터 (From)
              </h3>
              {connections.inputs.length > 0 ? (
                <div className="space-y-2">
                  {connections.inputs.map(input => (
                    <button
                      key={input.id}
                      onClick={() => onScreenClick(input.id)}
                      className="w-full p-3 bg-blue-50 border border-blue-200 rounded-lg text-left hover:shadow-md transition-all"
                    >
                      <div className="font-medium text-blue-700">{input.label || input.id}</div>
                      <div className="text-xs text-gray-500">{input.groupLabel}</div>
                    </button>
                  ))}
                </div>
              ) : (
                <p className="text-gray-400 text-sm">입력 데이터 없음 (시작점)</p>
              )}
            </div>

            {/* 출력 화면 */}
            <div>
              <h3 className="font-semibold text-gray-700 mb-3 flex items-center gap-2">
                <ArrowRight className="w-4 h-4" />
                출력 데이터 (To)
              </h3>
              {connections.outputs.length > 0 ? (
                <div className="space-y-2">
                  {connections.outputs.map(output => (
                    <button
                      key={output.id}
                      onClick={() => onScreenClick(output.id)}
                      className="w-full p-3 bg-green-50 border border-green-200 rounded-lg text-left hover:shadow-md transition-all"
                    >
                      <div className="font-medium text-green-700">{output.label || output.id}</div>
                      <div className="text-xs text-gray-500">{output.groupLabel}</div>
                    </button>
                  ))}
                </div>
              ) : (
                <p className="text-gray-400 text-sm">출력 데이터 없음 (종료점)</p>
              )}
            </div>
          </div>

          {/* 설명 */}
          {connections.description && (
            <div className="mt-6 p-4 bg-gray-50 rounded-lg">
              <div className="text-sm text-gray-600">{connections.description}</div>
            </div>
          )}
        </div>
      </div>

      {/* 연결 다이어그램 */}
      <div className="bg-white rounded-xl shadow-lg p-6">
        <h3 className="font-semibold text-gray-700 mb-4">데이터 흐름 다이어그램</h3>
        <div className="flex items-center justify-center gap-4 py-8 overflow-x-auto">
          {/* 입력 화면들 */}
          {connections.inputs.length > 0 && (
            <>
              <div className="flex flex-col gap-2">
                {connections.inputs.map(input => (
                  <button
                    key={input.id}
                    onClick={() => onScreenClick(input.id)}
                    className="px-4 py-2 bg-blue-100 text-blue-700 rounded-lg text-sm hover:bg-blue-200 transition-colors"
                  >
                    {input.label || input.id}
                  </button>
                ))}
              </div>
              <ArrowRight className="w-8 h-8 text-gray-400" />
            </>
          )}

          {/* 현재 화면 */}
          <div className={`px-8 py-6 ${color.bg} text-white rounded-xl shadow-lg`}>
            <div className="font-bold text-lg">{screenInfo.label}</div>
            <div className="text-sm opacity-80">{screenInfo.groupLabel}</div>
          </div>

          {/* 출력 화면들 */}
          {connections.outputs.length > 0 && (
            <>
              <ArrowRight className="w-8 h-8 text-gray-400" />
              <div className="flex flex-col gap-2">
                {connections.outputs.map(output => (
                  <button
                    key={output.id}
                    onClick={() => onScreenClick(output.id)}
                    className="px-4 py-2 bg-green-100 text-green-700 rounded-lg text-sm hover:bg-green-200 transition-colors"
                  >
                    {output.label || output.id}
                  </button>
                ))}
              </div>
            </>
          )}
        </div>
      </div>
    </div>
  );
};

export default BusinessFlowChart;
