import { motion } from 'framer-motion';
import { useData } from '../hooks/useData';
import {
  ComposedChart, Bar, Line, XAxis, YAxis, Tooltip, ResponsiveContainer, CartesianGrid, Legend,
} from 'recharts';

interface MonthData {
  month: string;
  label: string;
  sessions: number;
  messages: number;
  user_msgs: number;
  tool_calls: number;
  cost_usd: number;
  zero_edit_pct: number;
}

interface AdoptionPhase {
  phase: string;
  period: string;
  description: string;
  sessions: number;
}

interface ChartData {
  monthly_trends?: {
    headline?: string;
    months?: MonthData[];
    adoption_phases?: AdoptionPhase[];
  };
}

const tooltipStyle = {
  contentStyle: { background: '#1a1a2e', border: '1px solid rgba(255,255,255,0.1)', borderRadius: 8, color: '#e2e8f0' },
  itemStyle: { color: '#e2e8f0' },
};

const phaseColors: Record<string, string> = {
  'Early exploration': '#f59e0b',
  'Dormant': '#64748b',
  'Rapid adoption': '#22d3ee',
};

export default function MonthlyTrends() {
  const { data, loading } = useData<ChartData>('/data/chart_data.json', {});
  const mt = data.monthly_trends;
  if (loading || !mt) return null;

  const months = Array.isArray(mt.months) ? mt.months : [];
  const phases = Array.isArray(mt.adoption_phases) ? mt.adoption_phases : [];
  if (months.length === 0) return null;

  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 font-bold mb-2">
          From zero to <span className="text-cyan">131 sessions/month</span> in 5 months
        </h2>
        {mt.headline && <p className="text-text-2 text-sm mb-8 max-w-2xl">{mt.headline}</p>}

        {/* Adoption phases */}
        {phases.length > 0 && (
          <div className="flex gap-3 mb-8 flex-wrap">
            {phases.map((p) => (
              <div
                key={p.phase}
                className="bg-surface-2 border border-border-dim rounded-xl px-4 py-3 flex-1 min-w-[200px]"
              >
                <div className="flex items-center gap-2 mb-1">
                  <div className="w-2 h-2 rounded-full" style={{ background: phaseColors[p.phase] || '#94a3b8' }} />
                  <span className="text-xs font-semibold uppercase tracking-wider text-text-3">{p.period}</span>
                </div>
                <div className="text-sm font-bold text-text-1 mb-1">{p.phase}</div>
                <div className="text-xs text-text-3 leading-relaxed">{p.description}</div>
                <div className="text-xs text-text-3 mt-2 font-mono">{p.sessions} sessions</div>
              </div>
            ))}
          </div>
        )}

        {/* Main chart: sessions + cost bars, zero-edit line */}
        <div className="bg-surface-1 border border-border-dim rounded-xl p-6 mb-6">
          <h3 className="text-sm font-semibold text-text-2 mb-4">Sessions, Cost, and Zero-Edit Rate by Month</h3>
          <ResponsiveContainer width="100%" height={340}>
            <ComposedChart data={months} margin={{ top: 10, right: 20, bottom: 0, left: 0 }}>
              <CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.05)" />
              <XAxis dataKey="label" tick={{ fill: '#94a3b8', fontSize: 12 }} tickLine={false} axisLine={false} />
              <YAxis yAxisId="left" tick={{ fill: '#94a3b8', fontSize: 11 }} tickLine={false} axisLine={false} />
              <YAxis yAxisId="right" orientation="right" domain={[0, 100]} tick={{ fill: '#f87171', fontSize: 11 }} tickLine={false} axisLine={false} tickFormatter={(v: number) => `${v}%`} />
              <Tooltip
                {...tooltipStyle}
                formatter={(value: number, name: string) => {
                  if (name === 'Zero-Edit %') return [`${value.toFixed(1)}%`, name];
                  if (name === 'Cost ($)') return [`$${value.toFixed(2)}`, name];
                  return [value, name];
                }}
              />
              <Legend wrapperStyle={{ color: '#94a3b8', fontSize: 11 }} />
              <Bar yAxisId="left" dataKey="sessions" name="Sessions" fill="#22d3ee" radius={[4, 4, 0, 0]} barSize={32} />
              <Bar yAxisId="left" dataKey="cost_usd" name="Cost ($)" fill="#a78bfa" radius={[4, 4, 0, 0]} barSize={32} />
              <Line yAxisId="right" dataKey="zero_edit_pct" name="Zero-Edit %" stroke="#f87171" strokeWidth={2} dot={{ fill: '#f87171', r: 4 }} />
            </ComposedChart>
          </ResponsiveContainer>
        </div>

        {/* Tool calls growth */}
        <div className="bg-surface-1 border border-border-dim rounded-xl p-6">
          <h3 className="text-sm font-semibold text-text-2 mb-4">Tool Calls and Messages by Month</h3>
          <ResponsiveContainer width="100%" height={260}>
            <ComposedChart data={months} margin={{ top: 10, right: 20, bottom: 0, left: 0 }}>
              <CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.05)" />
              <XAxis dataKey="label" tick={{ fill: '#94a3b8', fontSize: 12 }} tickLine={false} axisLine={false} />
              <YAxis tick={{ fill: '#94a3b8', fontSize: 11 }} tickLine={false} axisLine={false} />
              <Tooltip {...tooltipStyle} formatter={(value: number, name: string) => [value.toLocaleString(), name]} />
              <Legend wrapperStyle={{ color: '#94a3b8', fontSize: 11 }} />
              <Bar dataKey="tool_calls" name="Tool Calls" fill="#34d399" radius={[4, 4, 0, 0]} barSize={28} />
              <Bar dataKey="user_msgs" name="User Messages" fill="#60a5fa" radius={[4, 4, 0, 0]} barSize={28} />
            </ComposedChart>
          </ResponsiveContainer>
        </div>
      </motion.div>
    </section>
  );
}
