'use client';

import { motion } from 'framer-motion';
import {
  ShieldCheck, CheckCircle2, AlertTriangle,
  TrendingUp, Lock, ArrowRight, Play
} from 'lucide-react';
import { normalizePerformanceMetrics } from '../lib/perf-metrics';

function ScoreRing({ value, label, color, size = 100 }: { value: number; label: string; color: string; size?: number }) {
  const radius = (size - 12) / 2;
  const circumference = 2 * Math.PI * radius;
  const offset = circumference - (value / 100) * circumference;

  return (
    <div className="flex flex-col items-center">
      <div className="relative" style={{ width: size, height: size }}>
        <svg width={size} height={size} className="-rotate-90">
          <circle cx={size / 2} cy={size / 2} r={radius} fill="none" stroke="var(--brd)" strokeWidth="6" />
          <motion.circle
            cx={size / 2}
            cy={size / 2}
            r={radius}
            fill="none"
            stroke={color}
            strokeWidth="6"
            strokeLinecap="round"
            strokeDasharray={circumference}
            initial={{ strokeDashoffset: circumference }}
            animate={{ strokeDashoffset: offset }}
            transition={{ duration: 1.5, ease: 'easeOut' }}
          />
        </svg>
        <div className="absolute inset-0 flex items-center justify-center rotate-0">
          <span className="text-xl font-bold text-foreground">{value}%</span>
        </div>
      </div>
      <span className="text-[10px] text-muted mt-2 uppercase tracking-wider">{label}</span>
    </div>
  );
}

