import { useMemo } from 'react'
import ReactECharts from 'echarts-for-react'
import { formatCurrency } from '@/lib/format'
import type { ActivitySimResult } from '@/domain/types'

interface TopSavingsChartProps {
  perActivityActual: ActivitySimResult[]
  perActivityAutomated: ActivitySimResult[]
  currency: string
}

function truncate(s: string, max: number) {
  return s.length > max ? s.slice(0, max - 1) + '…' : s
}

export function TopSavingsChart({
  perActivityActual,
  perActivityAutomated,
  currency,
}: TopSavingsChartProps) {
  const option = useMemo(() => {
    const automatedMap = new Map(perActivityAutomated.map((a) => [a.activityId, a]))

    const top5 = perActivityActual
      .map((act) => {
        const auto = automatedMap.get(act.activityId)
        const savings = act.expectedTotalCost - (auto?.expectedTotalCost ?? act.expectedTotalCost)
        return { name: act.activityName, value: savings }
      })
      .filter((s) => s.value > 0)
      .sort((a, b) => b.value - a.value)
      .slice(0, 5)

    if (top5.length === 0) return null

    const reversed = [...top5].reverse()

    return {
      tooltip: {
        trigger: 'axis',
        axisPointer: { type: 'shadow' },
        formatter: (params: unknown[]) => {
          const p = params[0] as { name: string; value: number }
          return `<div style="font-size:12px"><b>${p.name}</b><br/>Ahorro: <strong>${formatCurrency(p.value, currency)}</strong></div>`
        },
      },
      grid: { left: 12, right: 32, top: 8, bottom: 8, containLabel: true },
      xAxis: {
        type: 'value',
        axisLabel: {
          fontSize: 10,
          formatter: (v: number) => {
            if (v === 0) return '0'
            if (v >= 1_000_000) return `${(v / 1_000_000).toFixed(1)}M`
            if (v >= 1_000) return `${(v / 1_000).toFixed(0)}k`
            return String(v)
          },
        },
        splitLine: { lineStyle: { color: '#f1f5f9' } },
      },
      yAxis: {
        type: 'category',
        data: reversed.map((s) => truncate(s.name, 22)),
        axisLabel: { fontSize: 10, color: '#64748b' },
        axisTick: { show: false },
        axisLine: { show: false },
      },
      series: [
        {
          type: 'bar',
          data: reversed.map((s) => s.value),
          barMaxWidth: 32,
          itemStyle: { color: '#16A34A', borderRadius: [0, 4, 4, 0] },
          label: {
            show: true,
            position: 'right',
            fontSize: 10,
            formatter: (p: { value: number }) => formatCurrency(p.value, currency),
            color: '#16A34A',
          },
        },
      ],
    }
  }, [perActivityActual, perActivityAutomated, currency])

  if (!option) {
    return (
      <div className="flex items-center justify-center h-48 text-xs text-slate-400">
        Sin actividades con ahorro positivo
      </div>
    )
  }

  return <ReactECharts option={option} style={{ height: Math.max(180, option.yAxis.data.length * 48) }} notMerge />
}
