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

interface CumulativeSavingsChartProps {
  roi: RoiResult
  horizonYears: number
  currency: string
  investment: number
}

export function CumulativeSavingsChart({
  roi,
  horizonYears,
  currency,
  investment,
}: CumulativeSavingsChartProps) {
  const option = useMemo(() => {
    const years = Array.from({ length: horizonYears + 1 }, (_, i) => i)
    const values = years.map((y) => roi.annualSavings * y - investment)

    const markLineData: unknown[] = []
    if (isFinite(roi.paybackYears) && roi.paybackYears > 0 && roi.paybackYears <= horizonYears) {
      markLineData.push({
        xAxis: roi.paybackYears,
        name: 'Payback',
        label: {
          formatter: `Payback\n${roi.paybackYears.toFixed(1)} años`,
          position: 'insideEndTop',
          fontSize: 10,
          color: '#16A34A',
          padding: [0, 0, 0, 8],
          offset: [4, 0],
        },
        lineStyle: { color: '#16A34A', type: 'dashed', width: 2 },
      })
    }

    // Línea de referencia en y=0 para identificar el break-even visualmente
    markLineData.push({
      yAxis: 0,
      name: 'Break-even',
      label: { formatter: '', position: 'insideStartTop' },
      lineStyle: { color: '#94a3b8', type: 'solid', width: 1 },
    })

    return {
      tooltip: {
        trigger: 'axis',
        formatter: (params: unknown[]) => {
          const p = params[0] as { dataIndex: number; value: [number, number] }
          const year = p.value[0]
          const val = p.value[1]
          return `<div style="font-size:12px;line-height:1.6">
            <div style="font-weight:600;margin-bottom:4px">Año ${year}</div>
            <div>Acumulado neto: <strong style="color:${val >= 0 ? '#16A34A' : '#EF4444'}">${formatCurrency(val, currency)}</strong></div>
          </div>`
        },
      },
      grid: { left: 16, right: 24, top: 16, bottom: 8, containLabel: true },
      xAxis: {
        type: 'value',
        name: 'Año',
        nameLocation: 'end',
        nameTextStyle: { fontSize: 10, color: '#94a3b8' },
        min: 0,
        max: horizonYears,
        interval: 1,
        axisLabel: { fontSize: 11, formatter: (v: number) => `Año ${v}` },
        splitLine: { lineStyle: { color: '#f1f5f9' } },
      },
      yAxis: {
        type: 'value',
        axisLabel: {
          fontSize: 11,
          formatter: (v: number) => {
            if (v === 0) return '0'
            const abs = Math.abs(v)
            const sign = v < 0 ? '-' : ''
            if (abs >= 1_000_000) return `${sign}${(abs / 1_000_000).toFixed(1)}M`
            if (abs >= 1_000) return `${sign}${(abs / 1_000).toFixed(0)}k`
            return String(v)
          },
        },
        splitLine: { lineStyle: { color: '#f1f5f9' } },
      },
      series: [
        {
          type: 'line',
          data: years.map((y, i) => [y, values[i]]),
          smooth: false,
          lineStyle: { color: '#F59845', width: 2.5 },
          areaStyle: {
            color: {
              type: 'linear',
              x: 0, y: 0, x2: 0, y2: 1,
              colorStops: [
                { offset: 0, color: 'rgba(245,152,69,0.18)' },
                { offset: 1, color: 'rgba(245,152,69,0.02)' },
              ],
            },
          },
          itemStyle: { color: '#F59845' },
          symbolSize: 6,
          markLine: {
            silent: true,
            symbol: ['none', 'none'],
            data: markLineData,
          },
        },
      ],
    }
  }, [roi, horizonYears, currency, investment])

  return <ReactECharts option={option} style={{ height: 280 }} notMerge />
}
