"use client";

import { useMemo } from "react";

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

import { ChartShell } from "./ChartShell";

export function DistrictTreemap() {
  const { data, isLoading } = useDistricts();

  const option = useMemo(() => {
    const rows = data ?? [];
    return {
      tooltip: {
        formatter: (info: {
          data: { name: string; value: number; flat_count: number };
        }) =>
          `<b>${info.data.name}</b><br/>ЖК: ${info.data.value}<br/>квартир: ${info.data.flat_count?.toLocaleString("ru")}`,
      },
      series: [
        {
          type: "treemap",
          roam: false,
          breadcrumb: { show: false },
          label: {
            show: true,
            formatter: "{b}\n{c} ЖК",
            color: "#fff",
            fontSize: 13,
          },
          itemStyle: { borderColor: "#fff", borderWidth: 2, gapWidth: 2 },
          levels: [
            {
              colorMappingBy: "value",
              color: ["#dbeafe", "#3b82f6", "#1d4ed8"],
            },
          ],
          data: rows.map((r) => ({
            name: r.district_name,
            value: r.zk_count ?? 0,
            flat_count: r.flat_count ?? 0,
          })),
        },
      ],
    };
  }, [data]);

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