"use client";

import { useMemo } from "react";

import type { RecommendBucket } from "@/types/analytics";

import { ChartShell } from "./ChartShell";

interface DerivedBucket extends RecommendBucket {
  effective_share_pct: number;
  effective_units: number | null;
  effective_revenue_rub: number | null;
}

interface Props {
  rows: DerivedBucket[];
  priceFactor: number;
  elasticity: number;
}

const HORIZON_MONTHS = 36;

/**
 * Cumulative-sold curve over 36 months. Per bucket: linear sellout up to
 * months_to_sellout, then 100%. Aggregate = unit-weighted.
 *
 * Marker line at 24 months — that's the liquidity-score reference.
 */
export function RecommendLiquidityChart({
  rows,
  priceFactor,
  elasticity,
}: Props) {
  const option = useMemo(() => {
    const pfPow = priceFactor > 0 ? priceFactor ** elasticity : 1;
    const totalUnits = rows.reduce((a, r) => a + (r.effective_units ?? 0), 0);
    if (totalUnits === 0) {
      return {
        title: {
          text: "Укажи площадь — посчитаем сколько и когда продастся",
          left: "center",
          top: "middle",
          textStyle: { color: "#9ca3af", fontSize: 13, fontWeight: 400 },
        },
        xAxis: { show: false },
        yAxis: { show: false },
      };
    }
    const xs = Array.from({ length: HORIZON_MONTHS + 1 }, (_, m) => m);
    const cumulative = xs.map((m) => {
      let sold = 0;
      for (const r of rows) {
        const u = r.effective_units ?? 0;
        if (u <= 0) continue;
        const v = (r.velocity_per_month ?? 0) * pfPow;
        if (v <= 0) continue;
        const monthsTotal = u / v;
        const f = Math.min(1, m / monthsTotal);
        sold += f * u;
      }
      return Math.round((sold / totalUnits) * 1000) / 10; // %
    });

    return {
      tooltip: {
        trigger: "axis",
        valueFormatter: (v: unknown) =>
          typeof v === "number" ? `${v.toFixed(1)}%` : "—",
      },
      grid: { left: 56, right: 32, top: 24, bottom: 36 },
      xAxis: {
        type: "category",
        data: xs.map((m) => `${m}`),
        axisLabel: { formatter: "{value} мес" },
      },
      yAxis: {
        type: "value",
        max: 100,
        axisLabel: { formatter: "{value}%" },
      },
      series: [
        {
          name: "Кумулятивные продажи",
          type: "line",
          smooth: true,
          areaStyle: { color: "rgba(29, 78, 216, 0.15)" },
          lineStyle: { color: "#1d4ed8", width: 2 },
          symbol: "none",
          data: cumulative,
          markLine: {
            symbol: "none",
            label: { formatter: "24 мес — горизонт ликвидности" },
            data: [
              {
                xAxis: "24",
                lineStyle: { color: "#9a6700", type: "dashed" },
              },
            ],
          },
        },
      ],
    };
  }, [rows, priceFactor, elasticity]);

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