'use client';

import { useState, useCallback } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import Link from 'next/link';
import {
  ArrowLeft, Database, Loader2, Copy, Check, AlertTriangle,
  CheckCircle2, ChevronDown, ChevronRight, Server, Shield,
  DollarSign, Layers, Sparkles, FileText, BarChart3
} from 'lucide-react';

/* ------------------------------------------------------------------ */
/*  Types matching API response                                        */
/* ------------------------------------------------------------------ */

interface Source {
  name: string;
  description: string;
  format: string;
  priority: string;
  estimatedSize: string;
  collectionMethod: string;
  privacyNotes: string;
}

interface SourceCategory {
  category: string;
  sources: Source[];
}

interface QualityCheck {
  check: string;
  description: string;
  critical: boolean;
}

interface PipelineStep {
  step: number;
  name: string;
  description: string;
  duration: string;
}

interface Risk {
  risk: string;
  mitigation: string;
  severity: string;
}

interface HarvestPlan {
  businessAnalysis: {
    domain: string;
    llmPurpose: string;
    estimatedCorpusSize: string;
    estimatedTokens: string;
    trainingTimeEstimate: string;
  };
  dataSources: SourceCategory[];
  dataQualityChecklist: QualityCheck[];
  pipelineSteps: PipelineStep[];
  risks: Risk[];
  estimatedBudget: {
    dataCollection: string;
    preprocessing: string;
    training: string;
    totalRange: string;
  };
}

/* ------------------------------------------------------------------ */
/*  Sample inputs                                                       */
/* ------------------------------------------------------------------ */

const SAMPLES = [
  { label: 'Regional Law Firm', business: 'A 40-attorney regional law firm specializing in real estate, corporate M&A, and employment law. We have 15 years of case files, briefs, contracts, and internal memos stored across NetDocuments and local file shares.', useCase: 'Internal knowledge assistant for associates to research precedents and draft initial contract clauses.' },
  { label: 'Hospital Network', business: 'A 5-hospital healthcare network with 2,000+ physicians. We generate clinical notes, discharge summaries, radiology reports, and treatment protocols daily across Epic EHR.', useCase: 'Clinical decision support that suggests differential diagnoses and treatment pathways based on patient presentation.' },
  { label: 'E-Commerce Brand', business: 'A DTC e-commerce brand doing $50M ARR selling outdoor gear. We have 200K product reviews, 5 years of customer support tickets in Zendesk, detailed product specs, and a blog with 500+ articles.', useCase: 'AI shopping assistant that recommends gear based on activity, conditions, and budget — trained on our specific catalog.' },
];

/* ------------------------------------------------------------------ */
/*  Expandable section                                                  */
/* ------------------------------------------------------------------ */

