'use client';

import { useState, useCallback } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import Link from 'next/link';
import {
  ArrowLeft, Shield, ShieldAlert, ShieldCheck, AlertTriangle,
  Info, Copy, Check, Loader2, Zap, Code2
} from 'lucide-react';

interface Finding {
  id: string;
  severity: 'CRITICAL' | 'HIGH' | 'MEDIUM' | 'LOW' | 'INFO';
  category: string;
  title: string;
  line: number | null;
  description: string;
  remediation: string;
}

interface ScanReport {
  summary: string;
  score: number;
  language: string;
  findings: Finding[];
}

const SEVERITY_CONFIG: Record<string, { color: string; bg: string; border: string; icon: React.ReactNode }> = {
  CRITICAL: { color: 'text-red-400', bg: 'bg-red-500/10', border: 'border-red-500/30', icon: <ShieldAlert className="w-4 h-4" /> },
  HIGH: { color: 'text-orange-400', bg: 'bg-orange-500/10', border: 'border-orange-500/30', icon: <AlertTriangle className="w-4 h-4" /> },
  MEDIUM: { color: 'text-yellow-400', bg: 'bg-yellow-500/10', border: 'border-yellow-500/30', icon: <AlertTriangle className="w-4 h-4" /> },
  LOW: { color: 'text-blue-400', bg: 'bg-blue-500/10', border: 'border-blue-500/30', icon: <Info className="w-4 h-4" /> },
  INFO: { color: 'text-gray-400', bg: 'bg-gray-500/10', border: 'border-gray-500/30', icon: <Info className="w-4 h-4" /> },
};

const SAMPLE_CODE = `const express = require('express');
const mysql = require('mysql');
const app = express();

const db = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'admin123',
  database: 'users'
});

app.get('/user', (req, res) => {
  const userId = req.query.id;
  const query = "SELECT * FROM users WHERE id = '" + userId + "'";
  db.query(query, (err, results) => {
    res.json(results);
  });
});

app.post('/login', (req, res) => {
  const { username, password } = req.body;
  const token = Buffer.from(username + ':' + password).toString('base64');
  res.cookie('session', token);
  res.json({ success: true, token });
});

app.get('/admin', (req, res) => {
  res.sendFile('/etc/passwd');
});

app.listen(3000);`;

