import { useMemo, useRef, useState, useEffect } from 'react';

const INK = '#0A0A0A';
const PAPER = '#F4F1EA';
const SIGNAL = '#FF4D1F';
const STAMP = '#FFD93D';
const STATE = '#1A3D2E';
const VOID = '#E5E1D8';

export interface BarRaceRowIn {
  supplier: string;
  cui: string | null;
  value: number;
  monthlyValue: number;
  rank: number;
}

interface Props {
  months: string[];
  byMonth: Record<string, BarRaceRowIn[]>;
  height?: number;
}

function fmtRon(v: number): string {
  if (v >= 1_000_000_000) return `${(v / 1_000_000_000).toFixed(2)} mld`;
  if (v >= 1_000_000) return `${(v / 1_000_000).toFixed(1)} mil`;
  if (v >= 1_000) return `${(v / 1_000).toFixed(0)}K`;
  return v.toFixed(0);
}

const ROMANIAN_MONTHS = ['IAN', 'FEB', 'MAR', 'APR', 'MAI', 'IUN', 'IUL', 'AUG', 'SEP', 'OCT', 'NOI', 'DEC'];
function fmtMonthHeading(yyyymm: string): string {
  const [y, m] = yyyymm.split('-');
  const idx = parseInt(m, 10) - 1;
  return `${ROMANIAN_MONTHS[idx] || m} ${y}`;
}

