import React, { useMemo } from 'react';
import {
  BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer,
  PieChart, Pie, Cell, Legend,
} from 'recharts';
import type { CharacterState } from '../../types';

interface Props {
  characters: Map<string, CharacterState>;
}

const ELEMENT_COLORS: Record<string, string> = {
  Slash: '#cc4444',
  Pierce: '#44cc44',
  Bludgeon: '#888888',
  Fire: '#ff6622',
  Cold: '#4488ff',
  Acid: '#44cc44',
  Electric: '#ffcc00',
  Typeless: '#aa66cc',
};

export const CombatTab: React.FC<Props> = ({ characters }) => {
  // Kill rate per character
  const killData = useMemo(() => {
    return Array.from(characters.values())
      .filter(c => c.telemetry)
      .map(c => ({
        name: c.name.length > 18 ? c.name.slice(0, 16) + '..' : c.name,
        fullName: c.name,
        killsPerHour: parseInt(c.telemetry!.kills_per_hour) || 0,
        totalKills: c.telemetry!.kills || 0,
      }))
      .sort((a, b) => b.killsPerHour - a.killsPerHour)
      .slice(0, 30);
  }, [characters]);

  // Damage given per character (from combat stats)
  const damageData = useMemo(() => {
    return Array.from(characters.values())
      .filter(c => c.combat?.session)
      .map(c => ({
        name: c.name.length > 18 ? c.name.slice(0, 16) + '..' : c.name,
        fullName: c.name,
        damage: c.combat!.session!.total_damage_given,
      }))
      .sort((a, b) => b.damage - a.damage)
      .slice(0, 30);
  }, [characters]);

  // Aggregate element breakdown across all characters
  const elementData = useMemo(() => {
    const totals: Record<string, number> = {};
    for (const ch of characters.values()) {
      const session = ch.combat?.session;
      if (!session?.monsters) continue;
      for (const mon of Object.values(session.monsters)) {
        if (!mon.offense) continue;
        for (const byEl of Object.values(mon.offense)) {
          for (const [el, stats] of Object.entries(byEl)) {
            if (el === 'None' || el === 'Unknown') continue;
            totals[el] = (totals[el] || 0) + (stats.damage || 0);
          }
        }
      }
    }
    return Object.entries(totals)
      .map(([name, value]) => ({ name, value }))
      .filter(d => d.value > 0)
      .sort((a, b) => b.value - a.value);
  }, [characters]);

  return (
    <div className="combat-tab">
      <div className="chart-section">
        <h3 className="chart-title">Kills per Hour</h3>
        <ResponsiveContainer width="100%" height={Math.max(200, killData.length * 28)}>
          <BarChart data={killData} layout="vertical" margin={{ left: 10, right: 20, top: 5, bottom: 5 }}>
            <CartesianGrid strokeDasharray="3 3" stroke="#333" />
            <XAxis type="number" stroke="#888" fontSize={11} />
            <YAxis type="category" dataKey="name" width={130} stroke="#888" fontSize={11} />
            <Tooltip
              contentStyle={{ background: '#1a1a1a', border: '1px solid #444', fontSize: 12 }}
              formatter={(v: number) => [v.toLocaleString(), 'Kills/hr']}
              labelFormatter={(l, payload) => payload?.[0]?.payload?.fullName || l}
            />
            <Bar dataKey="killsPerHour" fill="#44cc44" radius={[0, 3, 3, 0]} />
          </BarChart>
        </ResponsiveContainer>
      </div>

      {damageData.length > 0 && (
        <div className="chart-section">
          <h3 className="chart-title">Total Damage (Session)</h3>
          <ResponsiveContainer width="100%" height={Math.max(200, damageData.length * 28)}>
            <BarChart data={damageData} layout="vertical" margin={{ left: 10, right: 20, top: 5, bottom: 5 }}>
              <CartesianGrid strokeDasharray="3 3" stroke="#333" />
              <XAxis type="number" stroke="#888" fontSize={11} />
              <YAxis type="category" dataKey="name" width={130} stroke="#888" fontSize={11} />
              <Tooltip
                contentStyle={{ background: '#1a1a1a', border: '1px solid #444', fontSize: 12 }}
                formatter={(v: number) => [v.toLocaleString(), 'Damage']}
                labelFormatter={(l, payload) => payload?.[0]?.payload?.fullName || l}
              />
              <Bar dataKey="damage" fill="#ff6644" radius={[0, 3, 3, 0]} />
            </BarChart>
          </ResponsiveContainer>
        </div>
      )}

      {elementData.length > 0 && (
        <div className="chart-section">
          <h3 className="chart-title">Damage by Element (All Characters)</h3>
          <ResponsiveContainer width="100%" height={300}>
            <PieChart>
              <Pie
                data={elementData}
                dataKey="value"
                nameKey="name"
                cx="50%"
                cy="50%"
                outerRadius={100}
                label={({ name, percent }) => `${name} ${(percent * 100).toFixed(0)}%`}
                labelLine={true}
                fontSize={12}
              >
                {elementData.map((d) => (
                  <Cell key={d.name} fill={ELEMENT_COLORS[d.name] || '#888'} />
                ))}
              </Pie>
              <Tooltip
                contentStyle={{ background: '#1a1a1a', border: '1px solid #444', fontSize: 12 }}
                formatter={(v: number) => v.toLocaleString()}
              />
              <Legend wrapperStyle={{ fontSize: 12, color: '#aaa' }} />
            </PieChart>
          </ResponsiveContainer>
        </div>
      )}
    </div>
  );
};