export default function SentinelScanPage() {
  const [code, setCode] = useState('');
  const [report, setReport] = useState<ScanReport | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [expandedId, setExpandedId] = useState<string | null>(null);

  const handleScan = useCallback(async () => {
    const input = code.trim();
    if (input.length < 10) {
      setError('Please paste at least 10 characters of code.');
      return;
    }
    setLoading(true);
    setError('');
    setReport(null);
    try {
      const res = await fetch('/api/demos/sentinel-scan', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ code: input }),
      });
      const data = await res.json();
      if (data.error) throw new Error(data.error);
      setReport(data);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Scan failed.');
    } finally {
      setLoading(false);
    }
  }, [code]);

  const handleLoadSample = useCallback(() => {
    setCode(SAMPLE_CODE);
    setReport(null);
    setError('');
  }, []);

  const scoreColor = (score: number) => {
    if (score >= 80) return 'text-emerald-400';
    if (score >= 60) return 'text-yellow-400';
    if (score >= 40) return 'text-orange-400';
    return 'text-red-400';
  };

  const scoreRing = (score: number) => {
    if (score >= 80) return 'border-emerald-500/30';
    if (score >= 60) return 'border-yellow-500/30';
    if (score >= 40) return 'border-orange-500/30';
    return 'border-red-500/30';
  };

  return (
    <main className="min-h-screen bg-[#0C1222]">
      <div className="max-w-5xl mx-auto px-6 py-8">
        {/* Back */}
        <Link href="/demos" className="inline-flex items-center gap-2 text-gray-500 hover:text-gray-300 text-sm mb-8 transition-colors">
          <ArrowLeft className="w-4 h-4" /> Back to Demos
        </Link>

        {/* Header */}
        <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} className="mb-8">
          <div className="flex items-center gap-3 mb-3">
            <div className="w-10 h-10 rounded-xl bg-red-500/10 border border-red-500/20 flex items-center justify-center">
              <Shield className="w-5 h-5 text-red-400" />
            </div>
            <div>
              <h1 className="text-2xl font-bold text-white">SentinelScan</h1>
              <p className="text-gray-500 text-sm">AI-powered OWASP vulnerability scanner</p>
            </div>
          </div>
        </motion.div>

        {/* Code Input */}
        <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.1 }} className="mb-6">
          <div className="bg-black/40 border border-slate-800 rounded-xl overflow-hidden">
            <div className="flex items-center justify-between px-4 py-2 border-b border-slate-800/50">
              <div className="flex items-center gap-2">
                <Code2 className="w-4 h-4 text-gray-500" />
                <span className="text-xs text-gray-500">Paste your code below</span>
              </div>
              <button
                onClick={handleLoadSample}
                className="text-xs text-sky-500/70 hover:text-sky-400 transition-colors"
              >
                Load vulnerable sample
              </button>
            </div>
            <textarea
              value={code}
              onChange={(e) => setCode(e.target.value)}
              placeholder="// Paste your code here...\n// Supports JavaScript, Python, TypeScript, SQL, and more."
              rows={14}
              className="w-full bg-transparent text-sm text-gray-300 font-mono px-4 py-3 focus:outline-none resize-none placeholder-gray-700"
              spellCheck={false}
            />
          </div>
        </motion.div>

        {/* Scan Button */}
        <div className="flex items-center gap-4 mb-8">
          <button
            onClick={handleScan}
            disabled={loading || code.trim().length < 10}
            className="flex items-center gap-2 px-6 py-3 rounded-xl bg-gradient-to-r from-red-500/80 to-orange-500/80 hover:from-red-500 hover:to-orange-500 text-white font-medium text-sm disabled:opacity-40 disabled:cursor-not-allowed transition-all"
          >
            {loading ? (
              <><Loader2 className="w-4 h-4 animate-spin" /> Scanning...</>
            ) : (
              <><Zap className="w-4 h-4" /> Scan for Vulnerabilities</>
            )}
          </button>
          {error && <p className="text-red-400 text-sm">{error}</p>}
        </div>

        {/* Results */}
        <AnimatePresence>
          {report && (
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0 }}
              className="space-y-6"
            >
              {/* Score Card */}
              <div className="bg-white/[0.02] border border-slate-800/50 rounded-xl p-6">
                <div className="flex items-center gap-8">
                  <div className={`w-20 h-20 rounded-full border-4 ${scoreRing(report.score)} flex items-center justify-center`}>
                    <span className={`text-2xl font-bold ${scoreColor(report.score)}`}>{report.score}</span>
                  </div>
                  <div className="flex-1">
                    <div className="flex items-center gap-2 mb-1">
                      {report.score >= 80 ? (
                        <ShieldCheck className="w-5 h-5 text-emerald-400" />
                      ) : (
                        <ShieldAlert className="w-5 h-5 text-red-400" />
                      )}
                      <span className="text-white font-semibold">Security Score: {report.score}/100</span>
                      <span className="text-xs text-gray-500 ml-2">Language: {report.language}</span>
                    </div>
                    <p className="text-gray-400 text-sm">{report.summary}</p>
                    <div className="flex gap-4 mt-3">
                      {['CRITICAL', 'HIGH', 'MEDIUM', 'LOW'].map(sev => {
                        const count = report.findings.filter(f => f.severity === sev).length;
                        if (count === 0) return null;
                        const cfg = SEVERITY_CONFIG[sev];
                        return (
                          <span key={sev} className={`text-xs ${cfg.color} flex items-center gap-1`}>
                            {cfg.icon} {count} {sev.toLowerCase()}
                          </span>
                        );
                      })}
                    </div>
                  </div>
                </div>
              </div>

              {/* Findings */}
              {report.findings.length > 0 ? (
                <div className="space-y-3">
                  <h2 className="text-sm font-semibold text-white">Findings ({report.findings.length})</h2>
                  {report.findings.map((finding) => {
                    const cfg = SEVERITY_CONFIG[finding.severity] || SEVERITY_CONFIG.INFO;
                    const expanded = expandedId === finding.id;
                    return (
                      <motion.div
                        key={finding.id}
                        layout
                        className={`${cfg.bg} border ${cfg.border} rounded-xl overflow-hidden`}
                      >
                        <button
                          onClick={() => setExpandedId(expanded ? null : finding.id)}
                          className="w-full flex items-center gap-4 px-5 py-4 text-left"
                        >
                          <div className={cfg.color}>{cfg.icon}</div>
                          <div className="flex-1 min-w-0">
                            <div className="flex items-center gap-2">
                              <span className={`text-xs font-mono ${cfg.color}`}>{finding.id}</span>
                              <span className={`text-xs px-1.5 py-0.5 rounded ${cfg.bg} ${cfg.color} border ${cfg.border}`}>
                                {finding.severity}
                              </span>
                              {finding.line && (
                                <span className="text-xs text-gray-600">Line {finding.line}</span>
                              )}
                            </div>
                            <p className="text-sm text-white font-medium mt-0.5">{finding.title}</p>
                            <p className="text-xs text-gray-500 mt-0.5">{finding.category}</p>
                          </div>
                        </button>
                        <AnimatePresence>
                          {expanded && (
                            <motion.div
                              initial={{ height: 0, opacity: 0 }}
                              animate={{ height: 'auto', opacity: 1 }}
                              exit={{ height: 0, opacity: 0 }}
                              className="border-t border-slate-800/30"
                            >
                              <div className="px-5 py-4 space-y-3">
                                <div>
                                  <h4 className="text-xs text-gray-500 uppercase mb-1">Description</h4>
                                  <p className="text-sm text-gray-300">{finding.description}</p>
                                </div>
                                <div>
                                  <h4 className="text-xs text-gray-500 uppercase mb-1">Remediation</h4>
                                  <p className="text-sm text-emerald-400/80">{finding.remediation}</p>
                                </div>
                              </div>
                            </motion.div>
                          )}
                        </AnimatePresence>
                      </motion.div>
                    );
                  })}
                </div>
              ) : (
                <div className="text-center py-12">
                  <ShieldCheck className="w-12 h-12 text-emerald-400 mx-auto mb-3" />
                  <p className="text-emerald-400 font-medium">No vulnerabilities detected</p>
                  <p className="text-gray-500 text-sm mt-1">Your code looks secure. Keep it up.</p>
                </div>
              )}
            </motion.div>
          )}
        </AnimatePresence>

        {/* Footer */}
        <div className="text-center mt-12 text-gray-700 text-xs">
          Built by The Hearth • <Link href="/demos" className="text-sky-500/50 hover:text-sky-400">View all demos</Link>
        </div>
      </div>
    </main>
  );
}
