import { useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { useData } from '../hooks/useData';
import { ChevronDown, ChevronUp, Search, Code, Terminal, DollarSign } from 'lucide-react';
import CostInfoTip from './CostInfoTip';
import {
  RadarChart, Radar, PolarGrid, PolarAngleAxis, ResponsiveContainer,
  BarChart, Bar, XAxis, YAxis, Tooltip, Cell,
} from 'recharts';

interface Developer {
  email: string | null;
  total_sessions: number;
  total_user_messages: number;
  total_tool_calls: number;
  total_explore_calls: number;
  total_edit_calls: number;
  total_shell_calls: number;
  explore_to_edit_ratio: number | null;
  explore_to_edit_context: string | null;
  median_session_duration_min: number | null;
  single_interaction_sessions: number;
  total_hours: number;
  median_success_rate: number | null;
  median_prompts_before_edit: number | null;
  persona: string;
  sources: Record<string, number>;
  repos: string[];
  input_tokens: number;
  output_tokens: number;
  developer_summary?: string;
  avg_first_prompt_length?: number;
  median_first_prompt_length?: number;
  session_arcs?: Record<string, number>;
  active_hours?: number;
  wall_hours?: number;
  active_pct?: number;
  work_schedule?: string;
  peak_hour_ist?: number;
}

const PERSONA_COLORS: Record<string, string> = {
  Balanced: '#818cf8',
  Explorer: '#22d3ee',
  Delegator: '#34d399',
  Collaborator: '#fbbf24',
  Builder: '#fb7185',
};

const PERSONA_DESCRIPTIONS: Record<string, string> = {
  Balanced: 'Mix of exploration and editing, adaptable workflow',
  Explorer: 'Reads much more than edits — uses AI to understand code',
  Delegator: 'Few prompts, lets the agent work autonomously',
  Collaborator: 'Lots of back-and-forth, refining with the AI',
  Builder: 'High edit output, ships code frequently',
};

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

function shortName(email: string | null): string {
  if (!email) return '?';
  const name = shortEmail(email);
  // Extract initials
  return name.split(/[._+-]/).map(p => p[0]?.toUpperCase()).filter(Boolean).slice(0, 2).join('');
}

const SOURCE_COLORS: Record<string, string> = {
  claude_code: '#818cf8',
  codex_cli: '#34d399',
  gemini_cli: '#22d3ee',
  cursor: '#fbbf24',
};

const CustomTooltip = ({ active, payload, label }: any) => {
  if (!active || !payload?.length) return null;
  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">{label || payload[0]?.name}</div>
      <div className="text-text-1 font-semibold">{payload[0]?.value?.toLocaleString()}</div>
    </div>
  );
};