export default function Validation({ onNavigate, projectId: _projectId, maxReachedStep = 0, project: propProject }: { onNavigate: (s: string) => void; projectId?: string; maxReachedStep?: number; project?: import('../data/projectsData').Project | null }) {
  const project = propProject;
  const isDraft = project ? project.status === 'draft' && maxReachedStep < 5 : false;

  // Read from project config
  const rootCfg = (project?.config as Record<string, unknown> | undefined) ?? {};
  const cfg = (rootCfg.analysisResults as Record<string, unknown> | undefined) ?? {};
  const verification = (rootCfg.verification as Record<string, unknown> | undefined) ?? {};
  const testsCfg = (cfg.tests as { metrics?: { passed?: number; tests?: number; failed?: number; skipped?: number } } | undefined) ?? {};
  const securityCfg = (cfg.security as { metrics?: { score?: number } } | undefined) ?? {};
  const performanceCfg = (cfg.performance as { metrics?: unknown } | undefined) ?? {};
  const testGenerationCfg = (cfg.testGeneration as { metrics?: { coverage?: number } } | undefined) ?? {};
  const testMetrics = testsCfg.metrics;
  const secMetrics = securityCfg.metrics;
  const perfMetrics = performanceCfg.metrics;
  const perfM = normalizePerformanceMetrics(perfMetrics);
  const testGenMetrics = testGenerationCfg.metrics;
  const verificationIssues = Array.isArray(verification.securityIssues)
    ? verification.securityIssues as Array<{ severity: string; title: string; description?: string; location?: string }>
    : [];
  const criticalIssues = verificationIssues.filter((issue) => issue.severity === 'critical').length;
  const highIssues = verificationIssues.filter((issue) => issue.severity === 'high').length;
  const mediumIssues = verificationIssues.filter((issue) => issue.severity === 'medium').length;
  const lowIssues = verificationIssues.filter((issue) => issue.severity === 'low').length;
  const infoIssues = verificationIssues.filter((issue) => issue.severity === 'info').length;
  const totalIssues = verificationIssues.length;
  const totalTests = testMetrics?.tests ?? 0;
  const passedTests = testMetrics?.passed ?? 0;
  const failedTests = testMetrics?.failed ?? 0;
  const skippedTests = testMetrics?.skipped ?? 0;

  const vr = cfg ? {
    functionalParity: totalTests > 0 ? +((passedTests / totalTests) * 100).toFixed(1) : 0,
    syntaxCorrectness: 100,
    performanceScore: perfM.throughput != null ? Math.min(100, Math.round(perfM.throughput / 15)) : 0,
    securityScore: secMetrics?.score ?? 0,
    testCoverage: testGenMetrics?.coverage ?? 0,
    totalTests,
    passedTests,
    failedTests,
    skippedTests,
    performanceComparison: (perfM.throughput != null || perfM.latency != null || perfM.memory != null) ? [
      { metric: 'Throughput', legacy: '—', modern: perfM.throughput != null ? `${perfM.throughput.toLocaleString()} tps` : '—', improvement: '—' },
      { metric: 'Avg Latency', legacy: '—', modern: perfM.latency != null ? `${perfM.latency}ms` : '—', improvement: '—' },
      { metric: 'Memory', legacy: '—', modern: perfM.memory != null ? `${perfM.memory} MB` : '—', improvement: '—' },
    ] : [],
    securityChecks: [
      { check: 'Critical issues', status: criticalIssues === 0 ? 'pass' : 'warn', value: criticalIssues },
      { check: 'High severity issues', status: highIssues === 0 ? 'pass' : 'warn', value: highIssues },
      { check: 'Medium severity issues', status: mediumIssues === 0 ? 'pass' : 'warn', value: mediumIssues },
      { check: 'Total security findings', status: totalIssues === 0 ? 'pass' : 'warn', value: totalIssues },
    ] as { check: string; status: string; value: number }[],
    warnings: verificationIssues.map((issue) => ({
      severity: issue.severity,
      message: issue.title,
      detail: issue.description || '',
      file: issue.location || '—',
    })),
    infoIssues,
    lowIssues,
  } : null;

  if (isDraft) {
    return (
      <div className="space-y-5">
        <motion.div initial={{ opacity: 0, y: -10 }} animate={{ opacity: 1, y: 0 }} className="flex items-center justify-between">
          <div>
            <h2 className="text-2xl font-bold text-foreground flex items-center gap-2">
              <ShieldCheck className="w-6 h-6 text-accent-light" /> Validation & QA
            </h2>
            <p className="text-sm text-muted mt-1">Comprehensive quality assessment</p>
          </div>
        </motion.div>

        <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} className="glass-light rounded-lg p-12 text-center">
          <div className="w-20 h-20 rounded-full gradient-accent flex items-center justify-center mx-auto mb-6">
            <Play className="w-10 h-10 text-white" />
          </div>
          <h3 className="text-xl font-semibold text-foreground mb-3">Validation Not Started</h3>
          <p className="text-sm text-muted mb-8 max-w-md mx-auto">
            Connect a repository and run the migration process to see validation results, quality assessment, and security checks.
          </p>
          <button
            onClick={() => onNavigate('repository')}
            className="px-8 py-3 rounded-lg gradient-accent text-white text-sm font-semibold hover:opacity-90 transition-opacity flex items-center justify-center gap-2 cursor-pointer mx-auto glow-accent"
          >
            <Play className="w-5 h-5" /> Connect Repository
          </button>
        </motion.div>
      </div>
    );
  }

  return (
    <div className="space-y-5">
      <motion.div initial={{ opacity: 0, y: -10 }} animate={{ opacity: 1, y: 0 }} className="flex items-center justify-between">
        <div>
          <h2 className="text-2xl font-bold text-foreground flex items-center gap-2">
            <ShieldCheck className="w-6 h-6 text-accent-light" /> Validation & QA
          </h2>
          <p className="text-sm text-muted mt-1">Comprehensive quality assessment</p>
        </div>
        <button
          onClick={() => onNavigate('export')}
          className="px-4 py-2 rounded-lg gradient-accent text-white text-xs font-semibold hover:opacity-90 transition-opacity cursor-pointer flex items-center gap-1.5"
        >
          Export Conversion <ArrowRight className="w-3.5 h-3.5" />
        </button>
      </motion.div>

      {!vr ? (
        <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} className="glass-light rounded-lg p-12 text-center">
          <ShieldCheck className="w-12 h-12 text-muted/40 mx-auto mb-4" />
          <h3 className="text-lg font-semibold text-foreground mb-2">No Validation Data Yet</h3>
          <p className="text-sm text-muted max-w-md mx-auto">Run the migration pipeline to generate validation and QA results.</p>
        </motion.div>
      ) : (<>
        <div className="grid grid-cols-5 gap-4">
          {[
            { value: vr.functionalParity, label: 'Functional Parity', color: '#22c55e' },
            { value: vr.syntaxCorrectness, label: 'Syntax', color: '#ff914d' },
            { value: vr.performanceScore, label: 'Performance', color: '#e8712d' },
            { value: vr.securityScore, label: 'Security', color: '#f59e0b' },
            { value: vr.testCoverage, label: 'Test Coverage', color: '#ec4899' },
          ].map((score, i) => (
            <motion.div key={score.label} initial={{ opacity: 0, scale: 0.8 }} animate={{ opacity: 1, scale: 1 }} transition={{ delay: i * 0.1 }}
              className="glass rounded-xl p-4 flex flex-col items-center relative">
              <ScoreRing value={score.value} label={score.label} color={score.color} />
            </motion.div>
          ))}
        </div>

        <div className="grid grid-cols-4 gap-3">
          <div className="glass rounded-xl p-4 text-center">
            <p className="text-2xl font-bold text-foreground">{vr.totalTests.toLocaleString()}</p>
            <p className="text-[10px] text-muted uppercase tracking-wider mt-1">Total Tests</p>
          </div>
          <div className="glass rounded-xl p-4 text-center">
            <p className="text-2xl font-bold text-success">{vr.passedTests.toLocaleString()}</p>
            <p className="text-[10px] text-muted uppercase tracking-wider mt-1">Passed</p>
          </div>
          <div className="glass rounded-xl p-4 text-center">
            <p className="text-2xl font-bold text-danger">{vr.failedTests}</p>
            <p className="text-[10px] text-muted uppercase tracking-wider mt-1">Failed</p>
          </div>
          <div className="glass rounded-xl p-4 text-center">
            <p className="text-2xl font-bold text-warning">{vr.skippedTests}</p>
            <p className="text-[10px] text-muted uppercase tracking-wider mt-1">Skipped</p>
          </div>
        </div>

        <div className="grid grid-cols-2 gap-4">
          <motion.div initial={{ opacity: 0, x: -20 }} animate={{ opacity: 1, x: 0 }} transition={{ delay: 0.3 }} className="glass rounded-xl p-5">
            <h3 className="text-sm font-semibold text-foreground mb-4 flex items-center gap-2">
              <TrendingUp className="w-4 h-4 text-accent-light" /> Performance
            </h3>
            <div className="space-y-3">
              {vr.performanceComparison.map((p: { metric: string; legacy: string; modern: string; improvement: string }) => (
                <div key={p.metric} className="glass-light rounded-lg p-3">
                  <div className="flex items-center justify-between mb-2">
                    <span className="text-xs font-medium text-foreground">{p.metric}</span>
                  </div>
                  <div className="grid grid-cols-2 gap-3 text-[11px]">
                    <div className="flex items-center justify-between">
                      <span className="text-muted">Legacy</span>
                      <span className="text-red-400 font-mono">{p.legacy}</span>
                    </div>
                    <div className="flex items-center justify-between">
                      <span className="text-muted">Modern</span>
                      <span className="text-success font-mono">{p.modern}</span>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </motion.div>

          <div className="space-y-4">
            <motion.div initial={{ opacity: 0, x: 20 }} animate={{ opacity: 1, x: 0 }} transition={{ delay: 0.4 }} className="glass rounded-xl p-5">
              <h3 className="text-sm font-semibold text-foreground mb-3 flex items-center gap-2">
                <Lock className="w-4 h-4 text-accent-light" /> Security Checks
              </h3>
              <div className="space-y-2">
                {vr.securityChecks.map((check: { check: string; status: string; value: number }) => (
                  <div key={check.check} className="flex items-center gap-2 text-xs">
                    {check.status === 'pass' ? (
                      <CheckCircle2 className="w-4 h-4 text-success flex-shrink-0" />
                    ) : (
                      <AlertTriangle className="w-4 h-4 text-warning flex-shrink-0" />
                    )}
                    <span className={check.status === 'pass' ? 'text-foreground' : 'text-warning'}>{check.check}</span>
                    <span className="text-[10px] text-muted font-mono">{check.value}</span>
                    <span className={`ml-auto text-[10px] px-2 py-0.5 rounded-full font-medium ${
                      check.status === 'pass' ? 'bg-success/15 text-success' : 'bg-warning/15 text-warning'
                    }`}>
                      {check.status.toUpperCase()}
                    </span>
                  </div>
                ))}
              </div>
            </motion.div>

            <motion.div initial={{ opacity: 0, x: 20 }} animate={{ opacity: 1, x: 0 }} transition={{ delay: 0.5 }} className="glass rounded-xl p-5">
              <h3 className="text-sm font-semibold text-foreground mb-3 flex items-center gap-2">
                <AlertTriangle className="w-4 h-4 text-warning" /> Warnings
              </h3>
              {vr.warnings.length > 0 ? (
                <div className="space-y-2">
                  {vr.warnings.map((w: { severity: string; message: string; detail: string; file: string }, i: number) => (
                    <div key={i} className="glass-light rounded-lg p-3">
                      <div className="flex items-center gap-2 mb-1">
                        <span className="text-[10px] px-1.5 py-0.5 rounded font-medium bg-blue-500/15 text-blue-400">
                          {w.severity.toUpperCase()}
                        </span>
                      </div>
                      <p className="text-[11px] text-foreground">{w.message}</p>
                      {w.detail ? <p className="text-[11px] text-muted mt-1">{w.detail}</p> : null}
                      <p className="text-[10px] text-muted font-mono mt-1">{w.file}</p>
                    </div>
                  ))}
                </div>
              ) : (
                <p className="text-xs text-muted italic">No warnings</p>
              )}
            </motion.div>
          </div>
        </div>
      </>)}
    </div>
  );
}
