'use client'

// Cost-structure bucket chart (KAR-840, V11 section 1 — summary mode).
// Grouped bars ALT vs. NEU per cost bucket with a Δ annotation above each
// group and a click-to-toggle legend (V11 interactivity). Colors are the
// V11 stand colors (spec 3.10 — display constants, key-stable).

import { useState } from 'react'
import {
  Bar,
  BarChart,
  CartesianGrid,
  LabelList,
  Legend,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
} from 'recharts'
import type { BucketDatum } from '@/lib/qaf-differences'
import { moneyFormatter } from './format'

// V11 STAND_COLORS (b5_compare.js) — q0 = ALT, q1 = NEU. Registered as CSS
// vars in globals.css (light + dark) so the chart follows the theme.
const ALT_COLOR = 'var(--qaf-stand-alt)'
const NEU_COLOR = 'var(--qaf-stand-neu)'

export interface SeriesVisibility {
  alt: boolean
  neu: boolean
}

/** Legend click: toggle a series, but never hide both (empty chart reads as a bug). */
export function toggleSeries(hidden: SeriesVisibility, dataKey: string): SeriesVisibility {
  if (dataKey !== 'alt' && dataKey !== 'neu') return hidden
  const next = { ...hidden, [dataKey]: !hidden[dataKey] }
  return next.alt && next.neu ? hidden : next
}

const deltaFmt = new Intl.NumberFormat('de-DE', { maximumFractionDigits: 2, signDisplay: 'exceptZero' })

export interface DeltaAnnotation {
  arrow: '▲' | '▼'
  text: string
  fill: string
}

/** Δ annotation above the NEU bar: ▲ red = teurer, ▼ green = günstiger. */
export function resolveDeltaAnnotation(delta: number | null | undefined): DeltaAnnotation | null {
  if (delta === null || delta === undefined || delta === 0) return null
  const up = delta > 0
  return {
    arrow: up ? '▲' : '▼',
    text: deltaFmt.format(delta),
    fill: up ? 'var(--destructive)' : 'var(--success-text)',
  }
}

interface Props {
  buckets: BucketDatum[]
  currency: string | null
}

const valueFmt = new Intl.NumberFormat('de-DE', { maximumFractionDigits: 2 })

// Absolute value on top of each bar (Kais feedback 05.07.: "Werte fehlen").
function ValueLabel(props: { x?: number | string; y?: number | string; width?: number | string; value?: number | string }) {
  const { x, y, width, value } = props
  if (x === undefined || y === undefined || width === undefined || value === undefined) return null
  const n = Number(value)
  if (!Number.isFinite(n) || n === 0) return null
  return (
    <text x={Number(x) + Number(width) / 2} y={Number(y) - 4} textAnchor="middle" fontSize={10} fill="var(--muted-foreground)">
      {valueFmt.format(n)}
    </text>
  )
}

function DeltaLabel(props: {
  x?: number | string
  y?: number | string
  width?: number | string
  index?: number
  buckets: BucketDatum[]
}) {
  const { x, y, width, index, buckets } = props
  if (index === undefined || x === undefined || y === undefined || width === undefined) return null
  const annotation = resolveDeltaAnnotation(buckets[index]?.delta)
  if (!annotation) return null
  return (
    <text
      x={Number(x) + Number(width) / 2}
      y={Number(y) - 20}
      textAnchor="middle"
      fontSize={11}
      fontWeight={600}
      fill={annotation.fill}
    >
      {annotation.arrow} {annotation.text}
    </text>
  )
}

export default function QafCostStructureChart({ buckets, currency }: Props) {
  const [hidden, setHidden] = useState<SeriesVisibility>({ alt: false, neu: false })
  const fmt = moneyFormatter(currency)

  return (
    <div className="h-72 w-full" data-testid="qaf-cost-structure-chart">
      <ResponsiveContainer width="100%" height="100%">
        <BarChart data={buckets} margin={{ top: 40, right: 8, left: 8, bottom: 0 }} barCategoryGap="24%">
          <CartesianGrid strokeDasharray="3 3" stroke="var(--border)" vertical={false} />
          <XAxis dataKey="label" tick={{ fontSize: 12 }} tickLine={false} axisLine={{ stroke: 'var(--border)' }} />
          <YAxis
            tick={{ fontSize: 11 }}
            tickLine={false}
            axisLine={false}
            tickFormatter={(v: number) => fmt(v)}
            width={82}
          />
          <Tooltip
            formatter={(value, name) => [fmt(Number(value ?? 0)), String(name)]}
            cursor={{ fill: 'var(--muted)' }}
            contentStyle={{ fontSize: 12, borderRadius: 2, border: '1px solid var(--border)' }}
          />
          <Legend
            onClick={(e) => setHidden((h) => toggleSeries(h, String(e.dataKey)))}
            wrapperStyle={{ fontSize: 12, cursor: 'pointer' }}
            formatter={(value: string, entry) =>
              hidden[String(entry.dataKey) as keyof SeriesVisibility] ? `${value} (aus)` : value
            }
          />
          <Bar dataKey="alt" name="QAF ALT" fill={ALT_COLOR} hide={hidden.alt} radius={[2, 2, 0, 0]} isAnimationActive={false}>
            <LabelList content={(p) => <ValueLabel {...(p as object)} />} />
          </Bar>
          <Bar dataKey="neu" name="QAF NEU" fill={NEU_COLOR} hide={hidden.neu} radius={[2, 2, 0, 0]} isAnimationActive={false}>
            <LabelList content={(p) => <ValueLabel {...(p as object)} />} />
            <LabelList content={(p) => <DeltaLabel {...(p as object)} buckets={buckets} />} />
          </Bar>
        </BarChart>
      </ResponsiveContainer>
    </div>
  )
}
