// 공정관리 플로우차트 컴포넌트 - 이미지 기반 공정 흐름도
import React, { useState } from 'react';
import {
  ArrowRight, ArrowDown, CheckCircle, XCircle, AlertCircle,
  Settings, Users, Wrench, Package, Truck, ClipboardCheck,
  Factory, Monitor, FileText, Box, Play, Pause, RotateCcw,
  Scissors, Zap, Shield, Tag, ChevronRight, Info
} from 'lucide-react';
import processMasterConfig from '../configs/processMasterConfig';

const ProcessFlowChart = () => {
  const [activeProcess, setActiveProcess] = useState('SCREEN');
  const [selectedStep, setSelectedStep] = useState(null);
  const [animating, setAnimating] = useState(false);
  const [activeStepIndex, setActiveStepIndex] = useState(null);

  // config에서 공정 데이터 가져오기
  const { processWorkflows, materialInputMethods, workflowRelations } = processMasterConfig;

  // 공정별 색상 및 아이콘
  const processStyles = {
    SCREEN: { color: 'blue', bgColor: 'bg-blue-500', lightBg: 'bg-blue-50', border: 'border-blue-200', text: 'text-blue-700', icon: Scissors },
    SLAT: { color: 'purple', bgColor: 'bg-purple-500', lightBg: 'bg-purple-50', border: 'border-purple-200', text: 'text-purple-700', icon: Wrench },
    FOLD: { color: 'orange', bgColor: 'bg-orange-500', lightBg: 'bg-orange-50', border: 'border-orange-200', text: 'text-orange-700', icon: Factory },
    FORMING: { color: 'green', bgColor: 'bg-green-500', lightBg: 'bg-green-50', border: 'border-green-200', text: 'text-green-700', icon: Zap },
    PACK: { color: 'indigo', bgColor: 'bg-indigo-500', lightBg: 'bg-indigo-50', border: 'border-indigo-200', text: 'text-indigo-700', icon: Package },
  };

  // 애니메이션 시작
  const startAnimation = () => {
    const workflow = processWorkflows[activeProcess];
    if (!workflow) return;

    setAnimating(true);
    setActiveStepIndex(0);

    const interval = setInterval(() => {
      setActiveStepIndex(prev => {
        if (prev >= workflow.steps.length - 1) {
          clearInterval(interval);
          setAnimating(false);
          return prev;
        }
        return prev + 1;
      });
    }, 1500);
  };

  // 리셋
  const resetAnimation = () => {
    setAnimating(false);
    setActiveStepIndex(null);
    setSelectedStep(null);
  };

  // 현재 선택된 공정 워크플로우
  const currentWorkflow = processWorkflows[activeProcess];
  const currentStyle = processStyles[activeProcess];
  const currentMaterial = materialInputMethods[activeProcess];

  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">
          <Factory className="w-8 h-8 text-blue-600" />
          공정별 세부 작업 단계 흐름도
        </h1>
        <p className="text-gray-500 mt-1">방화셔터 제조 - 스크린/슬랫/절곡/포밍 공정 흐름</p>
      </div>

      {/* 섹션 1: 전체 공정 흐름 개요 (이미지 기반) */}
      <div className="bg-white rounded-xl shadow-lg p-6 mb-6">
        <h2 className="text-lg font-semibold text-gray-800 mb-4 flex items-center gap-2">
          <Monitor className="w-5 h-5 text-blue-600" />
          1. 전체 공정 흐름도
        </h2>

        {/* 공정 흐름도 - 이미지 스타일 */}
        <div className="overflow-x-auto">
          <div className="min-w-[1200px] space-y-4">
            {/* 스크린 라인 */}
            <div className="flex items-center gap-2">
              <div className="w-20 flex items-center">
                <ArrowRight className="w-5 h-5 text-gray-400" />
              </div>
              <ProcessFlowLine
                processCode="SCREEN"
                processName="스크린"
                steps={['원단 절단', '미싱', '앤드락 작업', '중간검사']}
                style={processStyles.SCREEN}
                isActive={activeProcess === 'SCREEN'}
                onClick={() => setActiveProcess('SCREEN')}
              />
              <ArrowRight className="w-5 h-5 text-gray-400" />
              <div className="flex-shrink-0 px-4 py-2 bg-gray-100 rounded border text-sm text-gray-600">
                중간검사
              </div>
              <ArrowRight className="w-5 h-5 text-gray-400" />
              <div className="flex-shrink-0 row-span-4 px-6 py-8 bg-indigo-100 rounded-lg border-2 border-indigo-300 text-center">
                <Package className="w-6 h-6 text-indigo-600 mx-auto mb-2" />
                <div className="font-bold text-indigo-700">포장</div>
                <div className="text-xs text-indigo-600 mt-1 max-w-[120px]">
                  포장 후 식별용 라벨 또는 메모가 필요함<br/>
                  (현재는 매직으로 직접 쓰고 있음.<br/>
                  층별/부호/분할정보 등)
                </div>
              </div>
            </div>

            {/* 슬랫 라인 */}
            <div className="flex items-center gap-2">
              <div className="w-20 flex items-center">
                <ArrowRight className="w-5 h-5 text-gray-400" />
              </div>
              <ProcessFlowLine
                processCode="SLAT"
                processName="슬랫"
                steps={['코일 절단', '중간검사', '미미작업\n(미세/미마감)']}
                style={processStyles.SLAT}
                isActive={activeProcess === 'SLAT'}
                onClick={() => setActiveProcess('SLAT')}
              />
              <div className="flex items-center">
                <svg className="w-32 h-8" viewBox="0 0 128 32">
                  <path d="M 0 16 L 100 16 L 100 -20 L 128 -20" stroke="#9CA3AF" fill="none" strokeWidth="2" strokeDasharray="4"/>
                </svg>
              </div>
            </div>

            {/* 절곡 라인 */}
            <div className="flex items-center gap-2">
              <div className="w-20 flex items-center">
                <ArrowRight className="w-5 h-5 text-gray-400" />
              </div>
              <ProcessFlowLine
                processCode="FOLD"
                processName="절곡"
                steps={['절곡판/절곡코일 절단', '절곡', '중간검사']}
                style={processStyles.FOLD}
                isActive={activeProcess === 'FOLD'}
                onClick={() => setActiveProcess('FOLD')}
              />
              <div className="flex items-center">
                <svg className="w-32 h-8" viewBox="0 0 128 32">
                  <path d="M 0 16 L 100 16 L 100 -52 L 128 -52" stroke="#9CA3AF" fill="none" strokeWidth="2" strokeDasharray="4"/>
                </svg>
              </div>
            </div>

            {/* 포밍 라인 */}
            <div className="flex items-center gap-2">
              <div className="w-20 flex items-center">
                <ArrowRight className="w-5 h-5 text-gray-400" />
              </div>
              <ProcessFlowLine
                processCode="FORMING"
                processName="포밍"
                steps={['중간검사']}
                style={processStyles.FORMING}
                isActive={activeProcess === 'FORMING'}
                onClick={() => setActiveProcess('FORMING')}
              />
              <div className="flex items-center">
                <svg className="w-64 h-8" viewBox="0 0 256 32">
                  <path d="M 0 16 L 220 16 L 220 -84 L 256 -84" stroke="#9CA3AF" fill="none" strokeWidth="2" strokeDasharray="4"/>
                </svg>
              </div>
            </div>
          </div>
        </div>

        <div className="mt-4 text-sm text-gray-500 flex items-center gap-2">
          <Info className="w-4 h-4" />
          각 공정 박스를 클릭하면 세부 작업 단계를 확인할 수 있습니다
        </div>
      </div>

      {/* 섹션 2: 공정 선택 탭 */}
      <div className="bg-white rounded-xl shadow-lg p-6 mb-6">
        <h2 className="text-lg font-semibold text-gray-800 mb-4 flex items-center gap-2">
          <Settings className="w-5 h-5 text-green-600" />
          2. 공정별 세부 작업 단계
        </h2>

        {/* 공정 선택 버튼 */}
        <div className="flex gap-3 mb-6 overflow-x-auto pb-2">
          {Object.entries(processWorkflows).map(([code, workflow]) => {
            const style = processStyles[code];
            const Icon = style?.icon || Factory;
            return (
              <button
                key={code}
                onClick={() => { setActiveProcess(code); resetAnimation(); }}
                className={`flex-shrink-0 px-4 py-3 rounded-xl flex items-center gap-2 transition-all ${
                  activeProcess === code
                    ? `${style.bgColor} text-white shadow-lg scale-105`
                    : `${style.lightBg} ${style.text} ${style.border} border hover:shadow-md`
                }`}
              >
                <Icon className="w-5 h-5" />
                <span className="font-medium">{workflow.name}</span>
              </button>
            );
          })}
        </div>

        {/* 현재 공정 정보 */}
        {currentWorkflow && (
          <div className={`p-4 rounded-xl ${currentStyle.lightBg} ${currentStyle.border} border mb-6`}>
            <div className="flex items-center justify-between flex-wrap gap-4">
              <div>
                <h3 className={`text-lg font-bold ${currentStyle.text}`}>{currentWorkflow.name} 공정</h3>
                <p className="text-sm text-gray-600">{currentWorkflow.description}</p>
              </div>
              {currentMaterial && (
                <div className="px-4 py-2 bg-white rounded-lg border">
                  <div className="text-xs text-gray-500">자재투입 방식</div>
                  <div className={`font-bold ${currentStyle.text}`}>{currentMaterial.unit}</div>
                  <div className="text-xs text-gray-600">{currentMaterial.description}</div>
                </div>
              )}
            </div>
          </div>
        )}

        {/* 작업 단계 흐름 */}
        {currentWorkflow && (
          <div className="relative">
            {/* 컨트롤 버튼 */}
            <div className="flex justify-end gap-2 mb-4">
              <button
                onClick={startAnimation}
                disabled={animating}
                className={`px-4 py-2 rounded-lg flex items-center gap-2 text-sm font-medium transition-all
                  ${animating
                    ? 'bg-gray-200 text-gray-500 cursor-not-allowed'
                    : `${currentStyle.bgColor} text-white hover:opacity-90`}`}
              >
                <Play className="w-4 h-4" />
                흐름 시작
              </button>
              <button
                onClick={resetAnimation}
                className="px-4 py-2 rounded-lg bg-gray-100 text-gray-600 hover:bg-gray-200
                  flex items-center gap-2 text-sm font-medium transition-all"
              >
                <RotateCcw className="w-4 h-4" />
                초기화
              </button>
            </div>

            {/* 작업 단계 카드들 */}
            <div className="flex items-start gap-4 overflow-x-auto pb-4">
              {currentWorkflow.steps.map((step, idx) => {
                const isActive = activeStepIndex !== null && idx <= activeStepIndex;
                const isCurrent = activeStepIndex === idx;
                const isSelected = selectedStep?.stepCode === step.stepCode;

                return (
                  <React.Fragment key={step.stepCode}>
                    <div
                      onClick={() => setSelectedStep(step)}
                      className={`flex-shrink-0 w-48 p-4 rounded-xl border-2 transition-all cursor-pointer
                        ${isCurrent
                          ? `${currentStyle.bgColor} text-white shadow-xl scale-105 border-transparent`
                          : isActive
                            ? `${currentStyle.lightBg} ${currentStyle.border} ${currentStyle.text}`
                            : isSelected
                              ? `bg-white border-gray-400 shadow-md`
                              : 'bg-white border-gray-200 hover:border-gray-300 hover:shadow-md'
                        }`}
                    >
                      <div className="flex items-center justify-between mb-2">
                        <span className={`text-xs font-mono px-2 py-0.5 rounded ${
                          isCurrent ? 'bg-white/20' : 'bg-gray-100'
                        }`}>
                          {step.stepCode}
                        </span>
                        {step.isQCStep && (
                          <Shield className={`w-4 h-4 ${isCurrent ? 'text-white' : 'text-yellow-500'}`} />
                        )}
                      </div>
                      <div className={`font-bold mb-1 ${isCurrent ? '' : 'text-gray-800'}`}>
                        {step.stepName}
                      </div>
                      <div className={`text-xs ${isCurrent ? 'text-white/80' : 'text-gray-500'}`}>
                        예상: {step.estimatedTime}분
                      </div>
                      {step.isQCStep && (
                        <div className={`mt-2 text-xs px-2 py-1 rounded ${
                          isCurrent ? 'bg-white/20' : 'bg-yellow-100 text-yellow-700'
                        }`}>
                          품질검사 단계
                        </div>
                      )}
                    </div>
                    {idx < currentWorkflow.steps.length - 1 && (
                      <div className="flex-shrink-0 flex items-center h-24">
                        <ChevronRight className={`w-6 h-6 ${
                          isActive ? currentStyle.text : 'text-gray-300'
                        }`} />
                      </div>
                    )}
                  </React.Fragment>
                );
              })}
            </div>
          </div>
        )}
      </div>

      {/* 섹션 3: 선택된 작업 단계 상세 */}
      {selectedStep && (
        <div className="bg-white rounded-xl shadow-lg p-6 mb-6">
          <h2 className="text-lg font-semibold text-gray-800 mb-4 flex items-center gap-2">
            <ClipboardCheck className="w-5 h-5 text-purple-600" />
            3. 작업 단계 상세: {selectedStep.stepName}
          </h2>

          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            {/* 기본 정보 */}
            <div className="p-4 bg-gray-50 rounded-xl">
              <h4 className="font-semibold text-gray-700 mb-3">기본 정보</h4>
              <div className="space-y-2 text-sm">
                <div className="flex justify-between">
                  <span className="text-gray-500">단계코드</span>
                  <span className="font-mono">{selectedStep.stepCode}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-500">예상시간</span>
                  <span>{selectedStep.estimatedTime}분</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-500">검사단계</span>
                  <span>{selectedStep.isQCStep ? '예' : '아니오'}</span>
                </div>
              </div>
            </div>

            {/* 필요 설비 */}
            <div className="p-4 bg-blue-50 rounded-xl">
              <h4 className="font-semibold text-blue-700 mb-3">필요 설비</h4>
              {selectedStep.requiredEquipment?.length > 0 ? (
                <ul className="space-y-1">
                  {selectedStep.requiredEquipment.map((eq, i) => (
                    <li key={i} className="flex items-center gap-2 text-sm text-blue-600">
                      <Wrench className="w-4 h-4" />
                      {eq}
                    </li>
                  ))}
                </ul>
              ) : (
                <p className="text-sm text-gray-500">설비 불필요</p>
              )}
            </div>

            {/* 투입/산출 자재 */}
            <div className="p-4 bg-green-50 rounded-xl">
              <h4 className="font-semibold text-green-700 mb-3">자재 흐름</h4>
              <div className="space-y-3 text-sm">
                <div>
                  <div className="text-xs text-gray-500 mb-1">투입 자재</div>
                  {selectedStep.inputMaterials?.map((m, i) => (
                    <div key={i} className="text-green-600">• {m}</div>
                  ))}
                </div>
                <div>
                  <div className="text-xs text-gray-500 mb-1">산출물</div>
                  {selectedStep.outputMaterials?.map((m, i) => (
                    <div key={i} className="text-green-700 font-medium">→ {m}</div>
                  ))}
                </div>
              </div>
            </div>

            {/* 체크포인트 */}
            <div className="p-4 bg-yellow-50 rounded-xl md:col-span-2 lg:col-span-1">
              <h4 className="font-semibold text-yellow-700 mb-3">체크포인트</h4>
              <ul className="space-y-1">
                {selectedStep.checkPoints?.map((cp, i) => (
                  <li key={i} className="flex items-center gap-2 text-sm text-yellow-700">
                    <CheckCircle className="w-4 h-4" />
                    {cp}
                  </li>
                ))}
              </ul>
            </div>

            {/* 비고 */}
            {(selectedStep.note || selectedStep.calculationMethod) && (
              <div className="p-4 bg-orange-50 rounded-xl md:col-span-2">
                <h4 className="font-semibold text-orange-700 mb-3">추가 정보</h4>
                {selectedStep.calculationMethod && (
                  <div className="text-sm text-orange-600 mb-2">
                    <span className="font-medium">계산방식:</span> {selectedStep.calculationMethod}
                  </div>
                )}
                {selectedStep.note && (
                  <div className="text-sm text-orange-700 p-2 bg-orange-100 rounded">
                    <AlertCircle className="w-4 h-4 inline mr-1" />
                    {selectedStep.note}
                  </div>
                )}
                {selectedStep.subSteps && (
                  <div className="mt-2">
                    <span className="text-sm font-medium text-orange-600">세부단계:</span>
                    <div className="flex gap-2 mt-1">
                      {selectedStep.subSteps.map((ss, i) => (
                        <span key={i} className="px-2 py-1 bg-orange-100 text-orange-700 text-xs rounded">
                          {ss}
                        </span>
                      ))}
                    </div>
                  </div>
                )}
              </div>
            )}
          </div>
        </div>
      )}

      {/* 섹션 4: 공정별 자재 투입 방식 요약 */}
      <div className="bg-white rounded-xl shadow-lg p-6 mb-6">
        <h2 className="text-lg font-semibold text-gray-800 mb-4 flex items-center gap-2">
          <Box className="w-5 h-5 text-indigo-600" />
          4. 공정별 자재 투입 방식
        </h2>

        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
          {Object.entries(materialInputMethods).map(([code, method]) => {
            const style = processStyles[code];
            return (
              <div
                key={code}
                className={`p-4 rounded-xl ${style?.lightBg || 'bg-gray-50'} ${style?.border || 'border-gray-200'} border`}
              >
                <div className={`font-bold ${style?.text || 'text-gray-700'} mb-2`}>
                  {processWorkflows[code]?.name || code}
                </div>
                <div className={`text-2xl font-bold ${style?.text || 'text-gray-800'} mb-1`}>
                  {method.unit}
                </div>
                <div className="text-sm text-gray-600">{method.description}</div>
                <div className="mt-2 text-xs text-gray-500 p-2 bg-white/50 rounded">
                  {method.calculationNote}
                </div>
              </div>
            );
          })}
        </div>
      </div>

      {/* 섹션 5: 포장 합류점 안내 */}
      <div className="bg-gradient-to-r from-indigo-500 to-purple-600 rounded-xl p-6 text-white">
        <h3 className="font-semibold mb-3 flex items-center gap-2">
          <Package className="w-5 h-5" />
          최종 합류점: 포장 공정
        </h3>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div>
            <p className="text-sm opacity-90 mb-3">
              모든 공정(스크린, 슬랫, 절곡, 포밍)은 최종적으로 포장 공정에서 합류합니다.
            </p>
            <div className="flex flex-wrap gap-2">
              {workflowRelations?.flows?.map((flow, i) => (
                <span key={i} className="px-3 py-1 bg-white/20 rounded-full text-sm">
                  {flow.description}
                </span>
              ))}
            </div>
          </div>
          <div className="p-4 bg-white/10 rounded-xl">
            <div className="text-sm font-medium mb-2">포장 시 필요 정보</div>
            <ul className="text-sm opacity-90 space-y-1">
              <li>• 층별 구분 정보</li>
              <li>• 부호/분할정보</li>
              <li>• 식별용 라벨 (현재 매직 수기)</li>
              <li>• 포장재 및 완충재</li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  );
};

