// 상세 프로세스 플로우차트 - 견적~출하 전체 사이클
import React, { useState } from 'react';
import {
  FileText, Package, Factory, ClipboardList, Truck, ShieldCheck,
  Download, CheckCircle, ArrowRight, ArrowDown, User, Printer,
  AlertCircle, Clock, Calendar, DollarSign, Box, ChevronDown, ChevronRight,
  Eye, Play, Pause, XCircle, RefreshCw
} from 'lucide-react';

// 프로세스 단계별 상태 색상
const statusColors = {
  waiting: 'bg-gray-100 border-gray-300 text-gray-700',
  active: 'bg-blue-100 border-blue-400 text-blue-700',
  complete: 'bg-green-100 border-green-400 text-green-700',
  error: 'bg-red-100 border-red-400 text-red-700',
};

// 문서 유형별 색상
const docColors = {
  quote: 'bg-purple-50 border-purple-300 text-purple-700',
  order: 'bg-blue-50 border-blue-300 text-blue-700',
  production: 'bg-orange-50 border-orange-300 text-orange-700',
  work: 'bg-yellow-50 border-yellow-300 text-yellow-700',
  quality: 'bg-teal-50 border-teal-300 text-teal-700',
  shipment: 'bg-green-50 border-green-300 text-green-700',
};

// 공정 분류 규칙
const processClassificationRules = {
  SCREEN: {
    name: '스크린',
    color: 'bg-blue-500',
    keywords: ['스크린', 'SCR', '원단', '방화원단'],
    categories: ['스크린', 'SCR'],
    itemTypes: ['FG-SCR', 'SCR-'],
  },
  SLAT: {
    name: '슬랫',
    color: 'bg-green-500',
    keywords: ['슬랫', 'SLT', '코일'],
    categories: ['슬랫', 'SLT'],
    itemTypes: ['FG-SLT', 'SLT-'],
  },
  FOLD: {
    name: '절곡',
    color: 'bg-orange-500',
    keywords: ['절곡', 'FLD', 'BND', '가이드레일', '케이스'],
    categories: ['절곡', 'BND', 'FOLD'],
    itemTypes: ['PT-BND', 'FLD-'],
  },
  STOCK: {
    name: '재고(포밍)',
    color: 'bg-purple-500',
    keywords: ['재고', '포밍', 'STK'],
    categories: ['재고', 'STOCK'],
    itemTypes: ['STK-'],
  },
  PURCHASE: {
    name: '구매품',
    color: 'bg-gray-500',
    keywords: ['전동개폐기', '제어반', '연기감지기', '모터'],
    categories: ['구매', 'BUY'],
    itemTypes: ['E-', 'CTL-', 'SMK-', 'M-'],
  },
};

// 품목을 공정으로 분류하는 함수
const classifyItemToProcess = (item) => {
  const itemCode = item.itemCode || item.productCode || '';
  const itemName = item.itemName || item.productName || '';
  const category = item.productCategory || item.category || '';

  // 구매품 체크 (구매 부품은 작업지시 생성 안함)
  for (const keyword of processClassificationRules.PURCHASE.keywords) {
    if (itemName.includes(keyword)) {
      return { processCode: 'PURCHASE', isPurchased: true, isService: false };
    }
  }
  for (const prefix of processClassificationRules.PURCHASE.itemTypes) {
    if (itemCode.startsWith(prefix)) {
      return { processCode: 'PURCHASE', isPurchased: true, isService: false };
    }
  }

  // 스크린 체크
  for (const keyword of processClassificationRules.SCREEN.keywords) {
    if (itemName.includes(keyword) || category.includes(keyword)) {
      return { processCode: 'SCR-001', processName: '스크린 생산', workflowCode: 'SCREEN', processSeq: 1, isPurchased: false };
    }
  }
  for (const prefix of processClassificationRules.SCREEN.itemTypes) {
    if (itemCode.startsWith(prefix)) {
      return { processCode: 'SCR-001', processName: '스크린 생산', workflowCode: 'SCREEN', processSeq: 1, isPurchased: false };
    }
  }

  // 슬랫 체크
  for (const keyword of processClassificationRules.SLAT.keywords) {
    if (itemName.includes(keyword) || category.includes(keyword)) {
      return { processCode: 'SLT-001', processName: '슬랫 생산', workflowCode: 'SLAT', processSeq: 2, isPurchased: false };
    }
  }
  for (const prefix of processClassificationRules.SLAT.itemTypes) {
    if (itemCode.startsWith(prefix)) {
      return { processCode: 'SLT-001', processName: '슬랫 생산', workflowCode: 'SLAT', processSeq: 2, isPurchased: false };
    }
  }

  // 절곡 체크
  for (const keyword of processClassificationRules.FOLD.keywords) {
    if (itemName.includes(keyword) || category.includes(keyword)) {
      return { processCode: 'FLD-001', processName: '절곡 생산', workflowCode: 'FOLD', processSeq: 3, isPurchased: false };
    }
  }
  for (const prefix of processClassificationRules.FOLD.itemTypes) {
    if (itemCode.startsWith(prefix)) {
      return { processCode: 'FLD-001', processName: '절곡 생산', workflowCode: 'FOLD', processSeq: 3, isPurchased: false };
    }
  }

  // 재고(포밍) 체크
  for (const keyword of processClassificationRules.STOCK.keywords) {
    if (itemName.includes(keyword) || category.includes(keyword)) {
      return { processCode: 'STK-001', processName: '재고 생산', workflowCode: 'STOCK', processSeq: 4, isPurchased: false };
    }
  }

  // 기본값: 스크린
  return { processCode: 'SCR-001', processName: '스크린 생산', workflowCode: 'SCREEN', processSeq: 1, isPurchased: false };
};

