'use client';

import { useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import Link from 'next/link';
import {
  ArrowLeft, MessageSquare, CheckCircle2, AlertCircle, HelpCircle,
  Copy, Check, Loader2, Zap, ChevronRight, Users, Calendar
} from 'lucide-react';

interface Decision { decision: string; context: string; }
interface ActionItem { task: string; owner: string; deadline: string; priority: string; }
interface Highlight { topic: string; detail: string; }

interface Minutes {
  title: string;
  participants: string[];
  duration: string;
  summary: string;
  decisions: Decision[];
  actionItems: ActionItem[];
  highlights: Highlight[];
  openQuestions: string[];
  nextSteps: string[];
  sentiment: string;
  followUpDate: string | null;
}

const SAMPLE = `Team standup - March 28, 2026

Present: Sarah (PM), Jake (Dev Lead), Maria (Design), Tom (QA), Lisa (DevOps)

Sarah: Alright team, let's do a quick round. Jake, how's the API migration going?

Jake: We finished migrating 8 of 12 endpoints yesterday. The remaining 4 are the payment endpoints which need extra security review. Should be done by Wednesday. One blocker - we need the new Stripe webhook secret from Lisa.

Lisa: I'll get that set up today. Should have it in the vault by EOD.

Sarah: Good. Maria, where are we on the redesign?

Maria: The dashboard mockups are done and in Figma. I need Jake's team to review the component specs before I finalize. There's a question about whether we're keeping the sidebar navigation or switching to top nav. I'd recommend top nav for mobile parity.

Sarah: Let's go with top nav. Jake, can your team review Maria's specs by Thursday?

Jake: Yeah, I'll assign Alex to that.

Sarah: Tom, QA update?

Tom: We found 3 critical bugs in the checkout flow during regression testing. Two are related to the coupon code validation and one is a race condition on concurrent cart updates. I've filed them all. Jake, the race condition one is urgent - it's causing double charges in staging.

Jake: Yikes. I'll look at that today. Can you send me the reproduction steps?

Tom: Already in the ticket.

Sarah: OK, so priorities are clear. Lisa gets the webhook secret today, Jake tackles the double charge bug immediately, Alex reviews design specs by Thursday, and we aim to finish the API migration by Wednesday. Anything else?

Maria: Can we schedule the design review for Friday? I'd like everyone's eyes on it.

Sarah: Friday 2pm works. I'll send the invite. Let's reconvene Monday. Good meeting everyone.`;

const PRIORITY_CONFIG: Record<string, { color: string; bg: string }> = {
  high: { color: 'text-red-400', bg: 'bg-red-500/10' },
  medium: { color: 'text-amber-400', bg: 'bg-amber-500/10' },
  low: { color: 'text-green-400', bg: 'bg-green-500/10' },
};

const SENTIMENT_EMOJI: Record<string, string> = {
  positive: '😊',
  neutral: '😐',
  mixed: '🤔',
  tense: '😬',
};

export default function MeetingMindPage() {
  const [input, setInput] = useState('');
  const [minutes, setMinutes] = useState<Minutes | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [copied, setCopied] = useState(false);

  const analyze = async () => {
    const text = input.trim();
    if (text.length < 20) { setError('Please enter at least 20 characters.'); return; }
    setError('');
    setLoading(true);
    setMinutes(null);
    try {
      const res = await fetch('/api/demos/meeting-mind', {
        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');
      setMinutes(data);
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Something went wrong.');
    } finally {
      setLoading(false);
    }
  };

  const copyMarkdown = () => {
    if (!minutes) return;
    let md = `# ${minutes.title}\n\n`;
    md += `**Participants:** ${minutes.participants.join(', ')}\n`;
    if (minutes.duration) md += `**Duration:** ${minutes.duration}\n`;
    md += `\n## Summary\n${minutes.summary}\n`;
    if (minutes.decisions.length) {
      md += `\n## Decisions\n`;
      minutes.decisions.forEach(d => { md += `- **${d.decision}** — ${d.context}\n`; });
    }
    if (minutes.actionItems.length) {
      md += `\n## Action Items\n`;
      minutes.actionItems.forEach(a => { md += `- [ ] **${a.task}** → ${a.owner} (${a.deadline}) [${a.priority}]\n`; });
    }
    if (minutes.openQuestions.length) {
      md += `\n## Open Questions\n`;
      minutes.openQuestions.forEach(q => { md += `- ${q}\n`; });
    }
    if (minutes.nextSteps.length) {
      md += `\n## Next Steps\n`;
      minutes.nextSteps.forEach(s => { md += `- ${s}\n`; });
    }
    navigator.clipboard.writeText(md);
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  };

  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-orange-500/10 rounded-lg"><MessageSquare className="w-6 h-6 text-orange-400" /></div>
          <h1 className="text-3xl font-bold">MeetingMind</h1>
        </div>
        <p className="text-gray-400 mb-8 max-w-2xl">
          Paste raw meeting notes or a transcript. AI generates structured minutes with action items, decisions, and follow-ups.
        </p>

        {/* Input */}
        <div className="mb-6">
          <div className="flex items-center justify-between mb-2">
            <label className="text-sm text-gray-400">Meeting Notes / Transcript</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 meeting notes or transcript 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-orange-500/50 resize-y"
          />
        </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-orange-500 to-orange-600 text-white font-semibold rounded-lg hover:from-orange-400 hover:to-orange-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 ? 'Processing...' : 'Generate Minutes'}
          </button>
          {minutes && (
            <button onClick={copyMarkdown} 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 as Markdown'}
            </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>
          {minutes && (
            <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-3">
                  <h2 className="text-xl font-bold text-white">{minutes.title}</h2>
                  <span className="text-2xl">{SENTIMENT_EMOJI[minutes.sentiment] || '📋'}</span>
                </div>
                <div className="flex flex-wrap gap-4 text-sm text-gray-400 mb-4">
                  <div className="flex items-center gap-1.5"><Users className="w-3.5 h-3.5" />{minutes.participants.length} participants</div>
                  {minutes.duration && <div className="flex items-center gap-1.5"><Calendar className="w-3.5 h-3.5" />{minutes.duration}</div>}
                  {minutes.followUpDate && <div className="flex items-center gap-1.5 text-sky-400"><Calendar className="w-3.5 h-3.5" />Follow-up: {minutes.followUpDate}</div>}
                </div>
                <p className="text-gray-300">{minutes.summary}</p>
              </div>

              {/* Participants */}
              <div className="flex flex-wrap gap-2">
                {minutes.participants.map((p, i) => (
                  <span key={i} className="px-3 py-1 text-xs rounded-full bg-white/5 text-gray-300 border border-white/10">{p}</span>
                ))}
              </div>

              {/* Decisions */}
              {minutes.decisions?.length > 0 && (
                <div className="rounded-xl border border-white/10 bg-white/[0.02] p-5">
                  <h3 className="text-white font-semibold mb-3 flex items-center gap-2">
                    <CheckCircle2 className="w-4 h-4 text-green-400" /> Decisions ({minutes.decisions.length})
                  </h3>
                  <div className="space-y-3">
                    {minutes.decisions.map((d, i) => (
                      <div key={i} className="flex items-start gap-2 text-sm">
                        <ChevronRight className="w-4 h-4 text-green-400 mt-0.5 flex-shrink-0" />
                        <div>
                          <span className="text-white font-medium">{d.decision}</span>
                          <span className="text-gray-500 ml-2">{d.context}</span>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {/* Action Items */}
              {minutes.actionItems?.length > 0 && (
                <div className="rounded-xl border border-orange-500/20 bg-orange-500/5 p-5">
                  <h3 className="text-white font-semibold mb-3 flex items-center gap-2">
                    <AlertCircle className="w-4 h-4 text-orange-400" /> Action Items ({minutes.actionItems.length})
                  </h3>
                  <div className="space-y-3">
                    {minutes.actionItems.map((a, i) => {
                      const cfg = PRIORITY_CONFIG[a.priority] || PRIORITY_CONFIG.medium;
                      return (
                        <div key={i} className="flex items-start justify-between text-sm p-3 rounded-lg bg-white/[0.02] border border-white/5">
                          <div className="flex items-start gap-2">
                            <div className={`w-2 h-2 rounded-full mt-1.5 ${cfg.bg.replace('/10', '')}`} />
                            <div>
                              <span className="text-white">{a.task}</span>
                              <div className="text-gray-500 text-xs mt-0.5">→ {a.owner} · {a.deadline}</div>
                            </div>
                          </div>
                          <span className={`text-xs px-2 py-0.5 rounded-full ${cfg.bg} ${cfg.color}`}>{a.priority}</span>
                        </div>
                      );
                    })}
                  </div>
                </div>
              )}

              {/* Highlights */}
              {minutes.highlights?.length > 0 && (
                <div className="rounded-xl border border-white/10 bg-white/[0.02] p-5">
                  <h3 className="text-white font-semibold mb-3">💡 Discussion Highlights</h3>
                  <div className="space-y-3">
                    {minutes.highlights.map((h, i) => (
                      <div key={i} className="text-sm">
                        <span className="text-sky-400 font-medium">{h.topic}</span>
                        <span className="text-gray-400 ml-2">{h.detail}</span>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {/* Open Questions */}
              {minutes.openQuestions?.length > 0 && (
                <div className="rounded-xl border border-white/10 bg-white/[0.02] p-5">
                  <h3 className="text-white font-semibold mb-3 flex items-center gap-2">
                    <HelpCircle className="w-4 h-4 text-violet-400" /> Open Questions
                  </h3>
                  <div className="space-y-2">
                    {minutes.openQuestions.map((q, i) => (
                      <p key={i} className="text-sm text-gray-400 flex items-start gap-2">
                        <span className="text-violet-400">?</span> {q}
                      </p>
                    ))}
                  </div>
                </div>
              )}

              {/* Next Steps */}
              {minutes.nextSteps?.length > 0 && (
                <div className="rounded-xl border border-sky-500/20 bg-sky-500/5 p-5">
                  <h3 className="text-white font-semibold mb-3">🚀 Next Steps</h3>
                  <div className="space-y-2">
                    {minutes.nextSteps.map((s, i) => (
                      <p key={i} className="text-sm text-gray-300 flex items-start gap-2">
                        <ChevronRight className="w-4 h-4 text-sky-400 mt-0.5 flex-shrink-0" /> {s}
                      </p>
                    ))}
                  </div>
                </div>
              )}
            </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>
  );
}