function DevCard({ dev, rank, maxValues, costInfo }: { dev: Developer; rank: number; maxValues: { sessions: number; explore: number; edit: number; shell: number; hours: number }; costInfo?: CostDeveloper }) {
  const [expanded, setExpanded] = useState(false);
  const color = PERSONA_COLORS[dev.persona] || '#818cf8';

  const radarData = [
    { axis: 'Sessions', value: (dev.total_sessions / (maxValues.sessions || 1)) * 100 },
    { axis: 'Explore', value: (dev.total_explore_calls / (maxValues.explore || 1)) * 100 },
    { axis: 'Edit', value: (dev.total_edit_calls / (maxValues.edit || 1)) * 100 },
    { axis: 'Shell', value: (dev.total_shell_calls / (maxValues.shell || 1)) * 100 },
    { axis: 'Hours', value: (dev.total_hours / (maxValues.hours || 1)) * 100 },
  ];

  const sourceData = Object.entries(dev.sources)
    .filter(([k]) => !['test', 'qc_trace_install'].includes(k))
    .map(([name, value]) => ({ name: name.replace('_', ' '), value, key: name }))
    .sort((a, b) => b.value - a.value);

  return (
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      whileInView={{ opacity: 1, y: 0 }}
      viewport={{ once: true }}
      transition={{ delay: rank * 0.08, duration: 0.4 }}
      className="bg-surface-1 border border-border-dim rounded-xl overflow-hidden"
    >
      {/* Header row */}
      <button
        onClick={() => setExpanded(!expanded)}
        className="w-full px-5 py-4 flex items-center gap-4 hover:bg-surface-2/50 transition-colors"
      >
        {/* Avatar */}
        <div
          className="w-10 h-10 rounded-full flex items-center justify-center text-sm font-bold shrink-0"
          style={{ background: `${color}22`, color }}
        >
          {shortName(dev.email)}
        </div>

        {/* Name & persona */}
        <div className="flex-1 min-w-0 text-left">
          <div className="text-sm font-semibold text-text-1 truncate">{shortEmail(dev.email)}</div>
          <div className="flex items-center gap-2 mt-0.5">
            <span
              className="text-[10px] font-semibold uppercase px-2 py-0.5 rounded-full"
              style={{ background: `${color}22`, color }}
            >
              {dev.persona}
            </span>
            <span className="text-xs text-text-3">{dev.repos.length} repos</span>
          </div>
          {dev.developer_summary && (
            <div className="text-xs text-text-3 mt-1 leading-snug max-w-md">{dev.developer_summary}</div>
          )}
        </div>

        {/* Quick stats */}
        <div className="hidden md:flex items-center gap-6 text-xs text-text-2">
          <div className="text-center">
            <div className="text-text-1 font-semibold text-sm">{dev.total_sessions}</div>
            <div className="text-text-3">sessions</div>
          </div>
          <div className="text-center">
            <div className="text-text-1 font-semibold text-sm">{Math.round(dev.total_hours)}h</div>
            <div className="text-text-3">with AI</div>
          </div>
          <div className="text-center">
            <div className="text-text-1 font-semibold text-sm">{dev.explore_to_edit_ratio?.toFixed(1) ?? '—'}x</div>
            <div className="text-text-3">explore/edit</div>
          </div>
          {costInfo && (
            <div className="text-center">
              <div className="text-amber font-semibold text-sm">${costInfo.total_cost_usd.toFixed(0)}</div>
              <div className="text-text-3">est. cost</div>
            </div>
          )}
        </div>

        {expanded ? <ChevronUp size={16} className="text-text-3" /> : <ChevronDown size={16} className="text-text-3" />}
      </button>

      {/* Expanded detail */}
      <AnimatePresence>
        {expanded && (
          <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">
              <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                {/* Radar chart */}
                <div>
                  <h4 className="text-xs font-medium text-text-3 uppercase tracking-wider mb-2">Activity Profile</h4>
                  <ResponsiveContainer width="100%" height={200}>
                    <RadarChart data={radarData}>
                      <PolarGrid stroke="#27272f" />
                      <PolarAngleAxis dataKey="axis" tick={{ fontSize: 10, fill: '#a1a1aa' }} />
                      <Radar dataKey="value" stroke={color} fill={color} fillOpacity={0.2} />
                    </RadarChart>
                  </ResponsiveContainer>
                </div>

                {/* CLI breakdown */}
                <div>
                  <h4 className="text-xs font-medium text-text-3 uppercase tracking-wider mb-2">CLI Tools Used</h4>
                  <ResponsiveContainer width="100%" height={200}>
                    <BarChart data={sourceData} layout="vertical" margin={{ left: 10, right: 10 }}>
                      <XAxis type="number" hide />
                      <YAxis type="category" dataKey="name" width={75} tick={{ fontSize: 11 }} />
                      <Tooltip content={<CustomTooltip />} />
                      <Bar dataKey="value" radius={[0, 4, 4, 0]}>
                        {sourceData.map(d => (
                          <Cell key={d.key} fill={SOURCE_COLORS[d.key] || '#63637a'} />
                        ))}
                      </Bar>
                    </BarChart>
                  </ResponsiveContainer>
                </div>

                {/* Stats grid */}
                <div className="grid grid-cols-2 gap-3">
                  <div className="bg-surface-2 rounded-lg p-3">
                    <Search size={12} className="text-text-3 mb-1" />
                    <div className="text-lg font-bold">{dev.total_explore_calls.toLocaleString()}</div>
                    <div className="text-xs text-text-3">explore calls</div>
                  </div>
                  <div className="bg-surface-2 rounded-lg p-3">
                    <Code size={12} className="text-text-3 mb-1" />
                    <div className="text-lg font-bold">{dev.total_edit_calls.toLocaleString()}</div>
                    <div className="text-xs text-text-3">edit calls</div>
                  </div>
                  <div className="bg-surface-2 rounded-lg p-3">
                    <Terminal size={12} className="text-text-3 mb-1" />
                    <div className="text-lg font-bold">{dev.total_shell_calls.toLocaleString()}</div>
                    <div className="text-xs text-text-3">shell calls</div>
                  </div>
                  <div className="bg-surface-2 rounded-lg p-3">
                    <Search size={12} className="text-text-3 mb-1" />
                    <div className="text-lg font-bold">{dev.median_prompts_before_edit ?? '—'}</div>
                    <div className="text-xs text-text-3">prompts to edit</div>
                  </div>
                  {costInfo && (
                    <>
                      <div className="bg-surface-2 rounded-lg p-3">
                        <div className="flex items-center gap-1 mb-1">
                          <DollarSign size={12} className="text-amber" />
                          <CostInfoTip />
                        </div>
                        <div className="text-lg font-bold text-amber">${costInfo.total_cost_usd.toFixed(2)}</div>
                        <div className="text-xs text-text-3">total cost</div>
                      </div>
                      <div className="bg-surface-2 rounded-lg p-3">
                        <DollarSign size={12} className="text-text-3 mb-1" />
                        <div className="text-lg font-bold">${costInfo.cost_per_session.toFixed(2)}</div>
                        <div className="text-xs text-text-3">per session</div>
                      </div>
                    </>
                  )}
                </div>
              </div>

              {/* Session arcs + prompt length */}
              <div className="mt-4 grid grid-cols-1 md:grid-cols-2 gap-4">
                {dev.session_arcs && Object.keys(dev.session_arcs).length > 0 && (
                  <div className="bg-surface-2 rounded-lg p-3">
                    <div className="text-[10px] text-text-3 uppercase tracking-wider mb-2">Session Patterns</div>
                    <div className="space-y-1.5">
                      {Object.entries(dev.session_arcs)
                        .sort(([, a], [, b]) => (b as number) - (a as number))
                        .filter(([, v]) => (v as number) > 0)
                        .map(([arc, count]) => {
                          const total = Object.values(dev.session_arcs!).reduce((s, v) => s + (v as number), 0);
                          const pct = total > 0 ? ((count as number) / total) * 100 : 0;
                          return (
                            <div key={arc} className="flex items-center gap-2">
                              <div className="w-24 text-[10px] text-text-2 truncate">{arc.replace(/_/g, ' ')}</div>
                              <div className="flex-1 h-2 bg-surface-0 rounded-full overflow-hidden">
                                <div className="h-full rounded-full bg-accent/50" style={{ width: `${pct}%` }} />
                              </div>
                              <span className="text-[10px] text-text-3 w-6 text-right">{count as number}</span>
                            </div>
                          );
                        })}
                    </div>
                  </div>
                )}
                <div className="bg-surface-2 rounded-lg p-3 space-y-2">
                  {dev.avg_first_prompt_length != null && (
                    <div>
                      <div className="text-[10px] text-text-3 uppercase tracking-wider mb-1">Avg First Prompt Length</div>
                      <div className="text-lg font-bold text-text-1">
                        {dev.avg_first_prompt_length >= 1000
                          ? `${(dev.avg_first_prompt_length / 1000).toFixed(1)}K`
                          : Math.round(dev.avg_first_prompt_length)} chars
                      </div>
                    </div>
                  )}
                  {dev.active_hours != null && (
                    <div>
                      <div className="text-[10px] text-text-3 uppercase tracking-wider mb-1">Active Time</div>
                      <div className="text-sm text-text-1">
                        <span className="font-bold">{dev.active_hours.toFixed(1)}h</span>
                        <span className="text-text-3"> of {dev.wall_hours?.toFixed(1)}h wall ({dev.active_pct?.toFixed(0)}%)</span>
                      </div>
                    </div>
                  )}
                  {dev.work_schedule && (
                    <div>
                      <div className="text-[10px] text-text-3 uppercase tracking-wider mb-1">Work Pattern</div>
                      <div className="text-xs text-text-2">{dev.work_schedule}</div>
                    </div>
                  )}
                </div>
              </div>

              {/* Persona description */}
              <div className="mt-4 text-xs text-text-3 bg-surface-2 rounded-lg p-3 space-y-1">
                <div>
                  <span className="font-semibold" style={{ color }}>
                    {dev.persona}:
                  </span>{' '}
                  {PERSONA_DESCRIPTIONS[dev.persona] || ''}
                </div>
                {dev.explore_to_edit_context && (
                  <div className="text-text-2">{dev.explore_to_edit_context}</div>
                )}
                {dev.single_interaction_sessions > 0 && (
                  <div className="text-text-3">
                    {dev.single_interaction_sessions} of {dev.total_sessions} sessions were single-shot ({'<'}1 min)
                  </div>
                )}
              </div>

              {/* Repos */}
              {dev.repos.length > 0 && (
                <div className="mt-3 flex flex-wrap gap-1.5">
                  {dev.repos.map(r => (
                    <span key={r} className="text-[10px] bg-surface-2 text-text-3 px-2 py-0.5 rounded-md border border-border-dim">
                      {r.split('/').pop()}
                    </span>
                  ))}
                </div>
              )}
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </motion.div>
  );
}

interface CostDeveloper {
  email: string;
  total_cost_usd: number;
  cost_per_session: number;
}

interface CostData {
  developers: CostDeveloper[];
}

export default function DeveloperProfiles() {
  const { data, loading } = useData<{ developers: Developer[] }>('/data/developer_profiles.json', { developers: [] });
  const { data: costData } = useData<CostData>('/data/cost_by_developer.json', { developers: [] });

  if (loading) return null;

  // Filter out NaN email developer (data artifact)
  const devs = data.developers
    .filter(d => d.email && typeof d.email === 'string' && d.total_sessions > 0)
    .sort((a, b) => b.total_sessions - a.total_sessions);

  if (!devs.length) return null;

  // Compute max values for radar normalization against dataset
  const maxValues = {
    sessions: Math.max(...devs.map(d => d.total_sessions)),
    explore: Math.max(...devs.map(d => d.total_explore_calls)),
    edit: Math.max(...devs.map(d => d.total_edit_calls)),
    shell: Math.max(...devs.map(d => d.total_shell_calls)),
    hours: Math.max(...devs.map(d => d.total_hours)),
  };

  // Build cost lookup
  const costByEmail = new Map(costData.developers.map(d => [d.email, d]));

  // Persona distribution
  const personaCounts: Record<string, number> = {};
  devs.forEach(d => {
    personaCounts[d.persona] = (personaCounts[d.persona] || 0) + 1;
  });

  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">
          {devs.length} developers, {Object.keys(personaCounts).length} distinct work styles.
        </h2>
        <p className="text-text-2 mb-3 max-w-2xl">
          Each developer has a unique relationship with AI coding assistants.
          We classified them based on how they balance exploration, editing, and delegation.
        </p>
        <div className="flex flex-wrap gap-2 mb-10">
          {Object.entries(personaCounts).map(([persona, count]) => (
            <span
              key={persona}
              className="text-xs font-semibold px-3 py-1 rounded-full"
              style={{
                background: `${PERSONA_COLORS[persona] || '#818cf8'}22`,
                color: PERSONA_COLORS[persona] || '#818cf8',
              }}
            >
              {count} {persona}{count > 1 ? 's' : ''}
            </span>
          ))}
        </div>
      </motion.div>

      <div className="flex flex-col gap-3">
        {devs.map((dev, i) => (
          <DevCard key={dev.email || i} dev={dev} rank={i} maxValues={maxValues} costInfo={costByEmail.get(dev.email || '')} />
        ))}
      </div>
    </section>
  );
}
