"use client";

import { useMemo } from "react";

import { ChartShell } from "./ChartShell";

interface Props {
  bucketLabels: string[];
  revenuesRub: (number | null)[];
}

const COLORS = ["#94a3b8", "#1d4ed8", "#0891b2", "#0a7a3a", "#c2410c"];

export function RecommendRevenueChart({ bucketLabels, revenuesRub }: Props) {
  const option = useMemo(() => {
    const valuesMln = revenuesRub.map((v) =>
      v == null ? 0 : Math.round((v / 1_000_000) * 10) / 10,
    );
    const total = valuesMln.reduce((a, b) => a + b, 0);
    return {
      tooltip: {
        trigger: "axis",
        valueFormatter: (v: unknown) =>
          typeof v === "number" ? `${v.toFixed(1)} млн ₽` : "—",
      },
      grid: { left: 60, right: 32, top: 24, bottom: 32 },
      xAxis: { type: "value", axisLabel: { formatter: "{value} млн" } },
      yAxis: { type: "category", data: ["Выручка"] },
      series: bucketLabels.map((label, i) => ({
        name: label,
        type: "bar",
        stack: "rev",
        data: [valuesMln[i] ?? 0],
        itemStyle: { color: COLORS[i % COLORS.length] },
        emphasis: { focus: "series" },
        label: {
          show: total > 0 && (valuesMln[i] ?? 0) >= total * 0.05,
          formatter: (p: { value: number; seriesName: string }) =>
            `${p.seriesName}\n${p.value.toFixed(1)} млн`,
          color: "#fff",
          fontSize: 11,
        },
      })),
    };
  }, [bucketLabels, revenuesRub]);

  return <ChartShell option={option} height={120} notMerge />;
}
