"use client";

import * as React from "react";
import {
  Chart as ChartJS,
  ArcElement,
  Tooltip,
  type ChartData,
  type ChartOptions,
} from "chart.js";
import { Doughnut } from "react-chartjs-2";

import { Badge } from "@/components/ui/badge";
import { cn } from "@/lib/utils";
import { formatPct } from "@/components/sales-targets/sales-targets-helpers";

export { SalesTargetProgressBar } from "@/components/sales-targets/sales-target-progress-bar";

ChartJS.register(ArcElement, Tooltip);

const ACCENT = "rgb(108, 99, 255)";
const SUCCESS = "rgb(16, 185, 129)";
const TRACK = "rgba(148, 163, 184, 0.35)";

type SalesTargetProgressChartProps = {
  pct: number | null | undefined;
  size?: "sm" | "md";
  className?: string;
  showLabel?: boolean;
};

export function SalesTargetProgressChart({
  pct,
  size = "md",
  className,
  showLabel = true,
}: SalesTargetProgressChartProps) {
  const hasPct = pct != null && !Number.isNaN(pct);
  const value = hasPct ? Math.min(100, Math.max(0, pct)) : 0;
  const complete = hasPct && value >= 100;
  const chartSize = size === "sm" ? 72 : 100;

  const data = React.useMemo<ChartData<"doughnut">>(
    () => ({
      labels: ["Attained", "Remaining"],
      datasets: [
        {
          data: hasPct
            ? value >= 100
              ? [100, 0]
              : [value, Math.max(0, 100 - value)]
            : [0, 100],
          backgroundColor: [complete ? SUCCESS : ACCENT, TRACK],
          borderWidth: 0,
          hoverOffset: 0,
        },
      ],
    }),
    [hasPct, value, complete],
  );

  const options = React.useMemo<ChartOptions<"doughnut">>(
    () => ({
      responsive: true,
      maintainAspectRatio: true,
      animation: { duration: 400 },
      cutout: "72%",
      plugins: {
        legend: { display: false },
        tooltip: {
          enabled: hasPct,
          callbacks: {
            label: (ctx) => {
              const v = ctx.raw as number;
              return `${ctx.label}: ${v.toFixed(1)}%`;
            },
          },
        },
      },
    }),
    [hasPct],
  );

  return (
    <div
      className={cn(
        "flex items-center gap-3",
        size === "sm" ? "flex-col gap-2" : "flex-row",
        className,
      )}
    >
      <div
        className="relative shrink-0"
        style={{ width: chartSize, height: chartSize }}
        aria-hidden={!hasPct}
      >
        <Doughnut data={data} options={options} />
        {showLabel && (
          <div className="pointer-events-none absolute inset-0 flex flex-col items-center justify-center">
            <span
              className={cn(
                "font-extrabold tabular-nums font-['Lexend'] leading-none",
                size === "sm" ? "text-[11px]" : "text-sm",
                complete && "text-emerald-600 dark:text-emerald-400",
              )}
            >
              {formatPct(pct)}
            </span>
          </div>
        )}
      </div>
      {size !== "sm" && (
        <div className="min-w-0 flex-1">
          <p className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground">
            Progress
          </p>
          {complete && (
            <Badge
              variant="outline"
              className="mt-1.5 border-emerald-500/40 bg-emerald-500/10 text-[10px] text-emerald-700 dark:text-emerald-300"
            >
              Target met
            </Badge>
          )}
          {!hasPct && (
            <p className="mt-1 text-xs text-muted-foreground">No target set</p>
          )}
          {hasPct && !complete && (
            <p className="mt-1 text-xs text-muted-foreground">
              {pct > 0 && pct < 0.1 ? "< 0.1" : value.toFixed(1)}% of monthly target
            </p>
          )}
        </div>
      )}
    </div>
  );
}
