import { motion } from 'framer-motion';
import { useData } from '../hooks/useData';
import { Activity, DollarSign, Users, Clock, Zap, TrendingDown } from 'lucide-react';
import CostInfoTip from './CostInfoTip';

interface Overview {
  total_sessions: number;
  unique_users: number;
  estimated_cost_usd: number;
  total_hours_with_ai: number;
  total_tool_calls: number;
  median_session_duration_min: number;
  mean_session_duration_min: number;
  date_range: { start: string; end: string };
  sources: Record<string, number>;
  executive_summary?: string[];
  cost_context?: string;
  zero_edit_pct?: number;
  zero_edit_sessions?: number;
  total_active_hours?: number;
  active_time?: {
    total_active_hours: number;
    total_wall_hours: number;
    active_pct: number;
    headline: string;
  };
  annualized_cost_usd?: number;
  cost_per_productive_session?: number;
  cost_per_session?: number;
  session_duration?: {
    median_all_min: number;
    median_meaningful_min: number;
    mean_min: number;
    context: string;
    breakdown: {
      single_interaction_lt1min: number;
      short_1_to_5min: number;
      medium_5_to_60min: number;
      long_gt60min: number;
    };
  };
}

const fallback: Overview = {
  total_sessions: 0, unique_users: 0, estimated_cost_usd: 0,
  total_hours_with_ai: 0,
  total_tool_calls: 0, median_session_duration_min: 0,
  mean_session_duration_min: 0,
  date_range: { start: '', end: '' },
  sources: {},
};

function StatCard({ icon: Icon, label, value, sub, delay }: {
  icon: React.ElementType; label: string; value: string; sub?: string; delay: number;
}) {
  return (
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ delay, duration: 0.5 }}
      className="bg-surface-2 border border-border-dim rounded-xl p-5 flex flex-col gap-1"
    >
      <div className="flex items-center gap-2 text-text-3 text-xs font-medium uppercase tracking-wider">
        <Icon size={14} />
        {label}
      </div>
      <div className="text-2xl font-bold text-text-1">{value}</div>
      {sub && <div className="text-xs text-text-3">{sub}</div>}
    </motion.div>
  );
}

