"use client";

import { wholeAchievementHours } from "../leaderboardValue";
import { Doughnut } from "react-chartjs-2";
import {
  Chart as ChartJS,
  ArcElement,
  Tooltip,
  Legend,
  type Chart,
} from "chart.js";
import { useTranslation } from "react-i18next";
import {} from "react";

ChartJS.register(ArcElement, Tooltip, Legend);

interface DoughnutChartProps {
  /*
   * All four are `number | undefined`: they come straight off
   * `GET /statistics/`, where `grand_total_hours` is `(int)` and the other
   * three are plain counts — and they are `undefined` until the fetch
   * resolves. `totalVolunteerHours` was declared `string`, which is why the
   * guard below defaulted it to the *string* `"0"`; the value reaching it has
   * always been a number.
   */
  totalVolunteerHours?: number;
  volOppCompleted?: number;
  learnserveOppCompleted?: number;
  reliefTrips?: number;
}

export default function DonutChart({
  totalVolunteerHours,
  volOppCompleted,
  learnserveOppCompleted,
  reliefTrips,
}: DoughnutChartProps) {
  const safeVolOppCompleted = volOppCompleted ?? 0;
  const safeLearnserveOppCompleted = learnserveOppCompleted ?? 0;
  const safeReliefTrips = reliefTrips ?? 0;
  const safeTotalVolunteerHours = totalVolunteerHours ?? 0;
  const { t, i18n } = useTranslation();
  const isRTL = i18n.language === "ar" || i18n.dir() === "rtl";
  const fontFamily = "'Cairo', sans-serif";
  const total =
    safeVolOppCompleted + safeLearnserveOppCompleted + safeReliefTrips;

  const data = {
    // Same colours as the counters beside the chart (client, 2026-10-19):
    // volunteering #5271FF, development #70B4C2, outside-Kuwait lime. The
    // labels are what the hover tooltip names each slice.
    labels: [
      t("ACHIEVEMENTS.VOL_OPP_COMPLETED"),
      t("ACHIEVEMENTS.LEARN_SERVE_COMPLETED"),
      t("ACHIEVEMENTS.RELIEF_TRIP"),
    ],
    datasets: [
      {
        data: [
          safeVolOppCompleted,
          safeLearnserveOppCompleted,
          safeReliefTrips,
        ],
        backgroundColor: ["#5271FF", "#70B4C2", "#D9EF61"],
        borderColor: "#fff",
        hoverBorderColor: "#C8C8C8",
        borderWidth: 7,
        cutout: "60%",
      },
    ],
  };

  /**
   * Hovering a slice names it and gives its count and share — "فرص التطوع
   * المكتملة: 74 (80%)". Rebuilt with the language so the tooltip reads RTL in
   * Arabic; the chart remounts on a language change anyway (`chartKey`).
   */
  const options = {
    rotation: 80,
    circumference: 360,
    plugins: {
      legend: { display: false },
      tooltip: {
        enabled: true,
        rtl: isRTL,
        textDirection: isRTL ? "rtl" : "ltr",
        displayColors: true,
        boxPadding: 6,
        padding: 12,
        backgroundColor: "#29246D",
        titleFont: { family: fontFamily, size: 14, weight: 600 as const },
        bodyFont: { family: fontFamily, size: 14 },
        callbacks: {
          title: () => "",
          label: (context: { label?: string; raw: unknown }) => {
            const value = Number(context.raw) || 0;
            const share = total > 0 ? Math.round((value / total) * 100) : 0;
            return ` ${context.label}: ${value.toLocaleString("en-US")} (${share}%)`;
          },
        },
      },
    },
  };

  const centerTextPlugin = {
    id: "centerText",
    /* `Chart` from chart.js: the plugin reads the canvas box and `ctx`, both
       of which are on the real type. */
    beforeDraw: (chart: Chart) => {
      const { width, height } = chart;
      const ctx = chart.ctx;
      ctx.restore();

      /* `String(...)` because `fillText` takes a string and the value is a
         number — it was being handed a number and coerced implicitly. */
      const text1 = wholeAchievementHours(safeTotalVolunteerHours);
      const text2 = t("COMMON.VOLUNTEER.HOUR");

      ctx.textAlign = isRTL ? "right" : "left";
      ctx.textBaseline = "middle";
      ctx.fillStyle = "#000";

      ctx.font = `700 28px ${fontFamily}`;
      const text1Width = ctx.measureText(text1).width;
      const text1X = isRTL
        ? width / 2 + text1Width / 2
        : (width - text1Width) / 2;
      const text1Y = height / 2 - 12;
      ctx.fillText(text1, text1X, text1Y);

      ctx.font = `600 14px ${fontFamily}`;
      const text2Width = ctx.measureText(text2).width;
      const paddingTop = 4;
      const text2X = isRTL
        ? width / 2 + text2Width / 2
        : (width - text2Width) / 2;
      const text2Y = text1Y + 30 + paddingTop;

      ctx.fillText(text2, text2X, text2Y);
      ctx.save();
    },
  };

  return (
    <div className="relative w-[220px] md:w-[250px] lg:w-[260px] max-w-full mx-auto">
      <Doughnut
        /*
         * The things that must remount the chart, used directly as the key.
         *
         * This was a counter bumped from an effect that also subscribed to
         * i18n's `languageChanged` by hand. The subscription was redundant:
         * `useTranslation()` above already re-renders this component on a
         * language change, so `i18n.language` is reactive here.
         */
        key={`${i18n.language}-${safeTotalVolunteerHours}`}
        className="!w-full !h-auto"
        data={data}
        options={options}
        plugins={[centerTextPlugin]}
      />
    </div>
  );
}
