import { useState, useEffect } from 'react'
import { PieChart, Pie, Cell, ResponsiveContainer, Legend, Tooltip } from 'recharts'
import { api } from '../utils/api'
import { useProfile } from '../context/ProfileContext'

/**
 * TrainingTypeDistribution - Pie chart showing activity distribution by type
 *
 * @param {number} days - Number of days to analyze (default: 28)
 */
export default function TrainingTypeDistribution({ days = 28 }) {
  const { activeProfile } = useProfile()  // Issue #31: Trigger reload on quality filter change
  const [data, setData] = useState([])
  const [categories, setCategories] = useState({})
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    const safeDays = Math.max(1, Math.min(4000, Number(days) || 28))
    const limit = Math.min(50_000, Math.max(250, safeDays * 25))
    Promise.all([
      api.listActivity(limit, safeDays),
      api.getTrainingCategories()
    ]).then(([activities, cats]) => {
      setCategories(cats)

      // Group by training_category
      const grouped = {}
      activities.forEach(act => {
        const cat = act.training_category || 'other'
        if (!grouped[cat]) grouped[cat] = 0
        grouped[cat]++
      })

      // Convert to chart data
      const chartData = Object.entries(grouped).map(([cat, count]) => ({
        name: cats[cat]?.name_de || 'Sonstiges',
        value: count,
        color: cats[cat]?.color || '#9CA3AF',
        icon: cats[cat]?.icon || '📝'
      }))

      setData(chartData.sort((a, b) => b.value - a.value))
      setLoading(false)
    }).catch(err => {
      console.error('Failed to load training type distribution:', err)
      setLoading(false)
    })
  }, [days, activeProfile?.quality_filter_level, activeProfile?.id])

  if (loading) {
    return (
      <div style={{textAlign:'center', padding:20}}>
        <div className="spinner" style={{width:24, height:24, margin:'0 auto'}}/>
      </div>
    )
  }

  if (data.length === 0) {
    return (
      <div style={{textAlign:'center', padding:20, color:'var(--text3)', fontSize:13}}>
        Keine Aktivitäten in den letzten {days} Tagen
      </div>
    )
  }

  const total = data.reduce((sum, d) => sum + d.value, 0)

  return (
    <div>
      <ResponsiveContainer width="100%" height={200}>
        <PieChart>
          <Pie
            data={data}
            cx="50%"
            cy="50%"
            innerRadius={50}
            outerRadius={80}
            paddingAngle={2}
            dataKey="value"
          >
            {data.map((entry, index) => (
              <Cell key={`cell-${index}`} fill={entry.color} />
            ))}
          </Pie>
          <Tooltip
            formatter={(value) => `${value} Einheiten (${Math.round(value/total*100)}%)`}
            contentStyle={{
              background:'var(--surface)',
              border:'1px solid var(--border)',
              borderRadius:8,
              fontSize:12
            }}
          />
        </PieChart>
      </ResponsiveContainer>

      {/* Legend */}
      <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:8, marginTop:12}}>
        {data.map((entry, i) => (
          <div key={i} style={{display:'flex', alignItems:'center', gap:6, fontSize:12}}>
            <div style={{
              width:12, height:12, borderRadius:'50%',
              background:entry.color, flexShrink:0
            }}/>
            <span style={{color:'var(--text2)'}}>
              {entry.icon} {entry.name}
            </span>
            <span style={{marginLeft:'auto', fontWeight:600, color:'var(--text1)'}}>
              {entry.value}
            </span>
          </div>
        ))}
      </div>

      <div style={{
        marginTop:12, padding:'8px 12px',
        background:'var(--surface)', borderRadius:8,
        fontSize:12, color:'var(--text3)', textAlign:'center'
      }}>
        Gesamt: <strong style={{color:'var(--text1)'}}>{total}</strong> Einheiten in {days} Tagen
      </div>
    </div>
  )
}