export function BarRace({ months, byMonth, height = 720 }: Props) {
  const containerRef = useRef<HTMLDivElement>(null);
  const [width, setWidth] = useState(1200);
  const [idx, setIdx] = useState(months.length > 0 ? months.length - 1 : 0);
  const [playing, setPlaying] = useState(false);
  const [flashed, setFlashed] = useState(false);
  const prevRanks = useRef<Map<string, number>>(new Map());

  useEffect(() => {
    if (!containerRef.current) return;
    const ro = new ResizeObserver((entries) => {
      for (const e of entries) setWidth(Math.max(640, e.contentRect.width));
    });
    ro.observe(containerRef.current);
    setWidth(containerRef.current.clientWidth);
    return () => ro.disconnect();
  }, []);

  useEffect(() => {
    setFlashed(true);
    const t = setTimeout(() => setFlashed(false), 600);
    return () => clearTimeout(t);
  }, []);

  // Autoplay
  useEffect(() => {
    if (!playing) return;
    if (months.length === 0) return;
    const t = setInterval(() => {
      setIdx(i => {
        if (i >= months.length - 1) {
          setPlaying(false);
          return i;
        }
        return i + 1;
      });
    }, 900);
    return () => clearInterval(t);
  }, [playing, months.length]);

  const currentMonth = months[idx] || '';
  const rows = byMonth[currentMonth] || [];

  // Track previous ranks to detect movers
  useEffect(() => {
    const newRanks = new Map<string, number>();
    rows.forEach(r => newRanks.set(r.cui || r.supplier, r.rank));
    prevRanks.current = newRanks;
    // intentionally not in deps — we want to update every render
  });

  const maxValue = Math.max(...rows.map(r => r.value), 1);

  // Layout
  const headerH = 84;
  const sliderH = 64;
  const rowsAreaH = height - headerH - sliderH;
  const rowGap = 8;
  const rowH = rows.length > 0 ? Math.max(34, Math.floor((rowsAreaH - rowGap * (rows.length - 1)) / rows.length)) : 34;
  const labelW = 220;
  const valueW = 130;
  const padX = 16;
  const barAreaW = Math.max(120, width - padX * 2 - labelW - valueW);

  function colorFor(rank: number, prevRank: number | undefined): string {
    if (rank === 1) return SIGNAL;
    if (prevRank !== undefined && prevRank > rank) return STAMP; // moved up
    return INK;
  }

  return (
    <div ref={containerRef} className="relative w-full bg-paper border-2 border-ink overflow-hidden" style={{ height }}>
      {/* Header */}
      <div className="border-b-2 border-ink px-4 pt-3 pb-2 flex items-baseline justify-between" style={{ height: headerH }}>
        <div>
          <div className="font-mono text-[10px] uppercase tracking-meta text-ink/60">
            TOP 10 FIRME · CUMULATIV LA
          </div>
          <div className="font-display font-bold text-3xl md:text-5xl text-ink leading-none mt-1 tabular-nums">
            {fmtMonthHeading(currentMonth)}
          </div>
        </div>
        <div className="text-right">
          <div className="font-mono text-[10px] uppercase tracking-meta text-ink/60">
            LUNA {idx + 1} DIN {months.length}
          </div>
          <div className="font-mono text-xs text-ink/60 tabular-nums mt-1">
            {currentMonth}
          </div>
        </div>
      </div>

      {/* Bars area */}
      <svg width={width} height={rowsAreaH} className="block" style={{ marginTop: 0 }}>
        <g>
          {rows.map((r, i) => {
            const prevRank = prevRanks.current.get(r.cui || r.supplier);
            const fill = flashed ? STAMP : colorFor(r.rank, prevRank);
            const barW = (r.value / maxValue) * barAreaW;
            const y = i * (rowH + rowGap);
            const labelX = padX;
            const barX = padX + labelW;

            return (
              <g
                key={r.cui || r.supplier}
                style={{ cursor: r.cui ? 'pointer' : 'default' }}
                onClick={() => { if (r.cui) window.location.href = `/firma/${r.cui}`; }}
              >
                {/* Rank + supplier label */}
                <text
                  x={labelX}
                  y={y + rowH / 2}
                  dy="0.32em"
                  fontFamily='"JetBrains Mono", monospace'
                  fontSize={10}
                  fontWeight={700}
                  fill={INK}
                  fillOpacity={0.4}
                  style={{ textTransform: 'uppercase', letterSpacing: '0.08em' }}
                >
                  {String(r.rank).padStart(2, '0')}
                </text>
                <text
                  x={labelX + 28}
                  y={y + rowH / 2}
                  dy="0.32em"
                  fontFamily='"Bricolage Grotesque", "Plus Jakarta Sans", sans-serif'
                  fontSize={13}
                  fontWeight={700}
                  fill={INK}
                  style={{ pointerEvents: 'none' }}
                >
                  {r.supplier.length > 26 ? r.supplier.slice(0, 25) + '…' : r.supplier}
                </text>

                {/* Bar */}
                <rect
                  x={barX}
                  y={y}
                  width={barW}
                  height={rowH}
                  fill={fill}
                  stroke={INK}
                  strokeWidth={2}
                  style={{ transition: 'width 800ms ease-out, fill 200ms linear' }}
                />

                {/* Value */}
                <text
                  x={barX + barW + 8}
                  y={y + rowH / 2}
                  dy="0.32em"
                  fontFamily='"JetBrains Mono", monospace'
                  fontSize={12}
                  fontWeight={700}
                  fill={INK}
                  style={{ pointerEvents: 'none' }}
                >
                  {fmtRon(r.value)} RON
                </text>
              </g>
            );
          })}
        </g>
      </svg>

      {/* Slider + autoplay */}
      <div className="absolute bottom-0 left-0 right-0 border-t-2 border-ink bg-paper px-4 py-3 flex items-center gap-3" style={{ height: sliderH }}>
        <button
          onClick={() => {
            if (idx >= months.length - 1) setIdx(0);
            setPlaying(p => !p);
          }}
          className="border-2 border-ink bg-ink text-paper hover:bg-stamp hover:text-ink font-mono text-xs uppercase tracking-meta px-3 py-2 transition-none"
          style={{ minWidth: 72 }}
        >
          {playing ? '◼ STOP' : '▶ PLAY'}
        </button>

        <div className="flex-1 flex items-center gap-2">
          <span className="font-mono text-[10px] uppercase tracking-meta text-ink/60 tabular-nums">
            {months[0] || ''}
          </span>
          <input
            type="range"
            min={0}
            max={Math.max(0, months.length - 1)}
            value={idx}
            onChange={(e) => { setPlaying(false); setIdx(parseInt(e.target.value, 10)); }}
            className="brutal-slider flex-1"
          />
          <span className="font-mono text-[10px] uppercase tracking-meta text-ink/60 tabular-nums">
            {months[months.length - 1] || ''}
          </span>
        </div>
      </div>

      <style>{`
        .brutal-slider { -webkit-appearance: none; appearance: none; height: 4px; background: ${INK}; outline: none; border-radius: 0; }
        .brutal-slider::-webkit-slider-thumb { -webkit-appearance: none; appearance: none; width: 14px; height: 22px; background: ${SIGNAL}; border: 2px solid ${INK}; cursor: pointer; border-radius: 0; }
        .brutal-slider::-moz-range-thumb { width: 14px; height: 22px; background: ${SIGNAL}; border: 2px solid ${INK}; cursor: pointer; border-radius: 0; }
      `}</style>
    </div>
  );
}