export default function Hero() {
  const { data: o, loading } = useData<Overview>('/data/overview.json', fallback);

  if (loading) return <div className="h-screen flex items-center justify-center text-text-3">Loading...</div>;

  const days = o.date_range.start && o.date_range.end
    ? Math.max(1, Math.round((new Date(o.date_range.end).getTime() - new Date(o.date_range.start).getTime()) / 86400000))
    : 1;

  const rawSummary = o.executive_summary;
  const summaryItems: string[] = Array.isArray(rawSummary)
    ? rawSummary
    : typeof rawSummary === 'string'
      ? rawSummary.split('. ').filter(Boolean).map(s => s.endsWith('.') ? s : s + '.')
      : [];

  const zeroEditPct = o.zero_edit_pct != null ? o.zero_edit_pct.toFixed(1) : null;
  const activeHours = o.active_time?.total_active_hours ?? o.total_active_hours ?? null;

  const sd = o.session_duration;
  const medianDisplay = sd?.median_meaningful_min?.toFixed(1) ?? o.median_session_duration_min?.toFixed(1) ?? '—';

  return (
    <section className="min-h-[80vh] flex flex-col justify-center px-8 max-w-7xl mx-auto">
      <motion.div
        initial={{ opacity: 0, y: -20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.8 }}
        className="mb-2"
      >
        <div className="flex items-center gap-3">
          <span className="text-xs font-medium uppercase tracking-widest text-accent">
            AI Developer Analytics
          </span>
          {o.date_range.start && o.date_range.end && (
            <span className="text-[10px] font-mono px-2 py-0.5 rounded-full bg-surface-2 border border-border-dim text-text-3">
              {new Date(o.date_range.start).toLocaleDateString('en-US', { month: 'short', year: 'numeric' })}
              {' - '}
              {new Date(o.date_range.end).toLocaleDateString('en-US', { month: 'short', year: 'numeric' })}
              {' '}({days} days)
            </span>
          )}
        </div>
      </motion.div>

      <motion.h1
        initial={{ opacity: 0, y: -10 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.8, delay: 0.1 }}
        className="text-4xl md:text-6xl font-extrabold leading-tight mb-3"
      >
        Your team spent <span className="text-accent">{Math.round(activeHours ?? o.total_hours_with_ai)}h</span> with AI
        <br />
        {zeroEditPct ? (
          <>and <span className="text-rose">{zeroEditPct}%</span> of sessions produced no code edits.</>
        ) : (
          <>across <span className="text-rose">{o.total_sessions}</span> sessions.</>
        )}
      </motion.h1>

      <motion.p
        initial={{ opacity: 0 }}
        animate={{ opacity: 1 }}
        transition={{ delay: 0.3, duration: 0.6 }}
        className="text-lg text-text-2 max-w-2xl mb-4"
      >
        {o.unique_users} developers. {o.total_sessions.toLocaleString()} sessions. {days} days.
        Here's what the trace data reveals about how your engineering team
        really uses AI coding assistants.
      </motion.p>

      {/* Adoption growth callout */}
      <motion.div
        initial={{ opacity: 0, x: -10 }}
        animate={{ opacity: 1, x: 0 }}
        transition={{ delay: 0.35, duration: 0.5 }}
        className="mb-10 inline-flex items-center gap-3 bg-accent/10 border border-accent/20 rounded-xl px-5 py-3"
      >
        <span className="text-2xl font-extrabold text-accent">7.7x</span>
        <span className="text-sm text-text-2">adoption growth in 5 months — from 17 sessions/mo to 131 sessions/mo — but {zeroEditPct ? `${zeroEditPct}%` : '60%'} of sessions still produce no code edits.</span>
      </motion.div>

      {/* Executive TL;DR from data */}
      <motion.div
        initial={{ opacity: 0 }}
        animate={{ opacity: 1 }}
        transition={{ delay: 0.35, duration: 0.6 }}
        className="mb-4 grid grid-cols-1 md:grid-cols-3 gap-3"
      >
        {summaryItems.map((text, i) => (
          <div key={i} className="bg-rose/5 border border-rose/20 rounded-xl px-4 py-3 flex items-start gap-3">
            <TrendingDown size={16} className="text-rose shrink-0 mt-0.5" />
            <span className="text-sm text-text-2 leading-snug">{text}</span>
          </div>
        ))}
      </motion.div>

      {/* Cost context callout */}
      {o.cost_context && (
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ delay: 0.4, duration: 0.6 }}
          className="mb-10 bg-surface-2 border border-border-dim rounded-xl px-5 py-3 text-sm text-text-2 max-w-3xl"
        >
          <DollarSign size={14} className="inline text-amber mr-1 -mt-0.5" />
          {o.cost_context}
        </motion.div>
      )}

      <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-3">
        <StatCard icon={Activity} label="Sessions" value={o.total_sessions.toLocaleString()} sub={`${Math.round(o.total_sessions / days)}/day`} delay={0.4} />
        <StatCard icon={Users} label="Developers" value={String(o.unique_users)} delay={0.45} />
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.5, duration: 0.5 }}
          className="bg-surface-2 border border-border-dim rounded-xl p-5 flex flex-col gap-1"
        >
          <div className="flex items-center gap-2 text-text-3 text-xs font-medium uppercase tracking-wider">
            <DollarSign size={14} />
            Est. Cost
            <CostInfoTip />
          </div>
          <div className="text-2xl font-bold text-text-1">${o.estimated_cost_usd.toLocaleString()}</div>
          <div className="text-xs text-text-3">${(o.estimated_cost_usd / days).toFixed(0)}/day -- see Methodology</div>
        </motion.div>
        {o.cost_per_productive_session != null && (
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.52, duration: 0.5 }}
            className="bg-surface-2 border border-rose/30 rounded-xl p-5 flex flex-col gap-1"
          >
            <div className="flex items-center gap-2 text-text-3 text-xs font-medium uppercase tracking-wider">
              <DollarSign size={14} />
              Cost / Productive Session
              <CostInfoTip />
            </div>
            <div className="text-2xl font-bold text-rose">${o.cost_per_productive_session.toFixed(2)}</div>
            <div className="text-xs text-text-3">
              vs ${(o.cost_per_session ?? (o.estimated_cost_usd / o.total_sessions)).toFixed(2)}/all sessions ({((o.cost_per_productive_session / (o.cost_per_session ?? (o.estimated_cost_usd / o.total_sessions))) ).toFixed(1)}x)
            </div>
          </motion.div>
        )}
        <StatCard icon={Clock} label="Median Session" value={`${medianDisplay}m`} sub={sd?.context ? 'active time, excl. idle >30m' : 'wall clock time'} delay={0.55} />
        <StatCard icon={Clock} label="Active AI Time" value={`${Math.round(activeHours ?? o.total_hours_with_ai)}h`} sub={activeHours ? `of ${Math.round(o.total_hours_with_ai)}h wall clock (idle >30m excluded)` : `${(o.total_hours_with_ai / o.unique_users).toFixed(0)}h/dev`} delay={0.6} />
        <StatCard icon={Zap} label="Tool Calls" value={o.total_tool_calls.toLocaleString()} sub={`${(o.total_tool_calls / o.total_sessions).toFixed(0)}/session`} delay={0.65} />
      </div>
    </section>
  );
}
