'use client';

import { useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import Link from 'next/link';
import {
  ArrowLeft, FileText, AlertTriangle, Shield, Calendar,
  DollarSign, Users, Copy, Check, Loader2, Zap, ChevronDown, ChevronUp
} from 'lucide-react';

interface Party { name: string; role: string; }
interface KeyDate { date: string; description: string; urgency: string; }
interface FinancialTerm { item: string; amount: string; frequency: string; }
interface Obligation { party: string; obligation: string; deadline: string; }
interface RiskFlag { severity: string; clause: string; risk: string; recommendation: string; }

interface Analysis {
  summary: string;
  documentType: string;
  parties: Party[];
  keyDates: KeyDate[];
  financialTerms: FinancialTerm[];
  obligations: Obligation[];
  riskFlags: RiskFlag[];
  terminationConditions: string[];
  overallRisk: number;
  recommendation: string;
}

const SAMPLE = `SERVICE AGREEMENT

This Service Agreement ("Agreement") is entered into as of March 15, 2026, between Acme Corp ("Client"), located at 123 Business Ave, Dallas, TX, and TechServe Solutions ("Provider"), located at 456 Innovation Blvd, Austin, TX.

1. SCOPE OF SERVICES
Provider shall deliver a custom CRM integration platform including data migration, API development, and user training. Delivery deadline: June 30, 2026.

2. COMPENSATION
Client shall pay Provider $150,000 in three installments:
- $50,000 upon signing
- $50,000 upon milestone delivery (April 30, 2026)
- $50,000 upon final acceptance
Late payments incur 1.5% monthly interest.

3. INTELLECTUAL PROPERTY
All deliverables become Client property upon final payment. Provider retains rights to pre-existing tools and frameworks.

4. CONFIDENTIALITY
Both parties agree to maintain confidentiality of proprietary information for 3 years following termination.

5. TERMINATION
Either party may terminate with 30 days written notice. Client owes for work completed. No refund on signing payment.

6. LIABILITY
Provider liability capped at total contract value. Neither party liable for consequential damages.

7. DISPUTE RESOLUTION
Disputes resolved through binding arbitration in Dallas, TX under AAA rules.`;

const RISK_CONFIG: Record<string, { color: string; bg: string; border: string }> = {
  HIGH: { color: 'text-red-400', bg: 'bg-red-500/10', border: 'border-red-500/30' },
  MEDIUM: { color: 'text-amber-400', bg: 'bg-amber-500/10', border: 'border-amber-500/30' },
  LOW: { color: 'text-green-400', bg: 'bg-green-500/10', border: 'border-green-500/30' },
};

export default function ContractCraftPage() {
  const [input, setInput] = useState('');
  const [analysis, setAnalysis] = useState<Analysis | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [copied, setCopied] = useState(false);
  const [expandedSection, setExpandedSection] = useState<string | null>('risks');

  const analyze = async () => {
    const text = input.trim();
    if (text.length < 20) { setError('Please enter at least 20 characters.'); return; }
    setError('');
    setLoading(true);
    setAnalysis(null);
    try {
      const res = await fetch('/api/demos/contract-craft', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ text }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'Analysis failed');
      setAnalysis(data);
      setExpandedSection('risks');
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Something went wrong.');
    } finally {
      setLoading(false);
    }
  };

  const copyJson = () => {
    if (analysis) {
      navigator.clipboard.writeText(JSON.stringify(analysis, null, 2));
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    }
  };

  const riskScore = analysis?.overallRisk ?? 0;
  const riskColor = riskScore >= 7 ? 'text-red-400' : riskScore >= 4 ? 'text-amber-400' : 'text-green-400';

  const Section = ({ id, title, icon, count, children }: { id: string; title: string; icon: React.ReactNode; count: number; children: React.ReactNode }) => (
    <div className="border border-white/10 rounded-lg overflow-hidden">
      <button
        onClick={() => setExpandedSection(expandedSection === id ? null : id)}
        className="w-full flex items-center justify-between p-4 hover:bg-white/[0.02] transition-colors"
      >
        <div className="flex items-center gap-3">
          {icon}
          <span className="text-white font-medium">{title}</span>
          <span className="text-xs px-2 py-0.5 rounded-full bg-white/10 text-gray-400">{count}</span>
        </div>
        {expandedSection === id ? <ChevronUp className="w-4 h-4 text-gray-500" /> : <ChevronDown className="w-4 h-4 text-gray-500" />}
      </button>
      <AnimatePresence>
        {expandedSection === id && (
          <motion.div initial={{ height: 0 }} animate={{ height: 'auto' }} exit={{ height: 0 }} className="overflow-hidden">
            <div className="p-4 pt-0 space-y-3">{children}</div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );

  return (
    <div className="min-h-screen bg-[#0C1222] text-white">
      <div className="max-w-5xl mx-auto px-6 py-12">
        {/* Header */}
        <div className="flex items-center justify-between mb-8">
          <Link href="/demos" className="flex items-center gap-2 text-gray-400 hover:text-sky-400 transition-colors text-sm">
            <ArrowLeft className="w-4 h-4" /> Back to Demos
          </Link>
          <span className="text-xs text-gray-600">Built by The Hearth</span>
        </div>

        <div className="flex items-center gap-3 mb-2">
          <div className="p-2 bg-sky-500/10 rounded-lg"><FileText className="w-6 h-6 text-sky-400" /></div>
          <h1 className="text-3xl font-bold">ContractCraft</h1>
        </div>
        <p className="text-gray-400 mb-8 max-w-2xl">
          Paste any contract or legal document. AI extracts key terms, obligations, deadlines, financial details, and risk flags in seconds.
        </p>

        {/* Input */}
        <div className="mb-6">
          <div className="flex items-center justify-between mb-2">
            <label className="text-sm text-gray-400">Contract Text</label>
            <button onClick={() => setInput(SAMPLE)} className="text-xs text-sky-400 hover:text-sky-300 transition-colors">Load Sample</button>
          </div>
          <textarea
            value={input}
            onChange={(e) => setInput(e.target.value)}
            placeholder="Paste your contract or legal document here..."
            rows={10}
            className="w-full bg-white/[0.03] border border-white/10 rounded-lg p-4 text-sm text-gray-200 placeholder-gray-600 focus:outline-none focus:border-sky-500/50 resize-y font-mono"
          />
        </div>

        <div className="flex items-center gap-3 mb-8">
          <button
            onClick={analyze}
            disabled={loading || input.trim().length < 20}
            className="flex items-center gap-2 px-6 py-3 bg-gradient-to-r from-sky-500 to-sky-600 text-white font-semibold rounded-lg hover:from-sky-400 hover:to-sky-500 disabled:opacity-40 disabled:cursor-not-allowed transition-all"
          >
            {loading ? <Loader2 className="w-4 h-4 animate-spin" /> : <Zap className="w-4 h-4" />}
            {loading ? 'Analyzing...' : 'Analyze Contract'}
          </button>
          {analysis && (
            <button onClick={copyJson} className="flex items-center gap-2 px-4 py-3 border border-white/10 rounded-lg text-gray-400 hover:text-white hover:border-white/20 transition-all text-sm">
              {copied ? <Check className="w-4 h-4 text-green-400" /> : <Copy className="w-4 h-4" />}
              {copied ? 'Copied!' : 'Copy JSON'}
            </button>
          )}
        </div>

        {error && <div className="text-red-400 text-sm mb-4 p-3 bg-red-500/10 border border-red-500/30 rounded-lg">{error}</div>}

        {/* Results */}
        <AnimatePresence>
          {analysis && (
            <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} className="space-y-6">
              {/* Summary Card */}
              <div className="p-6 rounded-xl border border-white/10 bg-white/[0.02]">
                <div className="flex items-start justify-between mb-4">
                  <div>
                    <div className="text-xs text-sky-400 font-medium mb-1">{analysis.documentType}</div>
                    <p className="text-gray-300">{analysis.summary}</p>
                  </div>
                  <div className="text-right flex-shrink-0 ml-6">
                    <div className="text-xs text-gray-500 mb-1">Risk Score</div>
                    <div className={`text-3xl font-bold ${riskColor}`}>{riskScore}/10</div>
                  </div>
                </div>
                <p className="text-sm text-gray-400 italic">{analysis.recommendation}</p>
              </div>

              {/* Parties */}
              {analysis.parties?.length > 0 && (
                <Section id="parties" title="Parties" icon={<Users className="w-4 h-4 text-sky-400" />} count={analysis.parties.length}>
                  {analysis.parties.map((p, i) => (
                    <div key={i} className="flex items-center gap-3 text-sm">
                      <span className="text-white font-medium">{p.name}</span>
                      <span className="text-gray-500">{p.role}</span>
                    </div>
                  ))}
                </Section>
              )}

              {/* Key Dates */}
              {analysis.keyDates?.length > 0 && (
                <Section id="dates" title="Key Dates" icon={<Calendar className="w-4 h-4 text-orange-400" />} count={analysis.keyDates.length}>
                  {analysis.keyDates.map((d, i) => (
                    <div key={i} className="flex items-center justify-between text-sm p-2 rounded bg-white/[0.02]">
                      <div><span className="text-white">{d.date}</span> <span className="text-gray-500 ml-2">{d.description}</span></div>
                      <span className={`text-xs px-2 py-0.5 rounded-full ${d.urgency === 'high' ? 'bg-red-500/10 text-red-400' : d.urgency === 'medium' ? 'bg-amber-500/10 text-amber-400' : 'bg-green-500/10 text-green-400'}`}>{d.urgency}</span>
                    </div>
                  ))}
                </Section>
              )}

              {/* Financial Terms */}
              {analysis.financialTerms?.length > 0 && (
                <Section id="financial" title="Financial Terms" icon={<DollarSign className="w-4 h-4 text-green-400" />} count={analysis.financialTerms.length}>
                  {analysis.financialTerms.map((f, i) => (
                    <div key={i} className="flex items-center justify-between text-sm p-2 rounded bg-white/[0.02]">
                      <span className="text-gray-300">{f.item}</span>
                      <div className="text-right">
                        <span className="text-white font-medium">{f.amount}</span>
                        {f.frequency && <span className="text-gray-500 ml-2 text-xs">{f.frequency}</span>}
                      </div>
                    </div>
                  ))}
                </Section>
              )}

              {/* Risk Flags */}
              {analysis.riskFlags?.length > 0 && (
                <Section id="risks" title="Risk Flags" icon={<AlertTriangle className="w-4 h-4 text-red-400" />} count={analysis.riskFlags.length}>
                  {analysis.riskFlags.map((r, i) => {
                    const cfg = RISK_CONFIG[r.severity] || RISK_CONFIG.LOW;
                    return (
                      <div key={i} className={`p-3 rounded-lg border ${cfg.border} ${cfg.bg}`}>
                        <div className="flex items-center gap-2 mb-1">
                          <span className={`text-xs font-bold ${cfg.color}`}>{r.severity}</span>
                          <span className="text-white text-sm font-medium">{r.clause}</span>
                        </div>
                        <p className="text-gray-400 text-sm mb-1">{r.risk}</p>
                        <p className="text-gray-500 text-xs"><Shield className="w-3 h-3 inline mr-1" />{r.recommendation}</p>
                      </div>
                    );
                  })}
                </Section>
              )}

              {/* Obligations */}
              {analysis.obligations?.length > 0 && (
                <Section id="obligations" title="Obligations" icon={<FileText className="w-4 h-4 text-violet-400" />} count={analysis.obligations.length}>
                  {analysis.obligations.map((o, i) => (
                    <div key={i} className="text-sm p-2 rounded bg-white/[0.02]">
                      <span className="text-sky-400 font-medium">{o.party}</span>
                      <span className="text-gray-300 ml-2">{o.obligation}</span>
                      {o.deadline && <span className="text-gray-500 ml-2 text-xs">by {o.deadline}</span>}
                    </div>
                  ))}
                </Section>
              )}

              {/* Termination */}
              {analysis.terminationConditions?.length > 0 && (
                <Section id="termination" title="Termination Conditions" icon={<Shield className="w-4 h-4 text-gray-400" />} count={analysis.terminationConditions.length}>
                  {analysis.terminationConditions.map((t, i) => (
                    <p key={i} className="text-sm text-gray-400">• {t}</p>
                  ))}
                </Section>
              )}
            </motion.div>
          )}
        </AnimatePresence>

        <div className="mt-12 text-center text-xs text-gray-600">
          Built by The Hearth · <Link href="/demos" className="text-sky-400/60 hover:text-sky-400">More Demos</Link>
        </div>
      </div>
    </div>
  );
}
