'use client';

import { useState, useCallback } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import Link from 'next/link';
import {
  ArrowLeft, BookOpen, CheckCircle, XCircle, AlertTriangle,
  Loader2, Zap, Award, Target, Brain
} from 'lucide-react';

interface Dimension {
  name: string;
  score: number;
  verdict: 'PASS' | 'NEEDS_WORK' | 'FAIL';
  feedback: string;
}

interface ReviewReport {
  overallScore: number;
  overallVerdict: string;
  summary: string;
  detectedField: string;
  topStrengths: string[];
  criticalIssues: string[];
  dimensions: Dimension[];
}

const VERDICT_CONFIG: Record<string, { color: string; bg: string; border: string; icon: React.ReactNode; label: string }> = {
  PASS: { color: 'text-emerald-400', bg: 'bg-emerald-500/10', border: 'border-emerald-500/20', icon: <CheckCircle className="w-4 h-4" />, label: 'Pass' },
  NEEDS_WORK: { color: 'text-yellow-400', bg: 'bg-yellow-500/10', border: 'border-yellow-500/20', icon: <AlertTriangle className="w-4 h-4" />, label: 'Needs Work' },
  FAIL: { color: 'text-red-400', bg: 'bg-red-500/10', border: 'border-red-500/20', icon: <XCircle className="w-4 h-4" />, label: 'Fail' },
};

const OVERALL_CONFIG: Record<string, { color: string; bg: string; label: string }> = {
  READY_TO_SUBMIT: { color: 'text-emerald-400', bg: 'bg-emerald-500/10', label: '\u2705 Ready to Submit' },
  REVISIONS_NEEDED: { color: 'text-yellow-400', bg: 'bg-yellow-500/10', label: '\u270f\ufe0f Revisions Needed' },
  MAJOR_REVISIONS: { color: 'text-orange-400', bg: 'bg-orange-500/10', label: '\u26a0\ufe0f Major Revisions Required' },
  NOT_READY: { color: 'text-red-400', bg: 'bg-red-500/10', label: '\u274c Not Ready' },
};

const SAMPLE_TEXT = `Abstract: This paper investigates the impact of transformer-based large language models on automated software testing methodologies. We propose TestFormer, a novel framework that leverages fine-tuned GPT-4 architectures to generate comprehensive test suites from natural language specifications. Our approach was evaluated against 47 open-source Java projects comprising over 2.3 million lines of code. Results demonstrate a 34% improvement in branch coverage compared to existing automated testing tools (EvoSuite, Randoop), with a 56% reduction in test generation time. The framework achieves 89% mutation score on the MutantBench benchmark. We identify three key limitations: handling of concurrent code patterns, test oracle generation for UI components, and scalability constraints beyond 500KLOC projects. Our contributions include: (1) a novel prompt engineering pipeline for test specification, (2) a feedback loop mechanism that iteratively improves test quality, and (3) an open-source implementation available for reproduction. This work advances the integration of AI into the software quality assurance lifecycle and provides a foundation for future research in LLM-assisted verification.`;