function Section({ title, icon: Icon, children, defaultOpen = false }: {
  title: string;
  icon: React.ElementType;
  children: React.ReactNode;
  defaultOpen?: boolean;
}) {
  const [open, setOpen] = useState(defaultOpen);
  return (
    <div className="border border-slate-700/60 rounded-lg overflow-hidden">
      <button
        onClick={() => setOpen(!open)}
        className="w-full flex items-center gap-3 px-5 py-4 bg-slate-800/40 hover:bg-slate-800/70 transition-colors text-left"
      >
        <Icon className="w-5 h-5 text-emerald-400 shrink-0" />
        <span className="font-semibold text-white flex-1">{title}</span>
        {open ? <ChevronDown className="w-4 h-4 text-slate-400" /> : <ChevronRight className="w-4 h-4 text-slate-400" />}
      </button>
      <AnimatePresence>
        {open && (
          <motion.div
            initial={{ height: 0, opacity: 0 }}
            animate={{ height: 'auto', opacity: 1 }}
            exit={{ height: 0, opacity: 0 }}
            transition={{ duration: 0.2 }}
            className="overflow-hidden"
          >
            <div className="p-5 space-y-4">{children}</div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}

/* ------------------------------------------------------------------ */
/*  Priority badge                                                      */
/* ------------------------------------------------------------------ */

function PriorityBadge({ priority }: { priority: string }) {
  const p = priority.toUpperCase();
  const color = p === 'HIGH' ? 'bg-red-500/20 text-red-300 border-red-500/30'
    : p === 'MEDIUM' ? 'bg-yellow-500/20 text-yellow-300 border-yellow-500/30'
    : 'bg-slate-500/20 text-slate-300 border-slate-500/30';
  return <span className={`text-xs px-2 py-0.5 rounded border font-medium ${color}`}>{p}</span>;
}

/* ------------------------------------------------------------------ */
/*  Severity badge                                                      */
/* ------------------------------------------------------------------ */

function SeverityBadge({ severity }: { severity: string }) {
  const s = severity.toUpperCase();
  const color = s === 'HIGH' ? 'text-red-400' : s === 'MEDIUM' ? 'text-yellow-400' : 'text-slate-400';
  return <span className={`text-xs font-semibold ${color}`}>{s}</span>;
}

/* ------------------------------------------------------------------ */
/*  Main page                                                           */
/* ------------------------------------------------------------------ */

export default function ScopeHarvesterPage() {
  const [business, setBusiness] = useState('');
  const [useCase, setUseCase] = useState('');
  const [plan, setPlan] = useState<HarvestPlan | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [copied, setCopied] = useState(false);

  const generate = useCallback(async () => {
    if (business.trim().length < 20) {
      setError('Describe your business in at least 20 characters.');
      return;
    }
    setError('');
    setLoading(true);
    setPlan(null);
    try {
      const res = await fetch('/api/demos/scope-harvester', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ business: business.trim(), useCase: useCase.trim() || undefined }),
      });
      if (!res.ok) {
        const d = await res.json().catch(() => ({}));
        throw new Error(d.error || 'Generation failed.');
      }
      const data: HarvestPlan = await res.json();
      setPlan(data);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Something went wrong.');
    } finally {
      setLoading(false);
    }
  }, [business, useCase]);

  const loadSample = useCallback((idx: number) => {
    setBusiness(SAMPLES[idx].business);
    setUseCase(SAMPLES[idx].useCase);
    setPlan(null);
    setError('');
  }, []);

  const exportJSON = useCallback(() => {
    if (!plan) return;
    navigator.clipboard.writeText(JSON.stringify(plan, null, 2));
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  }, [plan]);

  const totalSources = plan?.dataSources.reduce((sum, cat) => sum + cat.sources.length, 0) ?? 0;

  return (
    <div className="min-h-screen bg-[#0C1222] text-slate-200">
      {/* Header */}
      <div className="border-b border-slate-800">
        <div className="max-w-5xl mx-auto px-4 py-4 flex items-center gap-3">
          <Link href="/demos" className="text-slate-400 hover:text-white transition-colors">
            <ArrowLeft className="w-5 h-5" />
          </Link>
          <Database className="w-6 h-6 text-emerald-400" />
          <div>
            <h1 className="text-lg font-bold text-white">ScopeHarvester</h1>
            <p className="text-xs text-slate-400">Private LLM Data Collection Planner</p>
          </div>
        </div>
      </div>

      <div className="max-w-5xl mx-auto px-4 py-8 space-y-8">
        {/* Input form */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          className="space-y-6"
        >
          <div className="bg-slate-800/30 border border-slate-700/50 rounded-xl p-6 space-y-5">
            <div>
              <label className="block text-sm font-medium text-slate-300 mb-2">Business Description *</label>
              <textarea
                value={business}
                onChange={(e) => setBusiness(e.target.value)}
                placeholder="Describe your business, industry, size, and what data assets you have..."
                rows={4}
                className="w-full bg-slate-900/60 border border-slate-700 rounded-lg px-4 py-3 text-white placeholder:text-slate-500 focus:outline-none focus:ring-2 focus:ring-emerald-500/40 focus:border-emerald-500/60 resize-none"
              />
              <p className="text-xs text-slate-500 mt-1">{business.length}/20 minimum characters</p>
            </div>

            <div>
              <label className="block text-sm font-medium text-slate-300 mb-2">Intended LLM Use Case <span className="text-slate-500">(optional)</span></label>
              <input
                type="text"
                value={useCase}
                onChange={(e) => setUseCase(e.target.value)}
                placeholder="e.g., Customer support bot, internal knowledge assistant, document drafter..."
                className="w-full bg-slate-900/60 border border-slate-700 rounded-lg px-4 py-3 text-white placeholder:text-slate-500 focus:outline-none focus:ring-2 focus:ring-emerald-500/40 focus:border-emerald-500/60"
              />
            </div>

            {/* Sample buttons */}
            <div className="flex flex-wrap gap-2">
              <span className="text-xs text-slate-500 self-center mr-1">Try:</span>
              {SAMPLES.map((s, i) => (
                <button
                  key={i}
                  onClick={() => loadSample(i)}
                  className="text-xs px-3 py-1.5 rounded-full border border-slate-600 text-slate-300 hover:border-emerald-500/50 hover:text-emerald-300 transition-colors"
                >
                  {s.label}
                </button>
              ))}
            </div>

            <button
              onClick={generate}
              disabled={loading}
              className="w-full sm:w-auto px-8 py-3 bg-emerald-600 hover:bg-emerald-500 disabled:bg-slate-700 disabled:text-slate-400 text-white font-semibold rounded-lg transition-colors flex items-center justify-center gap-2"
            >
              {loading ? <><Loader2 className="w-4 h-4 animate-spin" /> Analyzing Business...</> : <><Sparkles className="w-4 h-4" /> Generate Collection Plan</>}
            </button>

            {error && (
              <div className="flex items-center gap-2 text-red-400 text-sm">
                <AlertTriangle className="w-4 h-4 shrink-0" />
                {error}
              </div>
            )}
          </div>
        </motion.div>

        {/* Results */}
        <AnimatePresence mode="wait">
          {plan && (
            <motion.div
              initial={{ opacity: 0, y: 30 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: -10 }}
              className="space-y-5"
            >
              {/* Overview cards */}
              <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
                {[
                  { label: 'Domain', value: plan.businessAnalysis.domain, icon: Layers },
                  { label: 'Corpus Size', value: plan.businessAnalysis.estimatedCorpusSize, icon: Database },
                  { label: 'Est. Tokens', value: plan.businessAnalysis.estimatedTokens, icon: BarChart3 },
                  { label: 'Training Time', value: plan.businessAnalysis.trainingTimeEstimate, icon: Server },
                ].map((card) => (
                  <div key={card.label} className="bg-slate-800/40 border border-slate-700/50 rounded-lg p-4">
                    <div className="flex items-center gap-2 text-slate-400 text-xs mb-1">
                      <card.icon className="w-3.5 h-3.5" />
                      {card.label}
                    </div>
                    <div className="text-white font-semibold text-sm">{card.value}</div>
                  </div>
                ))}
              </div>

              {/* Purpose */}
              <div className="bg-emerald-500/10 border border-emerald-500/20 rounded-lg p-4">
                <p className="text-sm text-emerald-300">
                  <strong>LLM Purpose:</strong> {plan.businessAnalysis.llmPurpose}
                </p>
              </div>

              {/* Data sources */}
              <Section title={`Data Sources (${totalSources} identified)`} icon={FileText} defaultOpen>
                <div className="space-y-6">
                  {plan.dataSources.map((cat, ci) => (
                    <div key={ci}>
                      <h4 className="text-sm font-semibold text-emerald-300 mb-3">{cat.category}</h4>
                      <div className="space-y-3">
                        {cat.sources.map((src, si) => (
                          <div key={si} className="bg-slate-900/50 border border-slate-700/40 rounded-lg p-4 space-y-2">
                            <div className="flex items-start justify-between gap-2">
                              <h5 className="text-sm font-medium text-white">{src.name}</h5>
                              <PriorityBadge priority={src.priority} />
                            </div>
                            <p className="text-xs text-slate-400">{src.description}</p>
                            <div className="grid grid-cols-1 sm:grid-cols-3 gap-2 text-xs">
                              <div><span className="text-slate-500">Format:</span> <span className="text-slate-300">{src.format}</span></div>
                              <div><span className="text-slate-500">Size:</span> <span className="text-slate-300">{src.estimatedSize}</span></div>
                              <div><span className="text-slate-500">Method:</span> <span className="text-slate-300">{src.collectionMethod}</span></div>
                            </div>
                            {src.privacyNotes && (
                              <div className="flex items-center gap-1.5 text-xs text-yellow-400/80">
                                <Shield className="w-3 h-3" />
                                {src.privacyNotes}
                              </div>
                            )}
                          </div>
                        ))}
                      </div>
                    </div>
                  ))}
                </div>
              </Section>

              {/* Pipeline */}
              <Section title={`Pipeline Steps (${plan.pipelineSteps.length})`} icon={Layers}>
                <div className="space-y-3">
                  {plan.pipelineSteps.map((step) => (
                    <div key={step.step} className="flex gap-4 items-start">
                      <div className="w-8 h-8 rounded-full bg-emerald-500/20 border border-emerald-500/30 flex items-center justify-center text-emerald-300 text-sm font-bold shrink-0">
                        {step.step}
                      </div>
                      <div className="flex-1">
                        <div className="flex items-center gap-2">
                          <span className="text-sm font-medium text-white">{step.name}</span>
                          <span className="text-xs text-slate-500">({step.duration})</span>
                        </div>
                        <p className="text-xs text-slate-400 mt-0.5">{step.description}</p>
                      </div>
                    </div>
                  ))}
                </div>
              </Section>

              {/* Quality checklist */}
              <Section title={`Quality Checklist (${plan.dataQualityChecklist.length})`} icon={Shield}>
                <div className="space-y-2">
                  {plan.dataQualityChecklist.map((qc, i) => (
                    <div key={i} className="flex items-start gap-3 bg-slate-900/40 rounded-lg p-3">
                      <CheckCircle2 className={`w-4 h-4 shrink-0 mt-0.5 ${qc.critical ? 'text-red-400' : 'text-emerald-400'}`} />
                      <div className="flex-1">
                        <div className="flex items-center gap-2">
                          <span className="text-sm text-white font-medium">{qc.check}</span>
                          {qc.critical && <span className="text-[10px] px-1.5 py-0.5 bg-red-500/20 text-red-300 rounded">CRITICAL</span>}
                        </div>
                        <p className="text-xs text-slate-400 mt-0.5">{qc.description}</p>
                      </div>
                    </div>
                  ))}
                </div>
              </Section>

              {/* Risks */}
              <Section title={`Risks & Mitigations (${plan.risks.length})`} icon={AlertTriangle}>
                <div className="space-y-3">
                  {plan.risks.map((r, i) => (
                    <div key={i} className="bg-slate-900/40 border border-slate-700/40 rounded-lg p-4 space-y-1">
                      <div className="flex items-center gap-2">
                        <span className="text-sm text-white font-medium">{r.risk}</span>
                        <SeverityBadge severity={r.severity} />
                      </div>
                      <p className="text-xs text-slate-400"><span className="text-slate-500">Mitigation:</span> {r.mitigation}</p>
                    </div>
                  ))}
                </div>
              </Section>

              {/* Budget */}
              <Section title="Estimated Budget" icon={DollarSign}>
                <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
                  {[
                    { label: 'Data Collection', value: plan.estimatedBudget.dataCollection },
                    { label: 'Preprocessing', value: plan.estimatedBudget.preprocessing },
                    { label: 'Training', value: plan.estimatedBudget.training },
                    { label: 'Total Range', value: plan.estimatedBudget.totalRange },
                  ].map((b) => (
                    <div key={b.label} className="bg-slate-900/50 border border-slate-700/40 rounded-lg p-3 text-center">
                      <div className="text-xs text-slate-500 mb-1">{b.label}</div>
                      <div className={`text-sm font-semibold ${b.label === 'Total Range' ? 'text-emerald-300' : 'text-white'}`}>{b.value}</div>
                    </div>
                  ))}
                </div>
              </Section>

              {/* Export */}
              <div className="flex justify-end">
                <button
                  onClick={exportJSON}
                  className="flex items-center gap-2 px-4 py-2 text-sm bg-slate-800 border border-slate-700 rounded-lg hover:border-emerald-500/50 text-slate-300 hover:text-emerald-300 transition-colors"
                >
                  {copied ? <><Check className="w-4 h-4" /> Copied!</> : <><Copy className="w-4 h-4" /> Copy Full Plan (JSON)</>}
                </button>
              </div>
            </motion.div>
          )}
        </AnimatePresence>

        {/* Footer */}
        <div className="text-center text-xs text-slate-600 pt-8 pb-4">
          Built by The Hearth · AI-powered data collection planning
        </div>
      </div>
    </div>
  );
}