// 공정 흐름 라인 컴포넌트
const ProcessFlowLine = ({ processCode, processName, steps, style, isActive, onClick }) => {
  return (
    <div className="flex items-center gap-2">
      <div
        onClick={onClick}
        className={`flex-shrink-0 w-24 h-20 rounded-lg border-2 flex flex-col items-center justify-center cursor-pointer transition-all
          ${isActive
            ? `${style.bgColor} text-white border-transparent shadow-lg scale-105`
            : `${style.lightBg} ${style.border} ${style.text} hover:shadow-md`
          }`}
      >
        <div className="font-bold text-sm">{processName}</div>
      </div>
      <ArrowRight className="w-5 h-5 text-gray-400 flex-shrink-0" />
      {steps.map((step, idx) => (
        <React.Fragment key={idx}>
          <div className={`flex-shrink-0 min-w-[100px] h-20 px-3 rounded border flex items-center justify-center text-center text-sm
            ${isActive ? `${style.lightBg} ${style.border}` : 'bg-gray-50 border-gray-200'}`}
          >
            <span className="whitespace-pre-line">{step}</span>
          </div>
          {idx < steps.length - 1 && (
            <ArrowRight className="w-5 h-5 text-gray-400 flex-shrink-0" />
          )}
        </React.Fragment>
      ))}
    </div>
  );
};

export default ProcessFlowChart;
