import { useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { useData } from '../hooks/useData';
import { ChevronDown, ChevronUp } from 'lucide-react';

interface SessionNarrative {
  session_id: string;
  developer: string;
  source: string;
  narrative: string;
  goal: string;
  outcome: string;
  difficulty: string;
  n_prompts: number;
  n_tool_calls: number;
  n_edits: number;
  active_min: number;
  pivots: string[];
}

interface DevSummary {
  email: string;
  developer: string;
  working_style: string;
  behavioral_patterns: { pattern: string; evidence: string }[];
  blind_spots: string[];
  recommendations: { action: string; expected_impact: string }[];
  assessment: string;
  sessions: number;
  active_hours: number;
}

interface TacitFact {
  category: string;
  fact: string;
  evidence: string;
  times_seen: number;
}

interface IntentClassification {
  sample_size: number;
  intent_distribution: Record<string, number>;
  complexity_distribution: Record<string, number>;
  specificity_distribution: Record<string, number>;
  vague_prompt_pct: number;
  ambitious_pct: number;
  headline: string;
}

interface AbandonmentCase {
  session_id: string;
  developer: string;
  source: string;
  root_cause: string;
  analysis: string;
  active_min: number;
  n_tool_calls: number;
}

interface AbandonmentData {
  total_abandoned?: number;
  analyzed?: number;
  reasons?: Record<string, number>;
  headline?: string;
  details?: AbandonmentCase[];
}

interface QualitativeData {
  session_narratives?: SessionNarrative[];
  developer_summaries?: DevSummary[];
  key_qualitative_findings?: string[];
  llm_intent_classification?: IntentClassification;
  tacit_knowledge?: {
    facts?: TacitFact[];
    claude_md_suggestions?: string[];
    headline?: string;
    sample_count?: number;
  };
  abandonment_analysis?: AbandonmentData | AbandonmentCase[];
}

function shortDev(email: string): string {
  const at = email.indexOf('@');
  return at > 0 ? email.slice(0, at) : email;
}

function OutcomeBadge({ outcome }: { outcome: string }) {
  const colors: Record<string, string> = {
    successful: 'bg-green/20 text-green',
    partial: 'bg-amber/20 text-amber',
    partially: 'bg-amber/20 text-amber',
    failed: 'bg-rose/20 text-rose',
    abandoned: 'bg-rose/20 text-rose',
  };
  const cls = colors[outcome.toLowerCase()] || 'bg-surface-2 text-text-3';
  return <span className={`text-[10px] font-semibold uppercase px-2 py-0.5 rounded-full ${cls}`}>{outcome}</span>;
}

export default function QualitativeInsights() {
  const { data, loading } = useData<QualitativeData>('/data/qualitative_insights.json', {});
  const [showAllNarratives, setShowAllNarratives] = useState(false);
  const [expandedDev, setExpandedDev] = useState<string | null>(null);

  if (loading) return null;

  const findings = data.key_qualitative_findings || [];
  const intents = data.llm_intent_classification;
  const facts = data.tacit_knowledge?.facts || [];
  const devSummaries = data.developer_summaries || [];
  const narratives = data.session_narratives || [];
  const rawAbandonment = data.abandonment_analysis;
  const abandonments: AbandonmentCase[] = Array.isArray(rawAbandonment)
    ? rawAbandonment
    : (rawAbandonment as AbandonmentData)?.details || [];
  const abandonmentHeadline = !Array.isArray(rawAbandonment) ? (rawAbandonment as AbandonmentData)?.headline : undefined;

  const hasContent = findings.length > 0 || intents || facts.length > 0 || devSummaries.length > 0;
  if (!hasContent) return null;

  const visibleNarratives = showAllNarratives ? narratives : narratives.slice(0, 4);

  return (
    <section className="px-8 max-w-7xl mx-auto py-16">
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        whileInView={{ opacity: 1, y: 0 }}
        viewport={{ once: true }}
        transition={{ duration: 0.6 }}
      >
        <h2 className="text-3xl md:text-4xl font-bold mb-2">
          What the AI <span className="text-accent">actually</span> reveals about your team.
        </h2>
        <p className="text-text-2 mb-8 max-w-2xl">
          LLM-powered qualitative analysis of session transcripts, prompt patterns, and developer behavior — insights that no dashboard metric can surface.
        </p>
      </motion.div>

      {/* Key behavioral findings */}
      {findings.length > 0 && (
        <div className="grid grid-cols-1 md:grid-cols-2 gap-3 mb-10">
          {findings.map((f, i) => (
            <motion.div
              key={i}
              initial={{ opacity: 0, x: -20 }}
              whileInView={{ opacity: 1, x: 0 }}
              viewport={{ once: true }}
              transition={{ delay: i * 0.06, duration: 0.4 }}
              className="bg-accent/5 border border-accent/20 rounded-xl p-4"
            >
              {typeof f === 'string' ? (
                <p className="text-sm text-text-1 leading-relaxed">{f}</p>
              ) : (
                <>
                  {f.title && <div className="text-sm font-semibold text-text-1 mb-1">{f.title}</div>}
                  {f.detail && <p className="text-xs text-text-2 leading-relaxed mb-1">{f.detail}</p>}
                  {f.evidence && <p className="text-[10px] text-text-3 italic">{f.evidence}</p>}
                </>
              )}
            </motion.div>
          ))}
        </div>
      )}

      {/* Developer behavioral assessments — the star section */}
      {devSummaries.length > 0 && (
        <div className="mb-10">
          <h3 className="text-lg font-semibold text-text-1 mb-1">Developer Behavioral Profiles</h3>
          <p className="text-xs text-text-3 mb-4">AI-generated from session transcript analysis — patterns, blind spots, and recommendations unique to each developer</p>
          <div className="flex flex-col gap-3">
            {devSummaries.map((d, i) => {
              const isExpanded = expandedDev === d.email;
              const patterns = Array.isArray(d.behavioral_patterns) ? d.behavioral_patterns : [];
              const blindSpots = Array.isArray(d.blind_spots) ? d.blind_spots : [];
              const recs = Array.isArray(d.recommendations) ? d.recommendations : [];

              return (
                <motion.div
                  key={d.email}
                  initial={{ opacity: 0, y: 10 }}
                  whileInView={{ opacity: 1, y: 0 }}
                  viewport={{ once: true }}
                  transition={{ delay: i * 0.08 }}
                  className="bg-surface-1 border border-border-dim rounded-xl overflow-hidden"
                >
                  <button
                    onClick={() => setExpandedDev(isExpanded ? null : d.email)}
                    className="w-full px-5 py-4 flex items-center gap-4 hover:bg-surface-2/50 transition-colors text-left"
                  >
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-3 mb-1">
                        <span className="text-sm font-semibold text-text-1">{shortDev(d.developer || d.email)}</span>
                        <span className="text-[10px] font-semibold uppercase px-2 py-0.5 rounded-full bg-accent/20 text-accent">
                          {d.working_style}
                        </span>
                        <span className="text-xs text-text-3">{d.sessions} sessions / {Number(d.active_hours).toFixed(1)}h active</span>
                      </div>
                      <p className="text-xs text-text-2 leading-relaxed line-clamp-2">{d.assessment}</p>
                    </div>
                    {isExpanded ? <ChevronUp size={16} className="text-text-3 shrink-0" /> : <ChevronDown size={16} className="text-text-3 shrink-0" />}
                  </button>

                  <AnimatePresence>
                    {isExpanded && (
                      <motion.div
                        initial={{ height: 0, opacity: 0 }}
                        animate={{ height: 'auto', opacity: 1 }}
                        exit={{ height: 0, opacity: 0 }}
                        transition={{ duration: 0.3 }}
                        className="overflow-hidden"
                      >
                        <div className="px-5 pb-5 border-t border-border-dim pt-4 grid grid-cols-1 md:grid-cols-3 gap-4">
                          {/* Behavioral patterns */}
                          {patterns.length > 0 && (
                            <div>
                              <div className="text-[10px] text-text-3 uppercase tracking-wider font-semibold mb-2">Behavioral Patterns</div>
                              <div className="space-y-2">
                                {patterns.map((p, pi) => (
                                  <div key={pi} className="bg-surface-2 rounded-lg px-3 py-2">
                                    <div className="text-xs text-text-1 font-medium">{typeof p === 'string' ? p : p.pattern}</div>
                                    {typeof p !== 'string' && p.evidence && (
                                      <div className="text-[10px] text-text-3 mt-1">{p.evidence}</div>
                                    )}
                                  </div>
                                ))}
                              </div>
                            </div>
                          )}

                          {/* Blind spots */}
                          {blindSpots.length > 0 && (
                            <div>
                              <div className="text-[10px] text-text-3 uppercase tracking-wider font-semibold mb-2">Blind Spots</div>
                              <div className="space-y-2">
                                {blindSpots.map((b, bi) => (
                                  <div key={bi} className="bg-rose/5 border border-rose/15 rounded-lg px-3 py-2 text-xs text-text-2">
                                    {b}
                                  </div>
                                ))}
                              </div>
                            </div>
                          )}

                          {/* Recommendations */}
                          {recs.length > 0 && (
                            <div>
                              <div className="text-[10px] text-text-3 uppercase tracking-wider font-semibold mb-2">Recommendations</div>
                              <div className="space-y-2">
                                {recs.map((r, ri) => (
                                  <div key={ri} className="bg-green/5 border border-green/15 rounded-lg px-3 py-2">
                                    <div className="text-xs text-text-1">{typeof r === 'string' ? r : r.action}</div>
                                    {typeof r !== 'string' && r.expected_impact && (
                                      <div className="text-[10px] text-green mt-1">{r.expected_impact}</div>
                                    )}
                                  </div>
                                ))}
                              </div>
                            </div>
                          )}
                        </div>
                      </motion.div>
                    )}
                  </AnimatePresence>
                </motion.div>
              );
            })}
          </div>
        </div>
      )}

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-10">
        {/* Prompt intent classification */}
        {intents && (
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            whileInView={{ opacity: 1, y: 0 }}
            viewport={{ once: true }}
            transition={{ delay: 0.1 }}
            className="bg-surface-1 border border-border-dim rounded-xl p-5"
          >
            <h3 className="text-sm font-semibold text-text-2 mb-1">LLM Prompt Classification</h3>
            <p className="text-xs text-text-3 mb-4">{intents.headline} ({intents.sample_size || (intents as any).sample_count || 0} prompts analyzed)</p>

            <div className="space-y-2 mb-4">
              {Object.entries(intents.intent_distribution || (intents as any).distribution || {})
                .sort(([, a], [, b]) => (b as number) - (a as number))
                .slice(0, 6)
                .map(([intent, count]) => {
                  const sampleSize = intents.sample_size || (intents as any).sample_count || 1;
                  const pct = sampleSize > 0 ? ((count as number) / sampleSize) * 100 : 0;
                  return (
                    <div key={intent} className="flex items-center gap-2">
                      <span className="text-xs text-text-2 w-24 shrink-0 capitalize">{intent}</span>
                      <div className="flex-1 h-4 bg-surface-2 rounded-full overflow-hidden">
                        <motion.div
                          className="h-full bg-accent/60 rounded-full"
                          initial={{ width: 0 }}
                          whileInView={{ width: `${pct}%` }}
                          viewport={{ once: true }}
                          transition={{ duration: 0.6, delay: 0.2 }}
                        />
                      </div>
                      <span className="text-[10px] text-text-3 w-10 text-right">{pct.toFixed(0)}%</span>
                    </div>
                  );
                })}
            </div>

            <div className="flex gap-4 text-xs text-text-3">
              {intents.vague_prompt_pct != null && (
                <span>Vague prompts: <span className="text-rose font-semibold">{intents.vague_prompt_pct.toFixed(0)}%</span></span>
              )}
              {intents.ambitious_pct != null && (
                <span>Ambitious: <span className="text-amber font-semibold">{intents.ambitious_pct.toFixed(0)}%</span></span>
              )}
            </div>
          </motion.div>
        )}

        {/* Tacit knowledge facts */}
        {facts.length > 0 && (
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            whileInView={{ opacity: 1, y: 0 }}
            viewport={{ once: true }}
            transition={{ delay: 0.2 }}
            className="bg-surface-1 border border-border-dim rounded-xl p-5"
          >
            <h3 className="text-sm font-semibold text-text-2 mb-1">Tacit Knowledge the AI Keeps Rediscovering</h3>
            <p className="text-xs text-text-3 mb-4">
              {data.tacit_knowledge?.headline || `${facts.length} facts the AI re-learns every session`}
            </p>

            <div className="space-y-2 max-h-[320px] overflow-y-auto pr-1">
              {facts.slice(0, 15).map((f, i) => (
                <div key={i} className="bg-surface-2 rounded-lg px-3 py-2">
                  <div className="flex items-center gap-2 mb-1">
                    <span className="text-[10px] font-semibold uppercase px-1.5 py-0.5 rounded bg-accent/15 text-accent">{f.category}</span>
                    {f.times_seen > 1 && <span className="text-[10px] text-text-3">seen {f.times_seen}x</span>}
                  </div>
                  <div className="text-xs text-text-2 leading-relaxed">{f.fact}</div>
                </div>
              ))}
            </div>

            {data.tacit_knowledge?.claude_md_suggestions && data.tacit_knowledge.claude_md_suggestions.length > 0 && (
              <div className="mt-4 pt-3 border-t border-border-dim">
                <div className="text-[10px] text-text-3 uppercase tracking-wider font-semibold mb-2">Suggested CLAUDE.md Entries</div>
                <div className="space-y-1">
                  {data.tacit_knowledge.claude_md_suggestions.slice(0, 5).map((s, i) => (
                    <div key={i} className="text-xs text-text-2 bg-green/5 border border-green/15 rounded-lg px-3 py-2 font-mono">{s}</div>
                  ))}
                </div>
              </div>
            )}
          </motion.div>
        )}
      </div>

      {/* Session narratives */}
      {narratives.length > 0 && (
        <div className="mb-10">
          <h3 className="text-lg font-semibold text-text-1 mb-1">Session Narratives</h3>
          <p className="text-xs text-text-3 mb-4">{narratives.length} sessions analyzed by AI — what actually happened, not just the metrics</p>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
            {visibleNarratives.map((n, i) => (
              <motion.div
                key={n.session_id}
                initial={{ opacity: 0, y: 10 }}
                whileInView={{ opacity: 1, y: 0 }}
                viewport={{ once: true }}
                transition={{ delay: i * 0.05 }}
                className="bg-surface-1 border border-border-dim rounded-xl p-4"
              >
                <div className="flex items-center gap-2 mb-2">
                  <span className="text-xs font-medium text-text-1">{shortDev(n.developer)}</span>
                  <span className="text-[10px] text-text-3">{n.source.replace('_', ' ')}</span>
                  <OutcomeBadge outcome={n.outcome} />
                  <span className="text-[10px] text-text-3 ml-auto">{Math.round(n.active_min)}m active</span>
                </div>
                <div className="text-xs text-accent font-medium mb-1">{n.goal}</div>
                <p className="text-xs text-text-2 leading-relaxed mb-2">{n.narrative}</p>
                <div className="flex gap-3 text-[10px] text-text-3">
                  <span>{n.n_prompts} prompts</span>
                  <span>{n.n_tool_calls} tools</span>
                  <span>{n.n_edits} edits</span>
                </div>
              </motion.div>
            ))}
          </div>
          {narratives.length > 4 && (
            <button
              onClick={() => setShowAllNarratives(!showAllNarratives)}
              className="mt-3 text-xs text-accent hover:text-accent/80 transition-colors"
            >
              {showAllNarratives ? 'Show fewer' : `Show all ${narratives.length} narratives`}
            </button>
          )}
        </div>
      )}

      {/* Abandonment analysis */}
      {abandonments.length > 0 && (
        <div>
          <h3 className="text-lg font-semibold text-text-1 mb-1">Why sessions get abandoned</h3>
          <p className="text-xs text-text-3 mb-4">{abandonmentHeadline || `${abandonments.length} zero-edit sessions analyzed for root cause`}</p>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
            {abandonments.slice(0, 6).map((a, i) => (
              <motion.div
                key={a.session_id}
                initial={{ opacity: 0, y: 10 }}
                whileInView={{ opacity: 1, y: 0 }}
                viewport={{ once: true }}
                transition={{ delay: i * 0.05 }}
                className="bg-rose/5 border border-rose/15 rounded-xl p-4"
              >
                <div className="flex items-center gap-2 mb-2">
                  <span className="text-xs font-medium text-text-1">{shortDev(a.developer)}</span>
                  <span className="text-[10px] text-text-3">{(a.source || '').replace('_', ' ')}</span>
                  <span className="text-[10px] text-text-3 ml-auto">{Math.round(a.active_min || 0)}m / {a.n_tool_calls || 0} tools</span>
                </div>
                <div className="text-xs text-rose font-medium mb-1">Root cause: {a.root_cause || (a as any).reason || 'unknown'}</div>
                <p className="text-xs text-text-2 leading-relaxed">{a.analysis || (a as any).explanation}</p>
              </motion.div>
            ))}
          </div>
        </div>
      )}
    </section>
  );
}
