"use client";

import { useMemo } from "react";

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

import { ChartShell } from "./ChartShell";

export function PrinzipGapBar() {
  const { data, isLoading } = usePrinzipInsights();

  const option = useMemo(() => {
    const rows = data?.key_gaps ?? [];
    return {
      tooltip: {
        trigger: "axis",
        axisPointer: { type: "shadow" },
        formatter: (
          params: {
            axisValueLabel: string;
            marker: string;
            seriesName: string;
            value: number;
          }[],
        ) => {
          const label = params[0]?.axisValueLabel ?? "";
          const unit = rows.find((r) => r.label === label)?.unit ?? "";
          return [
            `<b>${label}</b>`,
            ...params.map(
              (p) => `${p.marker}${p.seriesName}: ${p.value}${unit}`,
            ),
          ].join("<br/>");
        },
      },
      legend: { data: ["PRINZIP", "Рынок Свердл", "Брусника", "Форум-групп"] },
      grid: { left: 120, right: 32, top: 40, bottom: 28 },
      xAxis: { type: "value" },
      yAxis: { type: "category", data: rows.map((r) => r.label) },
      series: [
        {
          name: "PRINZIP",
          type: "bar",
          data: rows.map((r) => r.prinzip),
          itemStyle: { color: "#1d4ed8" },
        },
        {
          name: "Рынок Свердл",
          type: "bar",
          data: rows.map((r) => r.market),
          itemStyle: { color: "#94a3b8" },
        },
        {
          name: "Брусника",
          type: "bar",
          data: rows.map((r) => r.brusnika),
          itemStyle: { color: "#0a7a3a" },
        },
        {
          name: "Форум-групп",
          type: "bar",
          data: rows.map((r) => r.forum),
          itemStyle: { color: "#c2410c" },
        },
      ],
    };
  }, [data]);

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