// 프로세스 노드 컴포넌트
const ProcessNode = ({ title, icon: Icon, status = 'waiting', documents = [], onClick, isExpanded, children }) => {
  return (
    <div className="flex flex-col items-center">
      <div
        onClick={onClick}
        className={`relative cursor-pointer transition-all duration-200 hover:scale-105 ${onClick ? 'cursor-pointer' : ''}`}
      >
        <div className={`w-40 p-3 rounded-lg border-2 ${statusColors[status]} shadow-sm`}>
          <div className="flex items-center gap-2 mb-1">
            <Icon className="w-5 h-5" />
            <span className="font-medium text-sm">{title}</span>
          </div>
          {documents.length > 0 && (
            <div className="mt-2 space-y-1">
              {documents.map((doc, idx) => (
                <div key={idx} className={`text-xs px-2 py-0.5 rounded ${docColors[doc.type] || 'bg-gray-50'} flex items-center gap-1`}>
                  <Printer className="w-3 h-3" />
                  {doc.name}
                </div>
              ))}
            </div>
          )}
        </div>
        {status === 'complete' && (
          <CheckCircle className="absolute -top-1 -right-1 w-5 h-5 text-green-500 bg-white rounded-full" />
        )}
        {status === 'active' && (
          <div className="absolute -top-1 -right-1 w-5 h-5 bg-blue-500 rounded-full animate-pulse" />
        )}
      </div>
      {isExpanded && children && (
        <div className="mt-2 ml-4 border-l-2 border-gray-300 pl-4">
          {children}
        </div>
      )}
    </div>
  );
};

// 화살표 컴포넌트
const Arrow = ({ direction = 'right', label }) => {
  if (direction === 'right') {
    return (
      <div className="flex items-center mx-2">
        <div className="w-8 h-0.5 bg-gray-300" />
        <ArrowRight className="w-4 h-4 text-gray-400" />
        {label && <span className="text-xs text-gray-500 ml-1">{label}</span>}
      </div>
    );
  }
  return (
    <div className="flex flex-col items-center my-2">
      <div className="w-0.5 h-4 bg-gray-300" />
      <ArrowDown className="w-4 h-4 text-gray-400" />
      {label && <span className="text-xs text-gray-500">{label}</span>}
    </div>
  );
};

// 공정 분기 컴포넌트
const ProcessBranch = ({ processes = [], status = 'waiting' }) => {
  return (
    <div className="relative">
      <div className="flex flex-col items-center">
        <div className="w-0.5 h-4 bg-gray-300" />
        <div className="flex gap-4">
          {processes.map((proc, idx) => (
            <div key={idx} className="flex flex-col items-center">
              <div className={`w-24 p-2 rounded-lg border ${statusColors[status]} text-center`}>
                <div className={`w-3 h-3 rounded-full ${proc.color} mx-auto mb-1`} />
                <span className="text-xs font-medium">{proc.name}</span>
                <div className="text-xs text-gray-500">{proc.steps}단계</div>
              </div>
            </div>
          ))}
        </div>
        <div className="w-0.5 h-4 bg-gray-300" />
        <div className="text-xs text-gray-500 bg-gray-100 px-2 py-0.5 rounded">공정별 병렬 진행</div>
      </div>
    </div>
  );
};

