"use client";
import ReactApexChart from "react-apexcharts";
import type { ApexOptions } from "apexcharts";
import { useTheme } from "next-themes";
import type { ChartProps } from "./chart";
import { formatEnergyKwh } from "@/lib/format";
export default function RenderChart({
  type,
  series,
  categories,
  labels,
  height = 315,
  unit = "",
  appearance = "default",
  showLegend = true,
  showDonutTotal = false,
}: ChartProps) {
  const { resolvedTheme } = useTheme();
  const styles = getComputedStyle(document.documentElement);
  const token = (name: string) => styles.getPropertyValue(name).trim();
  const compact = appearance === "compact";
  const countFormatter = new Intl.NumberFormat("en-US");
  const options: ApexOptions = {
    chart: {
      fontFamily: "inherit",
      toolbar: { show: false },
      stacked: type === "bar",
      animations: {
        enabled: !window.matchMedia("(prefers-reduced-motion: reduce)").matches,
      },
      background: "transparent",
    },
    colors:
      type === "area"
        ? [token("--chart-4")]
        : type === "donut"
          ? (labels ?? []).map((label) => {
              const colorToken = {
                Available: "--success",
                Charging: "--info",
                Preparing: "--warning",
                Finishing: "--chart-4",
                Fault: "--destructive",
                Faulted: "--destructive",
                Offline: "--muted-foreground",
              }[label] ?? "--chart-1";
              return token(colorToken);
            })
          : [token("--chart-1"), token("--chart-2"), token("--chart-3")],
    theme: { mode: resolvedTheme === "dark" ? "dark" : "light" },
    plotOptions: {
      bar: {
        columnWidth: "40%",
        borderRadius: 10,
        borderRadiusApplication: "end",
        borderRadiusWhenStacked: "last",
      },
      pie: {
        donut: {
          size: "65%",
          labels: {
            show: true,
            name: { show: showDonutTotal },
            value: { show: true, offsetY: 0, color: token("--foreground") },
            total: showDonutTotal
              ? {
                  show: true,
                  showAlways: true,
                  label: "Total",
                  color: token("--foreground"),
                  formatter: (chart) =>
                    countFormatter.format(
                      chart.globals.seriesTotals.reduce(
                        (total: number, value: number) => total + value,
                        0,
                      ),
                    ),
                }
              : undefined,
          },
        },
      },
    },
    dataLabels: { enabled: false },
    stroke: { width: type === "area" ? 2 : 0, curve: "smooth" },
    fill: {
      type: type === "area" ? "gradient" : "solid",
      gradient: { opacityFrom: 0.55, opacityTo: compact ? 0 : 0.04 },
    },
    grid: compact
      ? { show: false }
      : { borderColor: token("--border"), strokeDashArray: 3 },
    xaxis: {
      categories: categories ?? [],
      axisBorder: { show: false },
      axisTicks: { show: false },
      labels: {
        show: !compact,
        style: { colors: token("--muted-foreground"), fontSize: "12px" },
      },
    },
    yaxis: {
      labels: {
        show: !compact,
        formatter: (value) =>
          `${value >= 1000000 ? `${(value / 1000000).toFixed(1)}M` : unit === "kWh" ? value.toLocaleString("en-US", { maximumFractionDigits: 6 }) : value.toFixed(0)}${unit ? ` ${unit}` : ""}`,
        style: { colors: token("--muted-foreground"), fontSize: "12px" },
      },
    },
    ...(compact ? { markers: { size: 0, hover: { size: 6 } } } : {}),
    labels: labels ?? [],
    legend: {
      show: type !== "area" && showLegend,
      position: type === "bar" ? "top" : "bottom",
      horizontalAlign: type === "bar" ? "left" : "center",
      fontSize: "13px",
      labels: { colors: token("--foreground") },
    },
    tooltip: {
      theme: resolvedTheme === "dark" ? "dark" : "light",
      y: {
        formatter: (value) =>
          unit === "kWh"
            ? `${formatEnergyKwh(value)} kWh`
            : compact
            ? `${value.toLocaleString("id-ID", { maximumFractionDigits: 0 })}${unit ? ` ${unit}` : ""}`
            : `${value.toFixed(2)} ${unit}`,
      },
    },
  };
  return (
    <ReactApexChart
      options={options}
      series={series}
      type={type}
      height={height}
    />
  );
}
