/**
 * 프로세스별 실제 통합 테스트 탭
 * - 각 프로세스별 10건씩 실제 데이터 생성
 * - localStorage에 저장
 * - 채번관리 검증
 * - 단일/통합/프로세스별 테스트 지원
 */
import React, { useState, useCallback, useEffect } from 'react';
import {
  Play, RefreshCw, CheckCircle, XCircle, ChevronDown, ChevronRight,
  Database, FileText, Package, Truck, ClipboardCheck, DollarSign,
  Settings, Layers, AlertTriangle, BarChart3, Trash2, Download,
  Eye, EyeOff
} from 'lucide-react';

import {
  runAllRealProcessTests,
  testMasterDataProcess,
  testQuoteProcess,
  testOrderProcess,
  testMaterialReceiptProcess,
  testWorkProgressProcess,
  testPQCProcess,
  testShipmentProcess,
  testFQCAndSalesProcess,
  clearAllTestData,
  getTestResults,
  getTestDataByProcess,
} from '../utils/mesRealProcessTest';

import {
  validateNumberingRules,
} from '../utils/processIntegrationTest';

import { resetAllSequences } from '../utils/mesCompleteIntegration';

// 프로세스 정의
const PROCESSES = [
  { id: 'master', name: '기준정보', icon: Database, color: 'purple', test: testMasterDataProcess, description: '거래처/현장/품목 각 10건 생성' },
  { id: 'quote', name: '견적', icon: FileText, color: 'blue', test: testQuoteProcess, description: '견적번호 KD-PR-YYMMDD-## 10건' },
  { id: 'order', name: '수주/생산지시', icon: Layers, color: 'green', test: testOrderProcess, description: '수주번호 KD-TS/SL/BD + 작업지시 KD-WO 10건' },
  { id: 'material', name: '자재입고(입고LOT)', icon: Package, color: 'orange', test: testMaterialReceiptProcess, description: '입고LOT YYMMDD-## 10건' },
  { id: 'work', name: '작업진행', icon: Settings, color: 'yellow', test: testWorkProgressProcess, description: '작업일지 KD-WO-YYMMDD-## 10건' },
  { id: 'pqc', name: '중간검사(PQC)', icon: ClipboardCheck, color: 'indigo', test: testPQCProcess, description: '중간검사LOT KD-WE-YYMMDD-## 10건' },
  { id: 'shipment', name: '출하/입금', icon: Truck, color: 'teal', test: testShipmentProcess, description: '출하번호 KD-SH-YYMMDD-## 10건' },
  { id: 'fqc', name: '최종검사(FQC)/매출', icon: DollarSign, color: 'pink', test: testFQCAndSalesProcess, description: '최종검사LOT KD-SA-YYMMDD-## + 매출 10건' },
];

