import { motion } from 'framer-motion';
import { useData } from '../hooks/useData';
import { DollarSign, TrendingUp, AlertTriangle } from 'lucide-react';
import CostInfoTip from './CostInfoTip';
import {
  BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer, Cell,
} from 'recharts';

interface Overview {
  estimated_cost_usd: number;
  total_sessions: number;
  total_hours_with_ai: number;
  unique_users: number;
  date_range: { start: string; end: string };
  tokens: {
    total_input: number;
    total_output: number;
    total_cached: number;
    total_thinking: number;
  };
}

interface CostDeveloper {
  email: string | null;
  total_cost_usd: number;
  cost_per_session: number;
  total_sessions: number;
  total_hours: number;
  cost_per_hour: number;
  persona: string;
}

interface SavingsOpp {
  count: number;
  estimated_cost_usd?: number;
  pct?: number;
  recommendation: string;
}

interface CostData {
  developers: CostDeveloper[];
  total_cost: number;
  annualized_cost: number;
  cost_per_dev_per_month: number;
  industry_benchmark: string;
  savings_opportunities?: Record<string, SavingsOpp>;
}

const COLORS = ['#818cf8', '#34d399', '#22d3ee', '#fbbf24', '#fb7185', '#a78bfa'];

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

const CustomTooltip = ({ active, payload }: any) => {
  if (!active || !payload?.length) return null;
  const d = payload[0]?.payload;
  return (
    <div className="bg-surface-3 border border-border-dim rounded-lg px-3 py-2 text-xs shadow-xl">
      <div className="text-text-2 mb-1">{d?.name}</div>
      <div className="text-text-1 font-semibold">${d?.cost?.toFixed(2) ?? payload[0]?.value}</div>
    </div>
  );
};

