"use client";
import dynamic from "next/dynamic";
import { useTheme } from "next-themes";
import { Panel } from "./page";
const Chart = dynamic(() => import("react-apexcharts"), {
  ssr: false,
  loading: () => (
    <div className="flex h-64 items-center justify-center text-muted-foreground">
      Loading chart…
    </div>
  ),
});
export type ChartSeries = { name: string; data: number[] }[];
export function ChartPanel({
  title,
  type = "bar",
  series,
  categories = [],
  height = 300,
}: {
  title: string;
  type?: "area" | "bar" | "donut" | "line";
  series: ChartSeries;
  categories?: string[];
  height?: number;
}) {
  const { resolvedTheme } = useTheme();
  return (
    <Panel title={title}>
      <div
        className="chart-container overflow-hidden p-4"
        role="img"
        aria-label={`${title}: ${series.map((s) => `${s.name}: ${s.data.join(", ")}`).join("; ")}`}
      >
        <Chart
          type={type}
          height={height}
          series={type === "donut" ? (series[0]?.data ?? []) : series}
          options={{
            chart: {
              toolbar: { show: false },
              fontFamily: "inherit",
              background: "transparent",
              foreColor: "var(--muted-foreground)",
            },
            theme: { mode: resolvedTheme === "dark" ? "dark" : "light" },
            colors: [
              "var(--chart-1)",
              "var(--chart-2)",
              "var(--chart-3)",
              "var(--chart-4)",
            ],
            labels: categories,
            xaxis: { categories },
            dataLabels: { enabled: false },
            stroke: {
              curve: "smooth",
              width: type === "line" || type === "area" ? 2 : 0,
            },
            legend: { position: "bottom" },
            grid: { borderColor: "var(--border)" },
            plotOptions: { bar: { borderRadius: 4, columnWidth: "45%" } },
            tooltip: { theme: resolvedTheme === "dark" ? "dark" : "light" },
          }}
        />
      </div>
    </Panel>
  );
}
