"use client";

import React, { useState } from "react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Progress } from "@/components/ui/progress";
import StressTestSuite from "../../test-scenarios/stress-test-scenarios";

interface TestResult {
  testName: string;
  status: "passed" | "failed" | "warning";
  duration: number;
  details: string;
  metrics?: any;
}

interface StressTestResults {
  success: boolean;
  totalTests: number;
  passedTests: number;
  failedTests: number;
  warningTests: number;
  totalDuration: number;
  results: TestResult[];
  recommendation: string[];
}

export default function StressTestPage() {
  const [isRunning, setIsRunning] = useState(false);
  const [currentTest, setCurrentTest] = useState<string>("");
  const [progress, setProgress] = useState(0);
  const [testResults, setTestResults] = useState<StressTestResults | null>(null);
  const [testLogs, setTestLogs] = useState<string[]>([]);

  const runStressTests = async () => {
    setIsRunning(true);
    setTestResults(null);
    setTestLogs([]);
    setProgress(0);

    // 콘솔 로그를 캡처하기 위한 오버라이드
    const originalLog = console.log;
    const capturedLogs: string[] = [];

    console.log = (...args) => {
      const logMessage = args.join(" ");
      capturedLogs.push(logMessage);
      setTestLogs((prev) => [...prev, logMessage]);
      originalLog(...args);
    };

    try {
      // 개별 테스트 진행 상황 모니터링
      const testNames = [
        "대량 데이터 처리",
        "타입 오염 및 손상",
        "동시 작업 및 경합 상태",
        "메모리 부하 및 가비지 컬렉션",
        "API 스트레스 및 네트워크 시뮬레이션",
      ];

      // 각 테스트 시작 시 진행률 업데이트
      let completedTests = 0;

      const updateProgress = (testName: string) => {
        setCurrentTest(testName);
        setProgress((completedTests / testNames.length) * 100);
      };

      // 테스트 실행 (실제로는 StressTestSuite.runAllStressTests()가 모든 테스트를 순차 실행)
      updateProgress(testNames[0]);

      // 진행률 시뮬레이션을 위한 간격 업데이트
      const progressInterval = setInterval(() => {
        completedTests = Math.min(completedTests + 0.1, testNames.length - 0.1);
        const currentTestIndex = Math.floor(completedTests);
        if (currentTestIndex < testNames.length) {
          setCurrentTest(testNames[currentTestIndex]);
        }
        setProgress((completedTests / testNames.length) * 100);
      }, 200);

      const results = await StressTestSuite.runAllStressTests();

      clearInterval(progressInterval);
      setProgress(100);
      setCurrentTest("완료");
      setTestResults(results as StressTestResults);
    } catch (error) {
      console.error("스트레스 테스트 실행 중 오류:", error);
      setTestResults({
        success: false,
        totalTests: 0,
        passedTests: 0,
        failedTests: 1,
        warningTests: 0,
        totalDuration: 0,
        results: [],
        recommendation: [`스트레스 테스트 실행 중 오류가 발생했습니다: ${error}`],
      });
    } finally {
      // 콘솔 로그 복원
      console.log = originalLog;
      setIsRunning(false);
      setCurrentTest("");
    }
  };

  const getStatusBadgeVariant = (status: string) => {
    switch (status) {
      case "passed":
        return "default";
      case "failed":
        return "destructive";
      case "warning":
        return "secondary";
      default:
        return "outline";
    }
  };

  const getStatusIcon = (status: string) => {
    switch (status) {
      case "passed":
        return "✅";
      case "failed":
        return "❌";
      case "warning":
        return "⚠️";
      default:
        return "❓";
    }
  };

  return (
    <div className="container mx-auto space-y-6 p-6">
      <div className="space-y-4 text-center">
        <h1 className="text-3xl font-bold">🔥 타입 시스템 스트레스 테스트</h1>
        <p className="text-muted-foreground">극한 상황에서 타입 시스템의 견고함과 성능을 검증합니다</p>
        <div className="rounded-lg bg-amber-50 p-3 text-sm text-amber-600">
          ⚠️ 주의: 이 테스트는 시스템에 높은 부하를 가할 수 있습니다
        </div>

        <Button
          onClick={runStressTests}
          disabled={isRunning}
          size="lg"
          className="bg-gradient-to-r from-red-500 to-orange-500 hover:from-red-600 hover:to-orange-600"
        >
          {isRunning ? "🔥 스트레스 테스트 실행 중..." : "🚀 스트레스 테스트 시작"}
        </Button>
      </div>

      {/* 진행률 표시 */}
      {isRunning && (
        <Card>
          <CardHeader>
            <CardTitle className="text-xl">📊 테스트 진행 상황</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="space-y-2">
              <div className="flex justify-between text-sm">
                <span>현재 테스트: {currentTest}</span>
                <span>{Math.round(progress)}%</span>
              </div>
              <Progress value={progress} className="h-3" />
            </div>
          </CardContent>
        </Card>
      )}

      {/* 테스트 결과 */}
      {testResults && (
        <div className="space-y-6">
          {/* 요약 */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2 text-2xl">
                📈 스트레스 테스트 결과 요약
                {testResults.success ? "🎉" : "⚠️"}
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="grid grid-cols-2 gap-4 md:grid-cols-4">
                <div className="text-center">
                  <div className="text-2xl font-bold text-emerald-600">{testResults.passedTests}</div>
                  <div className="text-muted-foreground text-sm">통과</div>
                </div>
                <div className="text-center">
                  <div className="text-2xl font-bold text-destructive">{testResults.failedTests}</div>
                  <div className="text-muted-foreground text-sm">실패</div>
                </div>
                <div className="text-center">
                  <div className="text-2xl font-bold text-amber-600">{testResults.warningTests}</div>
                  <div className="text-muted-foreground text-sm">경고</div>
                </div>
                <div className="text-center">
                  <div className="text-2xl font-bold text-primary">{Math.round(testResults.totalDuration)}ms</div>
                  <div className="text-muted-foreground text-sm">총 소요시간</div>
                </div>
              </div>

              <div className="text-center">
                <div className="text-lg font-semibold">
                  성공률:{" "}
                  {testResults.totalTests > 0
                    ? Math.round((testResults.passedTests / testResults.totalTests) * 100)
                    : 0}
                  %
                </div>
              </div>

              {testResults.success ? (
                <div className="rounded-lg border border-emerald-200 bg-emerald-50 p-4">
                  <div className="font-medium text-emerald-800">🎉 모든 스트레스 테스트 통과!</div>
                  <div className="mt-2 text-sm text-emerald-600">
                    타입 시스템이 극한 상황에서도 안정적으로 작동합니다.
                  </div>
                </div>
              ) : (
                <div className="rounded-lg border border-destructive/20 bg-destructive/10 p-4">
                  <div className="font-medium text-red-800">⚠️ 일부 스트레스 테스트 실패</div>
                  <div className="mt-2 text-sm text-destructive">
                    개선이 필요한 영역이 있습니다. 아래 권장사항을 확인하세요.
                  </div>
                </div>
              )}
            </CardContent>
          </Card>

          {/* 개별 테스트 결과 */}
          <Card>
            <CardHeader>
              <CardTitle className="text-xl">🔍 개별 테스트 상세 결과</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              {testResults.results.map((result, index) => (
                <div key={index} className="rounded-lg border p-4">
                  <div className="mb-2 flex items-center justify-between">
                    <div className="flex items-center gap-2">
                      <span className="text-lg">{getStatusIcon(result.status)}</span>
                      <h3 className="font-semibold">{result.testName}</h3>
                    </div>
                    <Badge variant={getStatusBadgeVariant(result.status)}>
                      {result.status === "passed" ? "통과" : result.status === "failed" ? "실패" : "경고"}
                    </Badge>
                  </div>

                  <div className="text-muted-foreground mb-2 text-sm">{result.details}</div>

                  <div className="text-muted-foreground text-xs">소요시간: {Math.round(result.duration)}ms</div>

                  {/* 메트릭스 표시 */}
                  {result.metrics && (
                    <div className="mt-3 rounded bg-muted p-3 text-xs">
                      <div className="mb-1 font-medium">📊 상세 메트릭스:</div>
                      <div className="grid grid-cols-2 gap-2">
                        {Object.entries(result.metrics).map(([key, value]) => (
                          <div key={key} className="flex justify-between">
                            <span>{key}:</span>
                            <span className="font-mono">
                              {typeof value === "number"
                                ? Number.isInteger(value)
                                  ? value.toLocaleString()
                                  : value.toFixed(2)
                                : String(value)}
                            </span>
                          </div>
                        ))}
                      </div>
                    </div>
                  )}
                </div>
              ))}
            </CardContent>
          </Card>

          {/* 권장사항 */}
          {testResults.recommendation.length > 0 && (
            <Card>
              <CardHeader>
                <CardTitle className="text-xl">💡 개선 권장사항</CardTitle>
              </CardHeader>
              <CardContent>
                <ul className="space-y-2">
                  {testResults.recommendation.map((rec, index) => (
                    <li key={index} className="flex items-start gap-2">
                      <span className="mt-0.5 text-primary">•</span>
                      <span className="text-sm">{rec}</span>
                    </li>
                  ))}
                </ul>
              </CardContent>
            </Card>
          )}
        </div>
      )}

      {/* 실시간 로그 (축소된 형태) */}
      {testLogs.length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle className="text-lg">📋 테스트 로그 (최근 10개)</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="h-40 overflow-y-auto rounded bg-black p-4 font-mono text-xs text-emerald-400">
              {testLogs.slice(-10).map((log, index) => (
                <div key={index}>{log}</div>
              ))}
            </div>
          </CardContent>
        </Card>
      )}
    </div>
  );
}