export default function CostBreakdown() {
  const { data: overview } = useData<Overview>('/data/overview.json', {
    estimated_cost_usd: 0, total_sessions: 0,
    total_hours_with_ai: 0, unique_users: 0,
    date_range: { start: '', end: '' },
    tokens: { total_input: 0, total_output: 0, total_cached: 0, total_thinking: 0 },
  });

  const { data: costData } = useData<CostData>('/data/cost_by_developer.json', {
    developers: [], total_cost: 0, annualized_cost: 0, cost_per_dev_per_month: 0, industry_benchmark: '',
  });

  if (!overview.estimated_cost_usd) return null;

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

  const costPerDay = overview.estimated_cost_usd / days;
  const annualized = costData.annualized_cost || costPerDay * 260;
  const costPerHour = overview.estimated_cost_usd / (overview.total_hours_with_ai || 1);
  const costPerSession = overview.estimated_cost_usd / (overview.total_sessions || 1);
  const costPerDev = overview.estimated_cost_usd / (overview.unique_users || 1);

  const devCosts = costData.developers
    .filter(d => d.email && typeof d.email === 'string')
    .map(d => ({
      name: shortEmail(d.email),
      cost: d.total_cost_usd,
      sessions: d.total_sessions,
    }))
    .sort((a, b) => b.cost - a.cost);

  return (
    <section className="px-8 max-w-7xl mx-auto py-20">
      <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">
          ${Math.round(annualized).toLocaleString()}/year projected
          <span className="text-rose"> -- at ${costPerDev.toFixed(0)}/dev over {days} days.</span>
          <CostInfoTip />
        </h2>
        <p className="text-text-2 mb-10 max-w-2xl">
          At ${costPerDay.toFixed(0)}/day over {days} days, your team's AI spend annualizes to
          ${Math.round(annualized).toLocaleString()}. That's ${costPerSession.toFixed(2)} per session.
          Here's where the money goes.
        </p>
      </motion.div>

      {/* Top-line metrics */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-3 mb-8">
        {[
          { label: 'Total Spend', value: `$${overview.estimated_cost_usd.toLocaleString()}`, sub: `${days} days`, icon: DollarSign, color: 'text-text-1' },
          { label: 'Cost/Session', value: `$${costPerSession.toFixed(2)}`, sub: `${overview.total_sessions} sessions`, icon: TrendingUp, color: 'text-amber' },
          { label: 'Cost/AI Hour', value: `$${costPerHour.toFixed(2)}`, sub: `${Math.round(overview.total_hours_with_ai)}h total`, icon: DollarSign, color: 'text-accent' },
          { label: 'Cost/Developer', value: `$${costPerDev.toFixed(0)}`, sub: `${overview.unique_users} devs`, icon: DollarSign, color: 'text-cyan' },
        ].map((m, i) => (
          <motion.div
            key={m.label}
            initial={{ opacity: 0, y: 20 }}
            whileInView={{ opacity: 1, y: 0 }}
            viewport={{ once: true }}
            transition={{ delay: i * 0.05, duration: 0.4 }}
            className="bg-surface-2 border border-border-dim rounded-xl p-4"
          >
            <div className="flex items-center gap-1.5 text-text-3 text-[10px] font-semibold uppercase tracking-wider mb-1">
              <m.icon size={12} />
              {m.label}
            </div>
            <div className={`text-xl font-bold ${m.color}`}>{m.value}</div>
            <div className="text-[10px] text-text-3 mt-0.5">{m.sub}</div>
          </motion.div>
        ))}
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Cost by developer */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          whileInView={{ opacity: 1, y: 0 }}
          viewport={{ once: true }}
          transition={{ delay: 0.1, duration: 0.5 }}
          className="bg-surface-1 border border-border-dim rounded-xl p-5 lg:col-span-2"
        >
          <h3 className="text-sm font-medium text-text-3 uppercase tracking-wider mb-4">
            Estimated Cost by Developer
          </h3>
          <ResponsiveContainer width="100%" height={Math.max(200, devCosts.length * 50)}>
            <BarChart data={devCosts} layout="vertical" margin={{ left: 10, right: 40 }}>
              <XAxis type="number" tick={{ fontSize: 10 }} tickFormatter={(v) => `$${v}`} />
              <YAxis type="category" dataKey="name" width={120} tick={{ fontSize: 12 }} />
              <Tooltip content={<CustomTooltip />} />
              <Bar dataKey="cost" radius={[0, 4, 4, 0]}>
                {devCosts.map((_, i) => (
                  <Cell key={i} fill={COLORS[i % COLORS.length]} />
                ))}
              </Bar>
            </BarChart>
          </ResponsiveContainer>
          <div className="mt-3 text-[10px] text-text-3 leading-relaxed">
            <span className="font-semibold text-text-2">Pricing model:</span> Claude 3.5 Sonnet — $3/1M input, $15/1M output, $0.30/1M cached. Codex CLI (GPT-4o) — $2.50/1M input, $10/1M output. Thinking tokens included at output rate. Actual billing depends on model variant and enterprise agreements.
          </div>
        </motion.div>

        {/* Cost allocation pie */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          whileInView={{ opacity: 1, y: 0 }}
          viewport={{ once: true }}
          transition={{ delay: 0.2, duration: 0.5 }}
          className="flex flex-col gap-4"
        >
          <div className="bg-surface-1 border border-border-dim rounded-xl p-5 flex-1">
            <h3 className="text-sm font-medium text-text-3 uppercase tracking-wider mb-4">
              Spend Concentration
            </h3>
            <div className="space-y-3">
              {devCosts.map((d, i) => {
                const pct = (d.cost / overview.estimated_cost_usd) * 100;
                return (
                  <div key={d.name}>
                    <div className="flex justify-between text-xs mb-1">
                      <span className="text-text-2 font-medium">{d.name}</span>
                      <span className="text-text-1 font-semibold">${d.cost.toFixed(0)} ({pct.toFixed(0)}%)</span>
                    </div>
                    <div className="h-2 bg-surface-3 rounded-full overflow-hidden">
                      <div className="h-full rounded-full" style={{ width: `${pct}%`, background: COLORS[i % COLORS.length] }} />
                    </div>
                  </div>
                );
              })}
            </div>
            <div className="mt-3 text-[10px] text-text-3 leading-relaxed">
              {devCosts.length > 0 && devCosts[0].cost / overview.estimated_cost_usd > 0.5 &&
                `${devCosts[0].name} accounts for ${((devCosts[0].cost / overview.estimated_cost_usd) * 100).toFixed(0)}% of total spend.`
              }
            </div>
          </div>

          <div className="bg-amber/5 border border-amber/20 rounded-xl p-4">
            <AlertTriangle size={14} className="text-amber mb-2" />
            <div className="text-xs text-text-2 leading-relaxed">
              <span className="font-semibold text-amber">Industry benchmark:</span>{' '}
              {costData.industry_benchmark || 'GitHub Copilot costs $19-39/dev/month'}. Your AI spend is{' '}
              <span className="text-text-1 font-semibold">
                ${Math.round(costData.cost_per_dev_per_month || costPerDev / (days / 30))}/dev/month
              </span>
              {' '}— but these are agentic sessions (30+ tool calls), not autocomplete suggestions.
              The question is whether the output justifies the premium.
            </div>
          </div>
        </motion.div>
      </div>

      {/* Savings opportunities */}
      {costData.savings_opportunities && Object.keys(costData.savings_opportunities).length > 0 && (
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          whileInView={{ opacity: 1, y: 0 }}
          viewport={{ once: true }}
          transition={{ delay: 0.3, duration: 0.5 }}
          className="mt-6 bg-green/5 border border-green/20 rounded-xl p-5"
        >
          <h3 className="text-sm font-medium text-green uppercase tracking-wider mb-3">
            Potential Savings
          </h3>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
            {Object.entries(costData.savings_opportunities).map(([key, opp]) => (
              <div key={key} className="bg-surface-1 border border-border-dim rounded-lg p-4">
                <div className="text-xs text-text-3 uppercase tracking-wider mb-1">{key.replace(/_/g, ' ')}</div>
                <div className="text-sm text-text-2 leading-relaxed">{opp.recommendation}</div>
                {opp.estimated_cost_usd != null && (
                  <div className="mt-2 text-xs text-green font-semibold">
                    ~${opp.estimated_cost_usd.toFixed(2)} saveable per period
                  </div>
                )}
              </div>
            ))}
          </div>
        </motion.div>
      )}
    </section>
  );
}