export default function DissertationReadyPage() {
  const [title, setTitle] = useState('');
  const [field, setField] = useState('');
  const [text, setText] = useState('');
  const [report, setReport] = useState<ReviewReport | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  const handleReview = useCallback(async () => {
    if (text.trim().length < 50) { setError('Please paste at least 50 characters.'); return; }
    setLoading(true); setError(''); setReport(null);
    try {
      const res = await fetch('/api/demos/dissertation-ready', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ text: text.trim(), title: title.trim(), field: field.trim() }),
      });
      const data = await res.json();
      if (data.error) throw new Error(data.error);
      setReport(data);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Review failed.');
    } finally {
      setLoading(false);
    }
  }, [text, title, field]);

  const scoreColor = (s: number) => s >= 80 ? 'text-emerald-400' : s >= 60 ? 'text-yellow-400' : s >= 40 ? 'text-orange-400' : 'text-red-400';
  const scoreRing = (s: number) => s >= 80 ? 'border-emerald-500/40' : s >= 60 ? 'border-yellow-500/40' : s >= 40 ? 'border-orange-500/40' : 'border-red-500/40';

  return (
    <main className="min-h-screen bg-[#0C1222]">
      <div className="max-w-5xl mx-auto px-6 py-8">
        <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>

        <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-violet-500/10 border border-violet-500/20 flex items-center justify-center">
              <BookOpen className="w-5 h-5 text-violet-400" />
            </div>
            <div>
              <h1 className="text-2xl font-bold text-white">DissertationReady</h1>
              <p className="text-gray-500 text-sm">AI-powered academic peer review before submission</p>
            </div>
          </div>
        </motion.div>

        {/* Input */}
        <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.1 }} className="space-y-4 mb-6">
          <div className="grid md:grid-cols-2 gap-4">
            <div>
              <label className="text-xs text-gray-400 mb-1 block">Paper Title (optional)</label>
              <input value={title} onChange={e => setTitle(e.target.value)} placeholder="e.g., TestFormer: LLM-Assisted Test Generation" className="w-full bg-black/30 border border-slate-700 rounded-lg px-3 py-2 text-sm text-white placeholder-gray-600 focus:border-violet-500 focus:outline-none transition-colors" />
            </div>
            <div>
              <label className="text-xs text-gray-400 mb-1 block">Academic Field (optional)</label>
              <input value={field} onChange={e => setField(e.target.value)} placeholder="e.g., Computer Science, Psychology, Biology" className="w-full bg-black/30 border border-slate-700 rounded-lg px-3 py-2 text-sm text-white placeholder-gray-600 focus:border-violet-500 focus:outline-none transition-colors" />
            </div>
          </div>
          <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">
              <span className="text-xs text-gray-500">Paste your abstract, introduction, or full paper text</span>
              <button onClick={() => { setText(SAMPLE_TEXT); setTitle('TestFormer: LLM-Assisted Test Generation'); setField('Computer Science'); }} className="text-xs text-violet-500/70 hover:text-violet-400 transition-colors">Load sample abstract</button>
            </div>
            <textarea value={text} onChange={e => setText(e.target.value)} rows={10} placeholder="Paste your dissertation text here..." className="w-full bg-transparent text-sm text-gray-300 px-4 py-3 focus:outline-none resize-none placeholder-gray-700" spellCheck={false} />
          </div>
        </motion.div>

        <div className="flex items-center gap-4 mb-8">
          <button onClick={handleReview} disabled={loading || text.trim().length < 50} className="flex items-center gap-2 px-6 py-3 rounded-xl bg-gradient-to-r from-violet-500/80 to-orange-500/80 hover:from-violet-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" /> Reviewing...</> : <><Zap className="w-4 h-4" /> Review Paper</>}
          </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">
              {/* Overall Score */}
              <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-24 h-24 rounded-full border-4 ${scoreRing(report.overallScore)} flex items-center justify-center`}>
                    <span className={`text-3xl font-bold ${scoreColor(report.overallScore)}`}>{report.overallScore}</span>
                  </div>
                  <div className="flex-1">
                    <div className="flex items-center gap-3 mb-2">
                      <span className={`text-lg font-semibold ${OVERALL_CONFIG[report.overallVerdict]?.color || 'text-white'}`}>
                        {OVERALL_CONFIG[report.overallVerdict]?.label || report.overallVerdict}
                      </span>
                      {report.detectedField && <span className="text-xs text-gray-500 px-2 py-0.5 rounded-full bg-white/5 border border-slate-800">{report.detectedField}</span>}
                    </div>
                    <p className="text-gray-400 text-sm">{report.summary}</p>
                    {report.topStrengths.length > 0 && (
                      <div className="flex flex-wrap gap-2 mt-3">
                        {report.topStrengths.map((s, i) => (
                          <span key={i} className="text-xs text-emerald-400/80 bg-emerald-500/10 px-2 py-1 rounded-lg flex items-center gap-1"><Award className="w-3 h-3" />{s}</span>
                        ))}
                      </div>
                    )}
                    {report.criticalIssues.length > 0 && (
                      <div className="flex flex-wrap gap-2 mt-2">
                        {report.criticalIssues.map((s, i) => (
                          <span key={i} className="text-xs text-red-400/80 bg-red-500/10 px-2 py-1 rounded-lg flex items-center gap-1"><Target className="w-3 h-3" />{s}</span>
                        ))}
                      </div>
                    )}
                  </div>
                </div>
              </div>

              {/* Dimensions */}
              <div className="space-y-3">
                <h2 className="text-sm font-semibold text-white flex items-center gap-2"><Brain className="w-4 h-4 text-violet-400" /> Detailed Review ({report.dimensions.length} dimensions)</h2>
                {report.dimensions.map((dim) => {
                  const cfg = VERDICT_CONFIG[dim.verdict] || VERDICT_CONFIG.NEEDS_WORK;
                  return (
                    <div key={dim.name} className={`${cfg.bg} border ${cfg.border} rounded-xl px-5 py-4`}>
                      <div className="flex items-center gap-4">
                        <div className={cfg.color}>{cfg.icon}</div>
                        <div className="flex-1">
                          <div className="flex items-center gap-2">
                            <span className="text-sm text-white font-medium">{dim.name}</span>
                            <span className={`text-xs ${cfg.color}`}>{dim.score}/10</span>
                            <span className={`text-[10px] px-1.5 py-0.5 rounded ${cfg.bg} ${cfg.color} border ${cfg.border}`}>{cfg.label}</span>
                          </div>
                          <p className="text-xs text-gray-400 mt-1">{dim.feedback}</p>
                        </div>
                        {/* Score bar */}
                        <div className="w-20 h-2 bg-black/30 rounded-full overflow-hidden hidden md:block">
                          <div className={`h-full rounded-full ${dim.score >= 7 ? 'bg-emerald-500' : dim.score >= 5 ? 'bg-yellow-500' : 'bg-red-500'}`} style={{ width: `${dim.score * 10}%` }} />
                        </div>
                      </div>
                    </div>
                  );
                })}
              </div>
            </motion.div>
          )}
        </AnimatePresence>

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