// 상세 플로우차트 메인 컴포넌트
const DetailedProcessFlowChart = ({ onNavigate }) => {
  const [expandedSections, setExpandedSections] = useState({
    quote: true,
    order: true,
    production: true,
    work: true,
    quality: true,
    shipment: true,
  });
  const [activePhase, setActivePhase] = useState(null);

  const toggleSection = (section) => {
    setExpandedSections(prev => ({
      ...prev,
      [section]: !prev[section],
    }));
  };

  return (
    <div className="space-y-6 p-6">
      {/* 헤더 */}
      <div className="space-y-3">
        <h1 className="text-xl font-bold text-gray-900 flex items-center gap-2">
          <Factory className="w-6 h-6 text-blue-500" />
          견적~출하 상세 프로세스 플로우차트
        </h1>
        <div className="flex items-center justify-end">
          <div className="flex items-center gap-4 text-sm">
            <div className="flex items-center gap-1">
              <div className="w-3 h-3 rounded bg-gray-200 border border-gray-300" />
              <span className="text-gray-600">대기</span>
            </div>
            <div className="flex items-center gap-1">
              <div className="w-3 h-3 rounded bg-blue-200 border border-blue-400" />
              <span className="text-gray-600">진행중</span>
            </div>
            <div className="flex items-center gap-1">
              <div className="w-3 h-3 rounded bg-green-200 border border-green-400" />
              <span className="text-gray-600">완료</span>
            </div>
            <div className="flex items-center gap-1">
              <Printer className="w-4 h-4 text-purple-500" />
              <span className="text-gray-600">문서 출력</span>
            </div>
          </div>
        </div>
      </div>

      {/* 전체 플로우 개요 */}
      <div className="bg-white rounded-xl border p-6">
        <h3 className="text-sm font-bold text-gray-700 mb-4">전체 프로세스 개요</h3>
        <div className="flex items-center justify-between overflow-x-auto pb-4">
          <ProcessNode
            title="견적"
            icon={FileText}
            status="complete"
            documents={[
              { type: 'quote', name: '견적서' },
              { type: 'quote', name: '산출내역서' },
            ]}
          />
          <Arrow direction="right" />
          <ProcessNode
            title="수주"
            icon={Package}
            status="complete"
            documents={[
              { type: 'order', name: '수주확인서' },
              { type: 'order', name: '발주서' },
            ]}
          />
          <Arrow direction="right" />
          <ProcessNode
            title="생산지시"
            icon={Factory}
            status="active"
            documents={[
              { type: 'production', name: '생산지시서' },
            ]}
          />
          <Arrow direction="right" />
          <ProcessNode
            title="작업지시"
            icon={ClipboardList}
            status="waiting"
            documents={[
              { type: 'work', name: '작업지시서' },
              { type: 'work', name: '작업일지' },
            ]}
          />
          <Arrow direction="right" />
          <ProcessNode
            title="품질검사"
            icon={ShieldCheck}
            status="waiting"
            documents={[
              { type: 'quality', name: '검사성적서' },
            ]}
          />
          <Arrow direction="right" />
          <ProcessNode
            title="출하"
            icon={Truck}
            status="waiting"
            documents={[
              { type: 'shipment', name: '출고증' },
              { type: 'shipment', name: '거래명세서' },
            ]}
          />
        </div>
      </div>

      {/* 1. 견적 단계 상세 */}
      <div className="bg-white rounded-xl border overflow-hidden">
        <button
          onClick={() => toggleSection('quote')}
          className="w-full px-4 py-3 bg-purple-50 flex items-center justify-between hover:bg-purple-100 transition-colors"
        >
          <div className="flex items-center gap-2">
            {expandedSections.quote ? <ChevronDown className="w-4 h-4" /> : <ChevronRight className="w-4 h-4" />}
            <FileText className="w-5 h-5 text-purple-600" />
            <span className="font-medium text-purple-800">1. 견적 단계</span>
          </div>
          <span className="text-sm text-purple-600">영업팀</span>
        </button>
        {expandedSections.quote && (
          <div className="p-4 space-y-4">
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              {/* 견적 등록 */}
              <div className="border rounded-lg p-4">
                <h4 className="font-medium text-gray-800 mb-2 flex items-center gap-2">
                  <span className="w-6 h-6 rounded-full bg-purple-100 text-purple-700 text-xs flex items-center justify-center">1</span>
                  견적 등록
                </h4>
                <ul className="text-sm text-gray-600 space-y-1 ml-8">
                  <li>거래처/현장 선택</li>
                  <li>품목 추가 (BOM 연동)</li>
                  <li>단가/수량 입력</li>
                  <li>견적수식 자동 계산</li>
                </ul>
                <div className="mt-3 p-2 bg-purple-50 rounded text-xs">
                  <span className="font-medium text-purple-700">연동 데이터:</span>
                  <span className="text-purple-600 ml-1">거래처기준, 품목기준, 견적수식</span>
                </div>
              </div>
              {/* 견적 확정 */}
              <div className="border rounded-lg p-4">
                <h4 className="font-medium text-gray-800 mb-2 flex items-center gap-2">
                  <span className="w-6 h-6 rounded-full bg-purple-100 text-purple-700 text-xs flex items-center justify-center">2</span>
                  견적 확정
                </h4>
                <ul className="text-sm text-gray-600 space-y-1 ml-8">
                  <li>내부 검토/승인</li>
                  <li>최종확정 처리</li>
                  <li>고객 발송</li>
                </ul>
                <div className="mt-3 p-2 bg-purple-50 rounded text-xs">
                  <span className="font-medium text-purple-700">상태 변경:</span>
                  <span className="text-purple-600 ml-1">최초작성 → 최종확정</span>
                </div>
              </div>
              {/* 문서 출력 */}
              <div className="border rounded-lg p-4 bg-gray-50">
                <h4 className="font-medium text-gray-800 mb-2 flex items-center gap-2">
                  <Printer className="w-5 h-5 text-purple-600" />
                  문서 출력
                </h4>
                <div className="space-y-2 text-sm">
                  <div className="flex items-center gap-2 p-2 bg-white rounded border">
                    <FileText className="w-4 h-4 text-purple-500" />
                    <div>
                      <div className="font-medium">견적서</div>
                      <div className="text-xs text-gray-500">고객 제출용 공식 견적서</div>
                    </div>
                  </div>
                  <div className="flex items-center gap-2 p-2 bg-white rounded border">
                    <FileText className="w-4 h-4 text-purple-500" />
                    <div>
                      <div className="font-medium">산출내역서</div>
                      <div className="text-xs text-gray-500">상세 산출 근거 내역</div>
                    </div>
                  </div>
                  <div className="flex items-center gap-2 p-2 bg-white rounded border">
                    <FileText className="w-4 h-4 text-purple-500" />
                    <div>
                      <div className="font-medium">발주서</div>
                      <div className="text-xs text-gray-500">구매품 발주용</div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        )}
      </div>

      {/* 2. 수주 단계 상세 */}
      <div className="bg-white rounded-xl border overflow-hidden">
        <button
          onClick={() => toggleSection('order')}
          className="w-full px-4 py-3 bg-blue-50 flex items-center justify-between hover:bg-blue-100 transition-colors"
        >
          <div className="flex items-center gap-2">
            {expandedSections.order ? <ChevronDown className="w-4 h-4" /> : <ChevronRight className="w-4 h-4" />}
            <Package className="w-5 h-5 text-blue-600" />
            <span className="font-medium text-blue-800">2. 수주 단계</span>
          </div>
          <span className="text-sm text-blue-600">영업팀 → 생산관리</span>
        </button>
        {expandedSections.order && (
          <div className="p-4 space-y-4">
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              {/* 견적 → 수주 전환 */}
              <div className="border rounded-lg p-4">
                <h4 className="font-medium text-gray-800 mb-2 flex items-center gap-2">
                  <span className="w-6 h-6 rounded-full bg-blue-100 text-blue-700 text-xs flex items-center justify-center">1</span>
                  수주 전환/등록
                </h4>
                <ul className="text-sm text-gray-600 space-y-1 ml-8">
                  <li>견적 → 수주 전환 (자동)</li>
                  <li>또는 신규 수주 등록</li>
                  <li>납기일/배송정보 확정</li>
                  <li>거래처 신용등급 확인</li>
                </ul>
                <div className="mt-3 p-2 bg-blue-50 rounded text-xs">
                  <span className="font-medium text-blue-700">신용등급:</span>
                  <span className="text-blue-600 ml-1">A등급(무조건 출하), B/C등급(입금확인 필요)</span>
                </div>
              </div>
              {/* 수주 확정 */}
              <div className="border rounded-lg p-4">
                <h4 className="font-medium text-gray-800 mb-2 flex items-center gap-2">
                  <span className="w-6 h-6 rounded-full bg-blue-100 text-blue-700 text-xs flex items-center justify-center">2</span>
                  수주 확정
                </h4>
                <ul className="text-sm text-gray-600 space-y-1 ml-8">
                  <li>품목/수량 최종 확인</li>
                  <li>수주확정 처리</li>
                  <li>→ 생산지시 생성 가능</li>
                </ul>
                <div className="mt-3 p-2 bg-blue-50 rounded text-xs">
                  <span className="font-medium text-blue-700">상태 변경:</span>
                  <span className="text-blue-600 ml-1">수주등록 → 수주확정 → 생산지시완료</span>
                </div>
              </div>
              {/* 문서 출력 */}
              <div className="border rounded-lg p-4 bg-gray-50">
                <h4 className="font-medium text-gray-800 mb-2 flex items-center gap-2">
                  <Printer className="w-5 h-5 text-blue-600" />
                  문서 출력
                </h4>
                <div className="space-y-2 text-sm">
                  <div className="flex items-center gap-2 p-2 bg-white rounded border">
                    <FileText className="w-4 h-4 text-blue-500" />
                    <div>
                      <div className="font-medium">수주확인서</div>
                      <div className="text-xs text-gray-500">수주 내역 확인용</div>
                    </div>
                  </div>
                  <div className="flex items-center gap-2 p-2 bg-white rounded border">
                    <FileText className="w-4 h-4 text-blue-500" />
                    <div>
                      <div className="font-medium">발주서</div>
                      <div className="text-xs text-gray-500">구매품 발주용 (수주 기준)</div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        )}
      </div>

      {/* 3. 생산지시 단계 상세 */}
      <div className="bg-white rounded-xl border overflow-hidden">
        <button
          onClick={() => toggleSection('production')}
          className="w-full px-4 py-3 bg-orange-50 flex items-center justify-between hover:bg-orange-100 transition-colors"
        >
          <div className="flex items-center gap-2">
            {expandedSections.production ? <ChevronDown className="w-4 h-4" /> : <ChevronRight className="w-4 h-4" />}
            <Factory className="w-5 h-5 text-orange-600" />
            <span className="font-medium text-orange-800">3. 생산지시 단계</span>
          </div>
          <span className="text-sm text-orange-600">생산관리</span>
        </button>
        {expandedSections.production && (
          <div className="p-4 space-y-4">
            {/* 품목 자동 분류 규칙 */}
            <div className="bg-orange-50 border border-orange-200 rounded-lg p-4">
              <h4 className="font-medium text-orange-800 mb-3 flex items-center gap-2">
                <AlertCircle className="w-4 h-4" />
                공정별 품목 자동 분류 규칙
              </h4>
              <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
                <div className="bg-white rounded p-3 border">
                  <div className="flex items-center gap-2 mb-2">
                    <div className="w-3 h-3 rounded-full bg-blue-500" />
                    <span className="font-medium text-sm">스크린 공정</span>
                  </div>
                  <ul className="text-xs text-gray-600 space-y-1">
                    <li>품목코드: FG-SCR-*, SCR-*</li>
                    <li>품목명: 스크린, 원단, 방화원단</li>
                    <li>분류: 스크린 카테고리</li>
                  </ul>
                </div>
                <div className="bg-white rounded p-3 border">
                  <div className="flex items-center gap-2 mb-2">
                    <div className="w-3 h-3 rounded-full bg-green-500" />
                    <span className="font-medium text-sm">슬랫 공정</span>
                  </div>
                  <ul className="text-xs text-gray-600 space-y-1">
                    <li>품목코드: FG-SLT-*, SLT-*</li>
                    <li>품목명: 슬랫, 코일</li>
                    <li>분류: 슬랫 카테고리</li>
                  </ul>
                </div>
                <div className="bg-white rounded p-3 border">
                  <div className="flex items-center gap-2 mb-2">
                    <div className="w-3 h-3 rounded-full bg-orange-500" />
                    <span className="font-medium text-sm">절곡 공정</span>
                  </div>
                  <ul className="text-xs text-gray-600 space-y-1">
                    <li>품목코드: PT-BND-*, FLD-*</li>
                    <li>품목명: 절곡, 가이드레일, 케이스</li>
                    <li>분류: 절곡 카테고리</li>
                  </ul>
                </div>
                <div className="bg-white rounded p-3 border">
                  <div className="flex items-center gap-2 mb-2">
                    <div className="w-3 h-3 rounded-full bg-gray-500" />
                    <span className="font-medium text-sm">구매품 (제외)</span>
                  </div>
                  <ul className="text-xs text-gray-600 space-y-1">
                    <li>품목코드: E-*, CTL-*, SMK-*</li>
                    <li>품목명: 전동개폐기, 제어반, 모터</li>
                    <li>→ 작업지시 생성 안함</li>
                  </ul>
                </div>
              </div>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              {/* 생산지시 생성 */}
              <div className="border rounded-lg p-4">
                <h4 className="font-medium text-gray-800 mb-2 flex items-center gap-2">
                  <span className="w-6 h-6 rounded-full bg-orange-100 text-orange-700 text-xs flex items-center justify-center">1</span>
                  생산지시 생성
                </h4>
                <ul className="text-sm text-gray-600 space-y-1 ml-8">
                  <li>수주 상세에서 생산지시 생성 버튼</li>
                  <li>BOM 품목 → 공정별 자동 분류</li>
                  <li>우선순위 설정 (긴급/높음/일반/낮음)</li>
                  <li>공정별 작업지시 미리보기</li>
                </ul>
                <div className="mt-3 p-2 bg-orange-50 rounded text-xs">
                  <span className="font-medium text-orange-700">자동 분류:</span>
                  <span className="text-orange-600 ml-1">공정관리 규칙 기반 품목 분류</span>
                </div>
              </div>
              {/* 우선순위 매핑 */}
              <div className="border rounded-lg p-4">
                <h4 className="font-medium text-gray-800 mb-2 flex items-center gap-2">
                  <span className="w-6 h-6 rounded-full bg-orange-100 text-orange-700 text-xs flex items-center justify-center">2</span>
                  우선순위 매핑
                </h4>
                <table className="w-full text-xs mt-2">
                  <thead>
                    <tr className="border-b">
                      <th className="text-left py-1">생산지시(영업)</th>
                      <th className="text-left py-1">작업지시(공장)</th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr className="border-b">
                      <td className="py-1"><span className="px-1.5 py-0.5 bg-red-100 text-red-700 rounded">긴급</span></td>
                      <td className="py-1"><span className="px-1.5 py-0.5 bg-red-100 text-red-700 rounded">1순위</span></td>
                    </tr>
                    <tr className="border-b">
                      <td className="py-1"><span className="px-1.5 py-0.5 bg-orange-100 text-orange-700 rounded">높음</span></td>
                      <td className="py-1"><span className="px-1.5 py-0.5 bg-orange-100 text-orange-700 rounded">3순위</span></td>
                    </tr>
                    <tr className="border-b">
                      <td className="py-1"><span className="px-1.5 py-0.5 bg-blue-100 text-blue-700 rounded">일반</span></td>
                      <td className="py-1"><span className="px-1.5 py-0.5 bg-blue-100 text-blue-700 rounded">5순위</span></td>
                    </tr>
                    <tr>
                      <td className="py-1"><span className="px-1.5 py-0.5 bg-gray-100 text-gray-700 rounded">낮음</span></td>
                      <td className="py-1"><span className="px-1.5 py-0.5 bg-gray-100 text-gray-700 rounded">9순위</span></td>
                    </tr>
                  </tbody>
                </table>
                <div className="mt-2 text-xs text-gray-500">
                  * 2,4,6~8순위는 현장 조정용 여유분
                </div>
              </div>
              {/* 문서 출력 */}
              <div className="border rounded-lg p-4 bg-gray-50">
                <h4 className="font-medium text-gray-800 mb-2 flex items-center gap-2">
                  <Printer className="w-5 h-5 text-orange-600" />
                  문서 출력
                </h4>
                <div className="space-y-2 text-sm">
                  <div className="flex items-center gap-2 p-2 bg-white rounded border">
                    <FileText className="w-4 h-4 text-orange-500" />
                    <div>
                      <div className="font-medium">생산지시서</div>
                      <div className="text-xs text-gray-500">공정별 생산 지시 내역</div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        )}
      </div>

      {/* 4. 작업지시 단계 상세 */}
      <div className="bg-white rounded-xl border overflow-hidden">
        <button
          onClick={() => toggleSection('work')}
          className="w-full px-4 py-3 bg-yellow-50 flex items-center justify-between hover:bg-yellow-100 transition-colors"
        >
          <div className="flex items-center gap-2">
            {expandedSections.work ? <ChevronDown className="w-4 h-4" /> : <ChevronRight className="w-4 h-4" />}
            <ClipboardList className="w-5 h-5 text-yellow-600" />
            <span className="font-medium text-yellow-800">4. 작업지시 → 작업자 → 공정진행</span>
          </div>
          <span className="text-sm text-yellow-600">생산팀 (스크린/슬랫/절곡팀)</span>
        </button>
        {expandedSections.work && (
          <div className="p-4 space-y-4">
            {/* 공정별 작업 단계 */}
            <div className="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
              <h4 className="font-medium text-yellow-800 mb-3">공정별 세부 작업 단계</h4>
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                {/* 스크린 공정 */}
                <div className="bg-white rounded-lg p-3 border">
                  <div className="flex items-center gap-2 mb-2">
                    <div className="w-3 h-3 rounded-full bg-blue-500" />
                    <span className="font-medium text-sm">스크린 공정 (8단계)</span>
                  </div>
                  <ol className="text-xs text-gray-600 space-y-1 list-decimal list-inside">
                    <li>자재투입 (LOT 선택)</li>
                    <li>절단매수확인</li>
                    <li>원단 절단</li>
                    <li>절단 Check</li>
                    <li>미싱</li>
                    <li>앤드락 작업</li>
                    <li className="text-teal-600 font-medium">중간검사 (PQC)</li>
                    <li>포장</li>
                  </ol>
                </div>
                {/* 슬랫 공정 */}
                <div className="bg-white rounded-lg p-3 border">
                  <div className="flex items-center gap-2 mb-2">
                    <div className="w-3 h-3 rounded-full bg-green-500" />
                    <span className="font-medium text-sm">슬랫 공정 (4단계)</span>
                  </div>
                  <ol className="text-xs text-gray-600 space-y-1 list-decimal list-inside">
                    <li>코일 절단</li>
                    <li>미미작업 (미세/미마감)</li>
                    <li className="text-teal-600 font-medium">중간검사 (PQC)</li>
                    <li>포장</li>
                  </ol>
                </div>
                {/* 절곡 공정 */}
                <div className="bg-white rounded-lg p-3 border">
                  <div className="flex items-center gap-2 mb-2">
                    <div className="w-3 h-3 rounded-full bg-orange-500" />
                    <span className="font-medium text-sm">절곡 공정 (5단계)</span>
                  </div>
                  <ol className="text-xs text-gray-600 space-y-1 list-decimal list-inside">
                    <li>절곡판/절곡코일 절단</li>
                    <li>V컷팅</li>
                    <li>절곡</li>
                    <li className="text-teal-600 font-medium">중간검사 (PQC)</li>
                    <li>포장</li>
                  </ol>
                </div>
              </div>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
              {/* 작업지시 생성 */}
              <div className="border rounded-lg p-4">
                <h4 className="font-medium text-gray-800 mb-2 flex items-center gap-2">
                  <span className="w-6 h-6 rounded-full bg-yellow-100 text-yellow-700 text-xs flex items-center justify-center">1</span>
                  작업지시 생성
                </h4>
                <ul className="text-sm text-gray-600 space-y-1 ml-8">
                  <li>생산지시에서 자동 생성</li>
                  <li>공정별 분리 (스크린/슬랫/절곡)</li>
                  <li>우선순위 개별 조정 (1~10)</li>
                  <li>작업자 배정</li>
                </ul>
              </div>
              {/* 작업자 화면 */}
              <div className="border rounded-lg p-4">
                <h4 className="font-medium text-gray-800 mb-2 flex items-center gap-2">
                  <span className="w-6 h-6 rounded-full bg-yellow-100 text-yellow-700 text-xs flex items-center justify-center">2</span>
                  작업자 화면
                </h4>
                <ul className="text-sm text-gray-600 space-y-1 ml-8">
                  <li>팀별/개인별 작업 조회</li>
                  <li>작업 시작/완료 처리</li>
                  <li>자재 투입 (LOT 선택)</li>
                  <li>이슈 보고</li>
                </ul>
              </div>
              {/* 공정 진행 */}
              <div className="border rounded-lg p-4">
                <h4 className="font-medium text-gray-800 mb-2 flex items-center gap-2">
                  <span className="w-6 h-6 rounded-full bg-yellow-100 text-yellow-700 text-xs flex items-center justify-center">3</span>
                  공정 진행
                </h4>
                <ul className="text-sm text-gray-600 space-y-1 ml-8">
                  <li>단계별 진행 처리</li>
                  <li>개별 품목 체크 (층/호수)</li>
                  <li>중간검사 요청</li>
                  <li>포장 및 라벨 부착</li>
                </ul>
              </div>
              {/* 문서 출력 */}
              <div className="border rounded-lg p-4 bg-gray-50">
                <h4 className="font-medium text-gray-800 mb-2 flex items-center gap-2">
                  <Printer className="w-5 h-5 text-yellow-600" />
                  문서 출력
                </h4>
                <div className="space-y-2 text-sm">
                  <div className="flex items-center gap-2 p-2 bg-white rounded border">
                    <FileText className="w-4 h-4 text-yellow-500" />
                    <div>
                      <div className="font-medium">작업지시서</div>
                      <div className="text-xs text-gray-500">공정별 상세 작업 지시</div>
                    </div>
                  </div>
                  <div className="flex items-center gap-2 p-2 bg-white rounded border">
                    <FileText className="w-4 h-4 text-yellow-500" />
                    <div>
                      <div className="font-medium">작업일지</div>
                      <div className="text-xs text-gray-500">일별 작업 내역 기록</div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        )}
      </div>

      {/* 5. 품질검사 단계 상세 */}
      <div className="bg-white rounded-xl border overflow-hidden">
        <button
          onClick={() => toggleSection('quality')}
          className="w-full px-4 py-3 bg-teal-50 flex items-center justify-between hover:bg-teal-100 transition-colors"
        >
          <div className="flex items-center gap-2">
            {expandedSections.quality ? <ChevronDown className="w-4 h-4" /> : <ChevronRight className="w-4 h-4" />}
            <ShieldCheck className="w-5 h-5 text-teal-600" />
            <span className="font-medium text-teal-800">5. 품질검사 단계</span>
          </div>
          <span className="text-sm text-teal-600">품질팀</span>
        </button>
        {expandedSections.quality && (
          <div className="p-4 space-y-4">
            <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
              {/* IQC */}
              <div className="border rounded-lg p-4">
                <h4 className="font-medium text-gray-800 mb-2 flex items-center gap-2">
                  <Download className="w-4 h-4 text-teal-600" />
                  수입검사 (IQC)
                </h4>
                <ul className="text-sm text-gray-600 space-y-1">
                  <li>자재 입고 시 검사</li>
                  <li>LOT별 샘플 검사</li>
                  <li>합격 → 창고 입고</li>
                  <li>불합격 → 반품 처리</li>
                </ul>
                <div className="mt-2 text-xs text-gray-500">
                  시점: 자재 입고 시
                </div>
              </div>
              {/* PQC */}
              <div className="border rounded-lg p-4 border-teal-300 bg-teal-50">
                <h4 className="font-medium text-gray-800 mb-2 flex items-center gap-2">
                  <ClipboardList className="w-4 h-4 text-teal-600" />
                  중간검사 (PQC)
                </h4>
                <ul className="text-sm text-gray-600 space-y-1">
                  <li>공정 중 품질검사</li>
                  <li>작업지시별 검사</li>
                  <li>합격 → 다음 공정</li>
                  <li>불합격 → 재작업</li>
                </ul>
                <div className="mt-2 text-xs text-teal-700 font-medium">
                  시점: 각 공정 중간검사 단계
                </div>
              </div>
              {/* FQC */}
              <div className="border rounded-lg p-4">
                <h4 className="font-medium text-gray-800 mb-2 flex items-center gap-2">
                  <Package className="w-4 h-4 text-teal-600" />
                  제품검사 (FQC)
                </h4>
                <ul className="text-sm text-gray-600 space-y-1">
                  <li>출하 전 최종 검사</li>
                  <li>포장 상태 확인</li>
                  <li>합격 → 출하 가능</li>
                  <li>불합격 → 재포장/수리</li>
                </ul>
                <div className="mt-2 text-xs text-gray-500">
                  시점: 출하 전
                </div>
              </div>
              {/* 문서 출력 */}
              <div className="border rounded-lg p-4 bg-gray-50">
                <h4 className="font-medium text-gray-800 mb-2 flex items-center gap-2">
                  <Printer className="w-5 h-5 text-teal-600" />
                  문서 출력
                </h4>
                <div className="space-y-2 text-sm">
                  <div className="flex items-center gap-2 p-2 bg-white rounded border">
                    <FileText className="w-4 h-4 text-teal-500" />
                    <div>
                      <div className="font-medium">검사성적서</div>
                      <div className="text-xs text-gray-500">검사 결과 공식 문서</div>
                    </div>
                  </div>
                  <div className="flex items-center gap-2 p-2 bg-white rounded border">
                    <FileText className="w-4 h-4 text-teal-500" />
                    <div>
                      <div className="font-medium">부적합품 보고서</div>
                      <div className="text-xs text-gray-500">불합격 시 처리 보고</div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        )}
      </div>

      {/* 6. 출하 단계 상세 */}
      <div className="bg-white rounded-xl border overflow-hidden">
        <button
          onClick={() => toggleSection('shipment')}
          className="w-full px-4 py-3 bg-green-50 flex items-center justify-between hover:bg-green-100 transition-colors"
        >
          <div className="flex items-center gap-2">
            {expandedSections.shipment ? <ChevronDown className="w-4 h-4" /> : <ChevronRight className="w-4 h-4" />}
            <Truck className="w-5 h-5 text-green-600" />
            <span className="font-medium text-green-800">6. 출하 단계</span>
          </div>
          <span className="text-sm text-green-600">물류팀</span>
        </button>
        {expandedSections.shipment && (
          <div className="p-4 space-y-4">
            <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
              {/* 출하 조건 */}
              <div className="border rounded-lg p-4 border-red-200 bg-red-50">
                <h4 className="font-medium text-gray-800 mb-2 flex items-center gap-2">
                  <AlertCircle className="w-4 h-4 text-red-600" />
                  출하 조건 확인
                </h4>
                <ul className="text-sm text-gray-600 space-y-1">
                  <li>작업완료 상태 확인</li>
                  <li className="text-red-600 font-medium">B/C등급: 입금확인 필수</li>
                  <li className="text-red-600 font-medium">C등급: 경리승인 필수</li>
                  <li>세금계산서 발행 확인</li>
                </ul>
              </div>
              {/* 출하 등록 */}
              <div className="border rounded-lg p-4">
                <h4 className="font-medium text-gray-800 mb-2 flex items-center gap-2">
                  <span className="w-6 h-6 rounded-full bg-green-100 text-green-700 text-xs flex items-center justify-center">1</span>
                  출하 등록
                </h4>
                <ul className="text-sm text-gray-600 space-y-1 ml-8">
                  <li>수주 선택 (생산완료 건)</li>
                  <li>출하일자/우선순위 설정</li>
                  <li>배차 정보 입력</li>
                  <li>출고구역 이동</li>
                </ul>
              </div>
              {/* 배송 진행 */}
              <div className="border rounded-lg p-4">
                <h4 className="font-medium text-gray-800 mb-2 flex items-center gap-2">
                  <span className="w-6 h-6 rounded-full bg-green-100 text-green-700 text-xs flex items-center justify-center">2</span>
                  배송 진행
                </h4>
                <ul className="text-sm text-gray-600 space-y-1 ml-8">
                  <li>출고지시 → 출고준비</li>
                  <li>상차대기 → 배송중</li>
                  <li>배송완료 처리</li>
                  <li>수주 상태: 출하완료</li>
                </ul>
              </div>
              {/* 문서 출력 */}
              <div className="border rounded-lg p-4 bg-gray-50">
                <h4 className="font-medium text-gray-800 mb-2 flex items-center gap-2">
                  <Printer className="w-5 h-5 text-green-600" />
                  문서 출력
                </h4>
                <div className="space-y-2 text-sm">
                  <div className="flex items-center gap-2 p-2 bg-white rounded border">
                    <FileText className="w-4 h-4 text-green-500" />
                    <div>
                      <div className="font-medium">출고증</div>
                      <div className="text-xs text-gray-500">출고 확인용</div>
                    </div>
                  </div>
                  <div className="flex items-center gap-2 p-2 bg-white rounded border">
                    <FileText className="w-4 h-4 text-green-500" />
                    <div>
                      <div className="font-medium">거래명세서</div>
                      <div className="text-xs text-gray-500">거래 내역 명세</div>
                    </div>
                  </div>
                  <div className="flex items-center gap-2 p-2 bg-white rounded border">
                    <FileText className="w-4 h-4 text-green-500" />
                    <div>
                      <div className="font-medium">세금계산서</div>
                      <div className="text-xs text-gray-500">회계관리 연동</div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        )}
      </div>

      {/* 전체 문서 출력 시점 요약 */}
      <div className="bg-gray-50 rounded-xl border p-6">
        <h3 className="text-sm font-bold text-gray-700 mb-4 flex items-center gap-2">
          <Printer className="w-5 h-5" />
          문서 출력 시점 요약
        </h3>
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b bg-gray-100">
                <th className="text-left py-2 px-3">단계</th>
                <th className="text-left py-2 px-3">문서명</th>
                <th className="text-left py-2 px-3">출력 시점</th>
                <th className="text-left py-2 px-3">용도</th>
                <th className="text-left py-2 px-3">연동 데이터</th>
              </tr>
            </thead>
            <tbody>
              <tr className="border-b">
                <td className="py-2 px-3"><span className="px-2 py-0.5 bg-purple-100 text-purple-700 rounded text-xs">견적</span></td>
                <td className="py-2 px-3">견적서</td>
                <td className="py-2 px-3">견적 확정 후</td>
                <td className="py-2 px-3">고객 제출</td>
                <td className="py-2 px-3 text-xs text-gray-500">거래처, 품목, 단가, 견적수식</td>
              </tr>
              <tr className="border-b">
                <td className="py-2 px-3"><span className="px-2 py-0.5 bg-purple-100 text-purple-700 rounded text-xs">견적</span></td>
                <td className="py-2 px-3">산출내역서</td>
                <td className="py-2 px-3">견적 확정 후</td>
                <td className="py-2 px-3">내부/고객 검토</td>
                <td className="py-2 px-3 text-xs text-gray-500">BOM, 상세 산출 근거</td>
              </tr>
              <tr className="border-b">
                <td className="py-2 px-3"><span className="px-2 py-0.5 bg-blue-100 text-blue-700 rounded text-xs">수주</span></td>
                <td className="py-2 px-3">수주확인서</td>
                <td className="py-2 px-3">수주 확정 시</td>
                <td className="py-2 px-3">수주 확인</td>
                <td className="py-2 px-3 text-xs text-gray-500">견적 데이터 + 납기 정보</td>
              </tr>
              <tr className="border-b">
                <td className="py-2 px-3"><span className="px-2 py-0.5 bg-blue-100 text-blue-700 rounded text-xs">수주</span></td>
                <td className="py-2 px-3">발주서</td>
                <td className="py-2 px-3">수주 확정 후</td>
                <td className="py-2 px-3">구매품 발주</td>
                <td className="py-2 px-3 text-xs text-gray-500">구매품 목록, 거래처 정보</td>
              </tr>
              <tr className="border-b">
                <td className="py-2 px-3"><span className="px-2 py-0.5 bg-orange-100 text-orange-700 rounded text-xs">생산지시</span></td>
                <td className="py-2 px-3">생산지시서</td>
                <td className="py-2 px-3">생산지시 생성 시</td>
                <td className="py-2 px-3">생산팀 전달</td>
                <td className="py-2 px-3 text-xs text-gray-500">공정별 품목, BOM, 우선순위</td>
              </tr>
              <tr className="border-b">
                <td className="py-2 px-3"><span className="px-2 py-0.5 bg-yellow-100 text-yellow-700 rounded text-xs">작업지시</span></td>
                <td className="py-2 px-3">작업지시서</td>
                <td className="py-2 px-3">작업지시 생성 시</td>
                <td className="py-2 px-3">작업자 전달</td>
                <td className="py-2 px-3 text-xs text-gray-500">공정단계, 품목상세, 작업자</td>
              </tr>
              <tr className="border-b">
                <td className="py-2 px-3"><span className="px-2 py-0.5 bg-yellow-100 text-yellow-700 rounded text-xs">작업지시</span></td>
                <td className="py-2 px-3">작업일지</td>
                <td className="py-2 px-3">작업 완료 시</td>
                <td className="py-2 px-3">작업 기록</td>
                <td className="py-2 px-3 text-xs text-gray-500">일별 작업내역, 투입자재LOT</td>
              </tr>
              <tr className="border-b">
                <td className="py-2 px-3"><span className="px-2 py-0.5 bg-teal-100 text-teal-700 rounded text-xs">품질검사</span></td>
                <td className="py-2 px-3">검사성적서</td>
                <td className="py-2 px-3">검사 완료 시</td>
                <td className="py-2 px-3">품질 증빙</td>
                <td className="py-2 px-3 text-xs text-gray-500">검사항목, 결과, 판정</td>
              </tr>
              <tr className="border-b">
                <td className="py-2 px-3"><span className="px-2 py-0.5 bg-green-100 text-green-700 rounded text-xs">출하</span></td>
                <td className="py-2 px-3">출고증</td>
                <td className="py-2 px-3">출하 시</td>
                <td className="py-2 px-3">출고 확인</td>
                <td className="py-2 px-3 text-xs text-gray-500">출하품목, 수량, 배송정보</td>
              </tr>
              <tr className="border-b">
                <td className="py-2 px-3"><span className="px-2 py-0.5 bg-green-100 text-green-700 rounded text-xs">출하</span></td>
                <td className="py-2 px-3">거래명세서</td>
                <td className="py-2 px-3">출하 완료 시</td>
                <td className="py-2 px-3">거래 기록</td>
                <td className="py-2 px-3 text-xs text-gray-500">품목, 금액, 거래처 정보</td>
              </tr>
              <tr>
                <td className="py-2 px-3"><span className="px-2 py-0.5 bg-green-100 text-green-700 rounded text-xs">출하</span></td>
                <td className="py-2 px-3">세금계산서</td>
                <td className="py-2 px-3">출하 완료 시</td>
                <td className="py-2 px-3">회계 처리</td>
                <td className="py-2 px-3 text-xs text-gray-500">회계관리 데이터</td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>

      {/* 데이터 연동 흐름 */}
      <div className="bg-white rounded-xl border p-6">
        <h3 className="text-sm font-bold text-gray-700 mb-4">데이터 연동 흐름</h3>
        <div className="bg-gray-50 rounded-lg p-4 text-sm font-mono">
          <div className="space-y-2">
            <div className="flex items-center gap-2">
              <span className="px-2 py-0.5 bg-purple-100 text-purple-700 rounded">견적</span>
              <span className="text-gray-400">→</span>
              <span className="text-gray-600">quoteNo, items[], customerInfo, siteInfo, totalAmount</span>
            </div>
            <div className="flex items-center gap-2 pl-8">
              <span className="text-gray-400">↓</span>
              <span className="text-xs text-gray-500">수주전환 시 자동 복사</span>
            </div>
            <div className="flex items-center gap-2">
              <span className="px-2 py-0.5 bg-blue-100 text-blue-700 rounded">수주</span>
              <span className="text-gray-400">→</span>
              <span className="text-gray-600">orderNo, quoteNo(연결), dueDate, deliveryInfo, creditGrade</span>
            </div>
            <div className="flex items-center gap-2 pl-8">
              <span className="text-gray-400">↓</span>
              <span className="text-xs text-gray-500">생산지시 생성 시 BOM 기반 공정 분류</span>
            </div>
            <div className="flex items-center gap-2">
              <span className="px-2 py-0.5 bg-orange-100 text-orange-700 rounded">생산지시</span>
              <span className="text-gray-400">→</span>
              <span className="text-gray-600">productionOrderNo, orderNo(연결), processGroups[], priority</span>
            </div>
            <div className="flex items-center gap-2 pl-8">
              <span className="text-gray-400">↓</span>
              <span className="text-xs text-gray-500">공정별 작업지시 자동 생성</span>
            </div>
            <div className="flex items-center gap-2">
              <span className="px-2 py-0.5 bg-yellow-100 text-yellow-700 rounded">작업지시</span>
              <span className="text-gray-400">→</span>
              <span className="text-gray-600">workOrderNo, productionOrderNo(연결), processCode, items[], stepStatus</span>
            </div>
            <div className="flex items-center gap-2 pl-8">
              <span className="text-gray-400">↓</span>
              <span className="text-xs text-gray-500">작업완료 시 수주 상태 업데이트</span>
            </div>
            <div className="flex items-center gap-2">
              <span className="px-2 py-0.5 bg-green-100 text-green-700 rounded">출하</span>
              <span className="text-gray-400">→</span>
              <span className="text-gray-600">shipmentNo, orderNo(연결), shipmentDate, dispatchInfo, paymentStatus</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export { classifyItemToProcess, processClassificationRules };
export default DetailedProcessFlowChart;
