"use client";

import { useMemo } from "react";

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

import { ChartShell } from "./ChartShell";

export function ObjectSaleChart({ objId }: { objId: number | string }) {
  const { data, isLoading } = useObjectSaleGraph(objId);

  const option = useMemo(() => {
    const points = data ?? [];
    if (points.length === 0) {
      return {
        title: {
          text: "Нет данных по продажам",
          left: "center",
          top: "middle",
          textStyle: { color: "#9ca3af", fontSize: 13, fontWeight: 400 },
        },
        xAxis: { show: false },
        yAxis: { show: false },
      };
    }
    const byType: Record<
      string,
      {
        months: string[];
        realised: number[];
        contracted: number[];
        price: (number | null)[];
      }
    > = {};
    for (const p of points) {
      const t = p.type;
      if (!byType[t])
        byType[t] = { months: [], realised: [], contracted: [], price: [] };
      byType[t].months.push((p.report_month ?? "").slice(0, 7));
      byType[t].realised.push(p.realised ?? 0);
      byType[t].contracted.push(p.contracted ?? 0);
      byType[t].price.push(p.price_avg);
    }
    const months = Object.values(byType)[0]?.months ?? [];
    const series = Object.entries(byType).flatMap(([type, d]) => [
      {
        name: `${type} · реализовано`,
        type: "bar",
        stack: type,
        data: d.realised,
        itemStyle: { color: type === "apartments" ? "#1d4ed8" : "#9333ea" },
      },
      {
        name: `${type} · цена ₽/м²`,
        type: "line",
        yAxisIndex: 1,
        smooth: true,
        symbol: "circle",
        data: d.price.map((v) => (v ? Math.round(v / 1000) : null)),
        lineStyle: { color: type === "apartments" ? "#0a7a3a" : "#c2410c" },
        itemStyle: { color: type === "apartments" ? "#0a7a3a" : "#c2410c" },
        connectNulls: true,
      },
    ]);
    return {
      tooltip: { trigger: "axis", axisPointer: { type: "cross" } },
      legend: {},
      grid: { left: 56, right: 64, top: 40, bottom: 36 },
      xAxis: { type: "category", data: months },
      yAxis: [
        { type: "value", name: "шт", position: "left" },
        { type: "value", name: "тыс ₽/м²", position: "right" },
      ],
      series,
    };
  }, [data]);

  return (
    <ChartShell option={option} loading={isLoading} height={300} notMerge />
  );
}