const ProcessIntegrationTestTab = () => {
  const [testMode, setTestMode] = useState('all'); // 'all', 'single', 'numbering'
  const [selectedProcess, setSelectedProcess] = useState(null);
  const [isRunning, setIsRunning] = useState(false);
  const [testResults, setTestResults] = useState(null);
  const [numberingResults, setNumberingResults] = useState(null);
  const [expandedProcesses, setExpandedProcesses] = useState({});
  const [expandedTests, setExpandedTests] = useState({});
  const [showRawData, setShowRawData] = useState(false);

  // 이전 테스트 결과 로드
  useEffect(() => {
    const savedResults = getTestResults();
    if (savedResults && savedResults.summary) {
      setTestResults(savedResults);
    }
  }, []);

  // 데이터 초기화
  const handleClearData = useCallback(() => {
    if (window.confirm('모든 테스트 데이터를 삭제하시겠습니까?')) {
      clearAllTestData();
      setTestResults(null);
      setNumberingResults(null);
      alert('모든 테스트 데이터가 삭제되었습니다.');
    }
  }, []);

  // 테스트 실행
  const handleRunTests = useCallback(() => {
    setIsRunning(true);
    setTestResults(null);
    setNumberingResults(null);

    // 약간의 딜레이 후 실행 (UI 업데이트를 위해)
    setTimeout(() => {
      try {
        if (testMode === 'all') {
          console.log('전체 통합 테스트 시작...');
          const results = runAllRealProcessTests();
          setTestResults(results);
          console.log('전체 통합 테스트 완료!', results);
        } else if (testMode === 'single' && selectedProcess) {
          console.log(`단일 프로세스 테스트 시작: ${selectedProcess}`);
          resetAllSequences();
          const process = PROCESSES.find(p => p.id === selectedProcess);
          if (process) {
            const result = process.test();
            setTestResults({
              summary: {
                totalProcesses: 1,
                totalTests: result?.tests?.length || 0,
                totalItems: result?.totalItems || 0,
                passedTests: result?.passedTests || 0,
                failedTests: result?.failedTests || 0,
              },
              processes: { [result?.processName || process.name]: result },
            });
          }
        } else if (testMode === 'numbering') {
          console.log('채번관리 검증 시작...');
          resetAllSequences();
          const results = validateNumberingRules();
          setNumberingResults(results);
          console.log('채번관리 검증 완료!', results);
        }
      } catch (error) {
        console.error('테스트 실행 오류:', error);
        setTestResults({ error: error.message, stack: error.stack });
      }
      setIsRunning(false);
    }, 100);
  }, [testMode, selectedProcess]);

  // 프로세스 확장/축소 토글
  const toggleProcessExpand = (processName) => {
    setExpandedProcesses(prev => ({
      ...prev,
      [processName]: !prev[processName],
    }));
  };

  // 테스트 확장/축소 토글
  const toggleTestExpand = (processName, testName) => {
    const key = `${processName}-${testName}`;
    setExpandedTests(prev => ({
      ...prev,
      [key]: !prev[key],
    }));
  };

  // 성공률에 따른 색상
  const getSuccessRateColor = (rate) => {
    if (rate >= 90) return 'text-green-600';
    if (rate >= 70) return 'text-yellow-600';
    return 'text-red-600';
  };

  // 결과 다운로드
  const handleDownloadResults = () => {
    const dataStr = JSON.stringify(testResults, null, 2);
    const blob = new Blob([dataStr], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `mes_test_results_${new Date().toISOString().split('T')[0]}.json`;
    link.click();
    URL.revokeObjectURL(url);
  };

  return (
    <div className="space-y-6">
      {/* 헤더 */}
      <div className="bg-gradient-to-r from-indigo-600 to-purple-600 text-white rounded-xl p-6">
        <div className="flex items-center justify-between">
          <div>
            <h2 className="text-2xl font-bold mb-2">MES 실제 프로세스 통합 테스트</h2>
            <p className="opacity-90">
              각 프로세스별 10건씩 실제 데이터 생성 + localStorage 저장 + 채번관리 검증
            </p>
          </div>
          <div className="flex gap-2">
            <button
              onClick={handleClearData}
              className="px-3 py-2 bg-red-500 hover:bg-red-600 rounded-lg text-sm flex items-center gap-1"
            >
              <Trash2 className="w-4 h-4" />
              데이터 초기화
            </button>
            {testResults && !testResults.error && (
              <button
                onClick={handleDownloadResults}
                className="px-3 py-2 bg-white/20 hover:bg-white/30 rounded-lg text-sm flex items-center gap-1"
              >
                <Download className="w-4 h-4" />
                결과 다운로드
              </button>
            )}
          </div>
        </div>
        <div className="mt-4 flex flex-wrap gap-2">
          {PROCESSES.map(p => (
            <span key={p.id} className="px-2 py-1 bg-white/20 rounded text-sm flex items-center gap-1">
              <p.icon className="w-3 h-3" />
              {p.name}
            </span>
          ))}
        </div>
      </div>

      {/* 테스트 모드 선택 */}
      <div className="bg-white rounded-xl p-6 border">
        <h3 className="text-lg font-bold mb-4">테스트 모드 선택</h3>
        <div className="grid grid-cols-3 gap-4">
          {/* 전체 테스트 */}
          <button
            onClick={() => setTestMode('all')}
            className={`p-4 rounded-xl border-2 transition-all ${
              testMode === 'all'
                ? 'border-indigo-500 bg-indigo-50'
                : 'border-gray-200 hover:border-gray-300'
            }`}
          >
            <div className="text-center">
              <BarChart3 className={`w-8 h-8 mx-auto mb-2 ${testMode === 'all' ? 'text-indigo-600' : 'text-gray-400'}`} />
              <p className="font-bold">전체 통합 테스트</p>
              <p className="text-sm text-gray-500 mt-1">8개 프로세스 × 10건 = 80건 이상</p>
            </div>
          </button>

          {/* 단일 프로세스 테스트 */}
          <button
            onClick={() => setTestMode('single')}
            className={`p-4 rounded-xl border-2 transition-all ${
              testMode === 'single'
                ? 'border-green-500 bg-green-50'
                : 'border-gray-200 hover:border-gray-300'
            }`}
          >
            <div className="text-center">
              <Settings className={`w-8 h-8 mx-auto mb-2 ${testMode === 'single' ? 'text-green-600' : 'text-gray-400'}`} />
              <p className="font-bold">단일 프로세스 테스트</p>
              <p className="text-sm text-gray-500 mt-1">특정 프로세스만 10건 테스트</p>
            </div>
          </button>

          {/* 채번관리 검증 */}
          <button
            onClick={() => setTestMode('numbering')}
            className={`p-4 rounded-xl border-2 transition-all ${
              testMode === 'numbering'
                ? 'border-orange-500 bg-orange-50'
                : 'border-gray-200 hover:border-gray-300'
            }`}
          >
            <div className="text-center">
              <FileText className={`w-8 h-8 mx-auto mb-2 ${testMode === 'numbering' ? 'text-orange-600' : 'text-gray-400'}`} />
              <p className="font-bold">채번관리 검증</p>
              <p className="text-sm text-gray-500 mt-1">11개 문서유형 패턴 검증</p>
            </div>
          </button>
        </div>

        {/* 단일 프로세스 선택 */}
        {testMode === 'single' && (
          <div className="mt-4 p-4 bg-gray-50 rounded-lg">
            <p className="text-sm text-gray-600 mb-3">테스트할 프로세스를 선택하세요:</p>
            <div className="grid grid-cols-2 gap-2">
              {PROCESSES.map(p => (
                <button
                  key={p.id}
                  onClick={() => setSelectedProcess(p.id)}
                  className={`p-3 rounded-lg border text-sm text-left ${
                    selectedProcess === p.id
                      ? 'border-green-500 bg-green-100 text-green-700'
                      : 'border-gray-200 hover:border-gray-300'
                  }`}
                >
                  <div className="flex items-center gap-2 mb-1">
                    <p.icon className="w-4 h-4" />
                    <span className="font-medium">{p.name}</span>
                  </div>
                  <p className="text-xs text-gray-500">{p.description}</p>
                </button>
              ))}
            </div>
          </div>
        )}
      </div>

      {/* 테스트 실행 버튼 */}
      <div className="flex justify-center">
        <button
          onClick={handleRunTests}
          disabled={isRunning || (testMode === 'single' && !selectedProcess)}
          className={`px-8 py-4 rounded-xl text-white font-bold text-lg flex items-center gap-3 ${
            isRunning || (testMode === 'single' && !selectedProcess)
              ? 'bg-gray-400 cursor-not-allowed'
              : 'bg-gradient-to-r from-indigo-600 to-purple-600 hover:from-indigo-700 hover:to-purple-700'
          }`}
        >
          {isRunning ? (
            <>
              <RefreshCw className="w-6 h-6 animate-spin" />
              테스트 실행 중... (콘솔 확인)
            </>
          ) : (
            <>
              <Play className="w-6 h-6" />
              {testMode === 'all' ? '전체 통합 테스트 실행 (10건×8)' :
               testMode === 'single' ? '단일 프로세스 테스트 실행 (10건)' :
               '채번관리 검증 실행'}
            </>
          )}
        </button>
      </div>

      {/* 채번관리 검증 결과 */}
      {testMode === 'numbering' && numberingResults && (
        <div className="bg-white rounded-xl p-6 border">
          <h3 className="text-lg font-bold mb-4 flex items-center gap-2">
            <FileText className="w-5 h-5 text-orange-500" />
            채번관리 검증 결과 ({numberingResults.date})
          </h3>

          {/* 요약 */}
          <div className="grid grid-cols-3 gap-4 mb-6">
            <div className="bg-gray-50 rounded-lg p-4 text-center">
              <p className="text-2xl font-bold">{numberingResults.summary.total}</p>
              <p className="text-sm text-gray-600">총 검증 항목</p>
            </div>
            <div className="bg-green-50 rounded-lg p-4 text-center">
              <p className="text-2xl font-bold text-green-600">{numberingResults.summary.passed}</p>
              <p className="text-sm text-gray-600">통과</p>
            </div>
            <div className="bg-red-50 rounded-lg p-4 text-center">
              <p className="text-2xl font-bold text-red-600">{numberingResults.summary.failed}</p>
              <p className="text-sm text-gray-600">실패</p>
            </div>
          </div>

          {/* 상세 결과 */}
          <table className="w-full text-sm border">
            <thead className="bg-gray-100">
              <tr>
                <th className="p-3 text-left border">적용대상</th>
                <th className="p-3 text-left border">예상 접두사</th>
                <th className="p-3 text-left border">예상 패턴</th>
                <th className="p-3 text-left border">생성된 번호</th>
                <th className="p-3 text-center border">결과</th>
              </tr>
            </thead>
            <tbody>
              {numberingResults.validations.map((v, idx) => (
                <tr key={idx} className={v.valid ? '' : 'bg-red-50'}>
                  <td className="p-3 border font-medium">{v.target}</td>
                  <td className="p-3 border font-mono text-blue-600">{v.expectedPrefix}</td>
                  <td className="p-3 border font-mono text-gray-600">{v.expectedPattern}</td>
                  <td className="p-3 border font-mono font-bold">{v.generated}</td>
                  <td className="p-3 border text-center">
                    {v.valid ? (
                      <CheckCircle className="w-5 h-5 text-green-500 mx-auto" />
                    ) : (
                      <XCircle className="w-5 h-5 text-red-500 mx-auto" />
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {/* 테스트 결과 */}
      {testResults && !testResults.error && testResults.processes && (
        <div className="space-y-4">
          {/* 결과 요약 */}
          <div className="bg-white rounded-xl p-6 border">
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-lg font-bold flex items-center gap-2">
                <CheckCircle className="w-5 h-5 text-green-500" />
                테스트 결과 요약
              </h3>
              <button
                onClick={() => setShowRawData(!showRawData)}
                className="px-3 py-1 text-sm border rounded flex items-center gap-1 hover:bg-gray-50"
              >
                {showRawData ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                {showRawData ? '요약 보기' : '상세 데이터'}
              </button>
            </div>

            <div className="grid grid-cols-6 gap-4 mb-6">
              <div className="bg-gray-50 rounded-lg p-4 text-center">
                <p className="text-2xl font-bold">{testResults.summary?.totalProcesses || 0}</p>
                <p className="text-sm text-gray-600">프로세스</p>
              </div>
              <div className="bg-blue-50 rounded-lg p-4 text-center">
                <p className="text-2xl font-bold text-blue-600">{testResults.summary?.totalTests || 0}</p>
                <p className="text-sm text-gray-600">테스트</p>
              </div>
              <div className="bg-purple-50 rounded-lg p-4 text-center">
                <p className="text-2xl font-bold text-purple-600">{testResults.summary?.totalItems || 0}</p>
                <p className="text-sm text-gray-600">데이터</p>
              </div>
              <div className="bg-green-50 rounded-lg p-4 text-center">
                <p className="text-2xl font-bold text-green-600">{testResults.summary?.passedTests || 0}</p>
                <p className="text-sm text-gray-600">성공</p>
              </div>
              <div className="bg-red-50 rounded-lg p-4 text-center">
                <p className="text-2xl font-bold text-red-600">{testResults.summary?.failedTests || 0}</p>
                <p className="text-sm text-gray-600">실패</p>
              </div>
              <div className="bg-indigo-50 rounded-lg p-4 text-center">
                <p className={`text-2xl font-bold ${getSuccessRateColor(
                  (testResults.summary?.passedTests || 0) / (testResults.summary?.totalTests || 1) * 100
                )}`}>
                  {((testResults.summary?.passedTests || 0) / (testResults.summary?.totalTests || 1) * 100).toFixed(1)}%
                </p>
                <p className="text-sm text-gray-600">성공률</p>
              </div>
            </div>

            {testResults.summary?.duration && (
              <p className="text-sm text-gray-500 text-right">소요시간: {testResults.summary.duration}</p>
            )}
          </div>

          {/* 프로세스별 상세 결과 */}
          {Object.entries(testResults.processes).map(([processName, process], pIdx) => {
            const processInfo = PROCESSES.find(p => p.name === processName);
            const Icon = processInfo?.icon || Settings;
            const allPassed = process.failedTests === 0;
            const isExpanded = expandedProcesses[processName];

            return (
              <div key={pIdx} className="bg-white rounded-xl border overflow-hidden">
                {/* 프로세스 헤더 */}
                <div
                  onClick={() => toggleProcessExpand(processName)}
                  className={`p-4 ${allPassed ? 'bg-green-50' : 'bg-red-50'} border-b cursor-pointer hover:opacity-90`}
                >
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-3">
                      {isExpanded ? <ChevronDown className="w-5 h-5" /> : <ChevronRight className="w-5 h-5" />}
                      <Icon className={`w-6 h-6 ${allPassed ? 'text-green-600' : 'text-red-600'}`} />
                      <span className="font-bold text-lg">{processName}</span>
                      <span className={`px-2 py-1 rounded text-sm ${
                        allPassed ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'
                      }`}>
                        {allPassed ? '모두 통과' : `${process.failedTests}건 실패`}
                      </span>
                    </div>
                    <div className="flex items-center gap-4 text-sm">
                      <span className="text-purple-600">데이터: {process.totalItems}건</span>
                      <span className="text-green-600">통과: {process.passedTests}</span>
                      <span className="text-red-600">실패: {process.failedTests}</span>
                    </div>
                  </div>
                </div>

                {/* 테스트 목록 */}
                {isExpanded && (
                  <div className="divide-y">
                    {process.tests?.map((test, tIdx) => {
                      const testKey = `${processName}-${test.name}`;
                      const isTestExpanded = expandedTests[testKey];

                      return (
                        <div key={tIdx}>
                          {/* 테스트 헤더 */}
                          <div
                            onClick={() => toggleTestExpand(processName, test.name)}
                            className={`p-3 cursor-pointer hover:bg-gray-50 flex items-center justify-between ${
                              !test.passed ? 'bg-red-50' : ''
                            }`}
                          >
                            <div className="flex items-center gap-3">
                              {isTestExpanded ? (
                                <ChevronDown className="w-4 h-4 text-gray-400" />
                              ) : (
                                <ChevronRight className="w-4 h-4 text-gray-400" />
                              )}
                              {test.passed ? (
                                <CheckCircle className="w-5 h-5 text-green-500" />
                              ) : (
                                <XCircle className="w-5 h-5 text-red-500" />
                              )}
                              <span className="font-medium">{test.name}</span>
                            </div>
                            <span className="text-sm text-gray-500">
                              {test.itemCount || test.items?.length || 0}개 항목
                            </span>
                          </div>

                          {/* 테스트 상세 */}
                          {isTestExpanded && test.items && test.items.length > 0 && (
                            <div className="p-4 bg-gray-50 border-t">
                              <div className="overflow-x-auto">
                                <table className="w-full text-sm">
                                  <thead className="bg-white">
                                    <tr>
                                      <th className="p-2 text-left border">#</th>
                                      {Object.keys(test.items[0] || {})
                                        .filter(k => k !== 'seq' && k !== 'valid' && k !== 'id' && k !== 'createdAt')
                                        .slice(0, showRawData ? undefined : 6)
                                        .map(key => (
                                          <th key={key} className="p-2 text-left border whitespace-nowrap">
                                            {key}
                                          </th>
                                        ))}
                                      <th className="p-2 text-center border">결과</th>
                                    </tr>
                                  </thead>
                                  <tbody>
                                    {test.items.map((item, iIdx) => (
                                      <tr key={iIdx} className={item.valid ? '' : 'bg-red-100'}>
                                        <td className="p-2 border">{item.seq || iIdx + 1}</td>
                                        {Object.entries(item)
                                          .filter(([k]) => k !== 'seq' && k !== 'valid' && k !== 'id' && k !== 'createdAt')
                                          .slice(0, showRawData ? undefined : 6)
                                          .map(([key, value]) => (
                                            <td
                                              key={key}
                                              className={`p-2 border ${
                                                key.toLowerCase().includes('no') ||
                                                key.toLowerCase().includes('code') ||
                                                key.toLowerCase().includes('pattern')
                                                  ? 'font-mono text-blue-600'
                                                  : ''
                                              }`}
                                            >
                                              {typeof value === 'boolean' ? (value ? 'O' : 'X') :
                                               typeof value === 'number' ? value.toLocaleString() :
                                               typeof value === 'object' ? JSON.stringify(value).substring(0, 50) :
                                               String(value || '-').substring(0, 50)}
                                            </td>
                                          ))}
                                        <td className="p-2 border text-center">
                                          {item.valid ? (
                                            <CheckCircle className="w-4 h-4 text-green-500 mx-auto" />
                                          ) : (
                                            <XCircle className="w-4 h-4 text-red-500 mx-auto" />
                                          )}
                                        </td>
                                      </tr>
                                    ))}
                                  </tbody>
                                </table>
                              </div>
                            </div>
                          )}
                        </div>
                      );
                    })}
                  </div>
                )}
              </div>
            );
          })}
        </div>
      )}

      {/* 에러 표시 */}
      {testResults?.error && (
        <div className="bg-red-50 border border-red-200 rounded-xl p-6">
          <div className="flex items-center gap-3 mb-4">
            <AlertTriangle className="w-6 h-6 text-red-500" />
            <h3 className="text-lg font-bold text-red-600">테스트 실행 오류</h3>
          </div>
          <pre className="p-4 bg-red-100 rounded text-sm text-red-800 overflow-auto">
            {testResults.error}
            {testResults.stack && `\n\nStack:\n${testResults.stack}`}
          </pre>
        </div>
      )}

      {/* 프로세스 흐름도 */}
      <div className="bg-white rounded-xl p-6 border">
        <h3 className="text-lg font-bold mb-4">MES 전체 프로세스 흐름 (채번관리)</h3>
        <div className="flex flex-wrap items-center gap-2 text-sm">
          {[
            { step: '1. 기준정보', items: 'C-###, PJ-YYMMDD-##' },
            { step: '2. 견적', items: 'KD-PR-YYMMDD-##' },
            { step: '3. 수주', items: 'KD-TS/SL/BD-YYMMDD-##' },
            { step: '4. 자재입고', items: '입고LOT: YYMMDD-##' },
            { step: '5. 생산지시', items: 'KD-PL-YYMMDD-##' },
            { step: '6. 작업지시', items: 'KD-WO-YYMMDD-##' },
            { step: '7. 중간검사', items: 'KD-WE-YYMMDD-##' },
            { step: '8. 입금확인', items: '계약금 30%' },
            { step: '9. 출하', items: 'KD-SH-YYMMDD-##' },
            { step: '10. 최종검사', items: 'KD-SA-YYMMDD-##' },
            { step: '11. 매출확정', items: '잔금 70%' },
          ].map((item, idx) => (
            <React.Fragment key={idx}>
              <div className="px-3 py-2 rounded-lg bg-gradient-to-br from-indigo-50 to-purple-50 border">
                <p className="font-bold text-indigo-700">{item.step}</p>
                <p className="text-xs text-gray-500 font-mono">{item.items}</p>
              </div>
              {idx < 10 && <span className="text-gray-400 text-lg">→</span>}
            </React.Fragment>
          ))}
        </div>
      </div>
    </div>
  );
};

export default ProcessIntegrationTestTab;
