"use client";

import Box from "@mui/material/Box";
import { alpha, useTheme } from "@mui/material/styles";
import { Cell, Pie, PieChart, ResponsiveContainer } from "recharts";

import { useDashboardChartReady } from "@/features/ministry/dashboard/components/charts/use-dashboard-chart-ready";
import type { DonutChartItem } from "@/features/ministry/dashboard/dashboard-data";

type DonutLabelProps = {
  index?: number;
  cx?: number | string;
  cy?: number | string;
  midAngle?: number;
  innerRadius?: number | string;
  outerRadius?: number | string;
};

type DashboardDonutChartProps = {
  centerLabel: string;
  centerValue: string | number;
  data: DonutChartItem[];
  height?: number;
  centerFill?: string;
};

export function DashboardDonutChart({
  centerLabel,
  centerValue,
  data,
  height = 220,
  centerFill,
}: DashboardDonutChartProps) {
  const { containerRef, chartReady } = useDashboardChartReady();
  const theme = useTheme();
  const total = data.reduce((sum, item) => sum + item.value, 0);

  const donutInnerRadius = 54;
  const donutOuterRadius = 92;
  const centerCircleRadius = 54;
  const resolvedCenterFill =
    centerFill ??
    (theme.palette.mode === "dark"
      ? alpha(theme.palette.primary.main, 0.28)
      : "#b9dff7");

  const getLabelColor = (sliceColor: string, isSmallSlice: boolean) => {
    if (isSmallSlice) return "#ffffff";

    const color = sliceColor.replace("#", "");
    if (color.length !== 6) return "#ffffff";

    const r = parseInt(color.slice(0, 2), 16);
    const g = parseInt(color.slice(2, 4), 16);
    const b = parseInt(color.slice(4, 6), 16);
    const brightness = (r * 299 + g * 587 + b * 114) / 1000;

    return brightness > 170 ? theme.palette.text.primary : "#ffffff";
  };

  return (
    <Box ref={containerRef} sx={{ height, width: "100%" }}>
      {chartReady ? (
        <ResponsiveContainer width="100%" height="100%" minWidth={0}>
          <PieChart>
            <Pie
              data={data}
              dataKey="value"
              nameKey="label"
              cx="50%"
              cy="56%"
              innerRadius={donutInnerRadius}
              outerRadius={donutOuterRadius}
              startAngle={189}
              endAngle={-171}
              stroke="none"
              labelLine={false}
              isAnimationActive
              animationDuration={850}
              animationBegin={50}
              label={({
                index,
                cx,
                cy,
                midAngle,
                innerRadius,
                outerRadius,
              }: DonutLabelProps) => {
                if (
                  index == null ||
                  cx == null ||
                  cy == null ||
                  midAngle == null ||
                  innerRadius == null ||
                  outerRadius == null
                ) {
                  return null;
                }

                const segment = data[index];
                if (!segment) return null;

                const percent = total === 0 ? 0 : segment.value / total;
                const isSmallSlice = percent <= 0.12;
                const angleInRadians = (-Number(midAngle) * Math.PI) / 180;
                const labelRadius =
                  Number(innerRadius) +
                  (Number(outerRadius) - Number(innerRadius)) *
                    (isSmallSlice ? 0.42 : 0.55);

                const x = Number(cx) + labelRadius * Math.cos(angleInRadians);
                const y = Number(cy) + labelRadius * Math.sin(angleInRadians);

                const labelText =
                  segment.labelText ??
                  `${Math.round(total === 0 ? 0 : (segment.value / total) * 100)}%`;

                return (
                  <text
                    x={x}
                    y={y}
                    fill={getLabelColor(segment.color, isSmallSlice)}
                    textAnchor="middle"
                    dominantBaseline="middle"
                    fontSize={isSmallSlice ? 10 : 11}
                    fontWeight={700}
                    style={{ pointerEvents: "none" }}
                  >
                    {labelText}
                  </text>
                );
              }}
            >
              {data.map((segment) => (
                <Cell key={segment.label} fill={segment.color} stroke="none" />
              ))}
            </Pie>

            <circle
              cx="50%"
              cy="56%"
              r={centerCircleRadius}
              fill={resolvedCenterFill}
              stroke="none"
            />

            <text
              x="50%"
              y="50%"
              textAnchor="middle"
              dominantBaseline="middle"
              fill={theme.palette.text.primary}
              fontSize="11"
              fontWeight="500"
            >
              {centerLabel}
            </text>

            <text
              x="50%"
              y="61%"
              textAnchor="middle"
              dominantBaseline="middle"
              fill={theme.palette.text.primary}
              fontSize="22"
              fontWeight="700"
            >
              {centerValue}
            </text>
          </PieChart>
        </ResponsiveContainer>
      ) : null}
    </Box>
  );
}