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

interface SessionDeepDive {
  session_id: string;
  email: string;
  source: string;
  repo: string | null;
  cost_usd: number;
  wall_clock_min: number;
  active_min: number;
  opening_prompt: string;
  top_tools: { name: string; count: number }[];
  msg_summary: Record<string, number>;
}

interface SessionNarrative {
  session_id: string;
  narrative: string;
}

interface ChartData {
  session_deepdives?: SessionDeepDive[];
  session_narratives?: SessionNarrative[];
}

interface QualData {
  session_narratives?: SessionNarrative[];
}

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

function formatMin(min: number): string {
  if (min < 1) return '<1m';
  if (min < 60) return `${Math.round(min)}m`;
  return `${(min / 60).toFixed(1)}h`;
}

export default function SessionDeepDives() {
  const { data, loading } = useData<ChartData>('/data/chart_data.json', {});
  const { data: qualData } = useData<QualData>('/data/qualitative_insights.json', {});
  const [expandedId, setExpandedId] = useState<string | null>(null);

  // Merge narratives from both chart_data and qualitative_insights
  const narrativeMap = new Map<string, string>();
  for (const n of data.session_narratives || []) narrativeMap.set(n.session_id, n.narrative);
  for (const n of qualData.session_narratives || []) if (n.narrative) narrativeMap.set(n.session_id, n.narrative);

  if (loading || !data.session_deepdives?.length) return null;

  const sessions = data.session_deepdives;
  const totalCost = sessions.reduce((s, d) => s + d.cost_usd, 0);

  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">
          Inside the <span className="text-rose">${totalCost.toFixed(0)}</span> sessions.
        </h2>
        <p className="text-text-2 mb-8 max-w-2xl">
          The {sessions.length} most expensive sessions, with their opening prompts, tool usage, and active time.
          Click any session to see what it actually did.
        </p>
      </motion.div>

      <div className="space-y-2">
        {sessions.map((s, i) => {
          const isExpanded = expandedId === s.session_id;
          const totalMsgs = Object.values(s.msg_summary).reduce((a, b) => a + b, 0);
          return (
            <motion.div
              key={s.session_id}
              initial={{ opacity: 0, y: 10 }}
              whileInView={{ opacity: 1, y: 0 }}
              viewport={{ once: true }}
              transition={{ delay: i * 0.05, duration: 0.3 }}
              className="bg-surface-1 border border-border-dim rounded-xl overflow-hidden"
            >
              <button
                onClick={() => setExpandedId(isExpanded ? null : s.session_id)}
                className="w-full px-5 py-3.5 flex items-center gap-4 hover:bg-surface-2/50 transition-colors"
              >
                <span className="text-xs font-mono text-text-3 w-6">#{i + 1}</span>
                <div className="flex-1 min-w-0 text-left">
                  <div className="flex items-center gap-2">
                    <span className="text-sm font-semibold text-text-1">{shortEmail(s.email)}</span>
                    <span className="text-[10px] font-mono text-text-3 bg-surface-2 px-1.5 py-0.5 rounded">
                      {s.source.replace('_', ' ')}
                    </span>
                    {s.repo && (
                      <span className="text-[10px] text-text-3">{s.repo.split('/').pop()}</span>
                    )}
                  </div>
                </div>
                <div className="hidden md:flex items-center gap-5 text-xs">
                  <div className="text-center">
                    <div className="text-rose font-bold text-sm">${s.cost_usd.toFixed(0)}</div>
                    <div className="text-text-3">cost</div>
                  </div>
                  <div className="text-center">
                    <div className="text-text-1 font-semibold">{formatMin(s.active_min)}</div>
                    <div className="text-text-3">active</div>
                  </div>
                  <div className="text-center">
                    <div className="text-text-1 font-semibold">{totalMsgs}</div>
                    <div className="text-text-3">messages</div>
                  </div>
                </div>
                {isExpanded ? <ChevronUp size={14} className="text-text-3" /> : <ChevronDown size={14} className="text-text-3" />}
              </button>

              <AnimatePresence>
                {isExpanded && (
                  <motion.div
                    initial={{ height: 0, opacity: 0 }}
                    animate={{ height: 'auto', opacity: 1 }}
                    exit={{ height: 0, opacity: 0 }}
                    transition={{ duration: 0.25 }}
                    className="overflow-hidden"
                  >
                    <div className="px-5 pb-4 border-t border-border-dim pt-3 space-y-3">
                      {/* Stats row */}
                      <div className="grid grid-cols-2 md:grid-cols-5 gap-2">
                        <div className="bg-surface-2 rounded-lg p-2.5 text-center">
                          <div className="flex items-center justify-center gap-1 mb-1">
                            <DollarSign size={12} className="text-rose" />
                            <CostInfoTip />
                          </div>
                          <div className="text-sm font-bold text-rose">${s.cost_usd.toFixed(2)}</div>
                          <div className="text-[10px] text-text-3">total cost</div>
                        </div>
                        <div className="bg-surface-2 rounded-lg p-2.5 text-center">
                          <div className="text-sm font-bold text-text-1">{formatMin(s.active_min)}</div>
                          <div className="text-[10px] text-text-3">active time</div>
                        </div>
                        <div className="bg-surface-2 rounded-lg p-2.5 text-center">
                          <div className="text-sm font-bold text-text-1">{formatMin(s.wall_clock_min)}</div>
                          <div className="text-[10px] text-text-3">wall clock</div>
                        </div>
                        <div className="bg-surface-2 rounded-lg p-2.5 text-center">
                          <div className="text-sm font-bold text-text-1">{totalMsgs}</div>
                          <div className="text-[10px] text-text-3">messages</div>
                        </div>
                        <div className="bg-surface-2 rounded-lg p-2.5 text-center">
                          <div className="text-sm font-bold text-text-1">{s.top_tools.reduce((a, t) => a + t.count, 0)}</div>
                          <div className="text-[10px] text-text-3">tool calls</div>
                        </div>
                      </div>

                      {/* Top tools */}
                      {s.top_tools.length > 0 && (
                        <div>
                          <div className="text-[10px] text-text-3 uppercase tracking-wider mb-1.5">Top Tools</div>
                          <div className="flex flex-wrap gap-1.5">
                            {s.top_tools.map(t => (
                              <span key={t.name} className="text-[10px] bg-surface-2 text-text-2 px-2 py-0.5 rounded-md border border-border-dim flex items-center gap-1">
                                <Terminal size={10} className="text-text-3" />
                                {t.name} ({t.count})
                              </span>
                            ))}
                          </div>
                        </div>
                      )}

                      {/* LLM Narrative */}
                      {narrativeMap.get(s.session_id) && (
                        <div>
                          <div className="text-[10px] text-text-3 uppercase tracking-wider mb-1.5">AI Analysis</div>
                          <div className="bg-accent/5 border border-accent/20 rounded-lg p-3 text-xs text-text-2 leading-relaxed italic">
                            {narrativeMap.get(s.session_id)}
                          </div>
                        </div>
                      )}

                      {/* Opening prompt */}
                      {s.opening_prompt && (
                        <div>
                          <div className="text-[10px] text-text-3 uppercase tracking-wider mb-1.5">Opening Prompt</div>
                          <div className="bg-surface-0 border border-border-dim rounded-lg p-3 text-xs text-text-2 leading-relaxed max-h-32 overflow-y-auto font-mono">
                            {s.opening_prompt.slice(0, 500)}
                            {s.opening_prompt.length > 500 && <span className="text-text-3"> ... ({s.opening_prompt.length} chars)</span>}
                          </div>
                        </div>
                      )}
                    </div>
                  </motion.div>
                )}
              </AnimatePresence>
            </motion.div>
          );
        })}
      </div>
    </section>
  );
}
