"use client";

import { useMemo } from "react";

import { usePipeline } from "@/lib/analytics-api";

import { ChartShell } from "./ChartShell";

export function PipelineChart() {
  const { data, isLoading } = usePipeline();

  const option = useMemo(() => {
    const rows = data ?? [];
    return {
      tooltip: {
        trigger: "axis",
        axisPointer: { type: "shadow" },
        valueFormatter: (v: number) => `${v}%`,
      },
      legend: { data: ["sold", "unsold", "не открыто"] },
      grid: { left: 48, right: 32, top: 40, bottom: 28 },
      xAxis: { type: "category", data: rows.map((r) => r.year) },
      yAxis: { type: "value", max: 100, axisLabel: { formatter: "{value}%" } },
      series: [
        {
          name: "sold",
          type: "bar",
          stack: "p",
          data: rows.map((r) => r.sold_perc),
          itemStyle: { color: "#0a7a3a" },
        },
        {
          name: "unsold",
          type: "bar",
          stack: "p",
          data: rows.map((r) => r.unsold_perc),
          itemStyle: { color: "#f59e0b" },
        },
        {
          name: "не открыто",
          type: "bar",
          stack: "p",
          data: rows.map((r) => r.unopened_perc),
          itemStyle: { color: "#b3261e" },
        },
      ],
    };
  }, [data]);

  return <ChartShell option={option} loading={isLoading} height={320} />;
}
