"use client";

import * as React from "react";
import { Cell, LabelList, Pie, PieChart } from "recharts";

import { ChartContainer, ChartTooltip, ChartTooltipContent } from "@/components/ui/chart";
import { pieGeometryForSliceCount, isPositivePieValue } from "@/lib/chart/positive-pie-slices";
import { cn } from "@/lib/utils";

import { formatAllocationAmount, formatAllocationPct } from "./utils";

export type PieSlice = {
  /** Stable unique id for React keys (bank id / asset class key). */
  id: string;
  name: string;
  value: number;
  amount: number;
  color: string;
};

const config = { value: { label: "Share" } };

export function AssetAllocationMiniPie({
  slices,
  compact = false,
}: {
  slices: PieSlice[];
  compact?: boolean;
}) {
  const [mounted, setMounted] = React.useState(false);
  React.useEffect(() => {
    setMounted(true);
  }, []);

  const chartSlices = React.useMemo(
    () => slices.filter((slice) => isPositivePieValue(slice.value) || isPositivePieValue(slice.amount)),
    [slices],
  );

  if (chartSlices.length === 0) {
    return (
      <div
        className={cn(
          "flex flex-col items-center justify-center gap-2 px-2 py-3",
          compact ? "min-h-[160px]" : "min-h-[180px]",
        )}
        aria-label="No allocation to chart"
      >
        <div
          className={cn(
            "rounded-full border-2 border-dashed border-border/50 bg-muted/10",
            "h-[min(120px,18vw)] w-[min(120px,18vw)] max-h-[140px] max-w-[140px]",
          )}
        />
      </div>
    );
  }

  const labeledSlices = chartSlices.map((slice) => ({
    ...slice,
    chartLabel: `${slice.name} ${formatAllocationPct(slice.value)}`.trim(),
  }));
  const { paddingAngle, cornerRadius } = pieGeometryForSliceCount(labeledSlices.length);
  const topSlices = labeledSlices.slice(0, compact ? 5 : 8);
  const rest = labeledSlices.length - topSlices.length;

  return (
    <div className="flex flex-col items-center gap-2 px-2 py-3">
      {mounted ? (
        <ChartContainer
          config={config}
          className="mx-auto aspect-square h-[min(150px,20vw)] w-[min(150px,20vw)] max-h-[160px] max-w-[160px]"
        >
          <PieChart margin={{ top: 4, right: 4, bottom: 4, left: 4 }}>
            <ChartTooltip
              cursor={false}
              content={
                <ChartTooltipContent
                  hideLabel
                  formatter={(_value, _name, item) => {
                    const payload = item.payload as PieSlice & { chartLabel?: string };
                    return (
                      <div className="space-y-0.5">
                        <p className="font-medium">{payload.name}</p>
                        <p className="text-muted-foreground text-xs tabular-nums">
                          {formatAllocationPct(payload.value)} · {formatAllocationAmount(payload.amount)}
                        </p>
                      </div>
                    );
                  }}
                />
              }
            />
            <Pie
              data={labeledSlices}
              dataKey="value"
              nameKey="name"
              innerRadius="52%"
              outerRadius="82%"
              paddingAngle={paddingAngle}
              cornerRadius={cornerRadius}
              stroke="hsl(var(--background))"
              strokeWidth={2}
              isAnimationActive={false}
            >
              {labeledSlices.map((slice) => (
                <Cell
                  key={slice.id}
                  fill={slice.color}
                  className="outline-none transition-opacity hover:opacity-90"
                />
              ))}
              {!compact ? (
                <LabelList
                  dataKey="chartLabel"
                  position="outside"
                  className="fill-foreground text-[8px]"
                  stroke="none"
                />
              ) : null}
            </Pie>
          </PieChart>
        </ChartContainer>
      ) : (
        <div
          className={cn(
            "mx-auto rounded-full border border-dashed border-border/50 bg-muted/20",
            "h-[min(150px,20vw)] w-[min(150px,20vw)] max-h-[160px] max-w-[160px]",
          )}
          aria-hidden
        />
      )}

      <ul className="w-full min-w-[150px] max-w-[220px] space-y-1">
        {topSlices.map((slice) => (
          <li key={slice.id} className="flex items-center justify-between gap-2 text-[10px] leading-tight">
            <span className="flex min-w-0 items-center gap-1.5">
              <span
                className="size-2 shrink-0 rounded-full ring-1 ring-background"
                style={{ backgroundColor: slice.color }}
              />
              <span className="truncate text-muted-foreground" title={slice.name}>
                {slice.name}
              </span>
            </span>
            <span className="shrink-0 font-medium text-foreground tabular-nums">
              {formatAllocationPct(slice.value)}
            </span>
          </li>
        ))}
        {rest > 0 ? (
          <li className="text-center text-[10px] text-muted-foreground">+{rest} more</li>
        ) : null}
      </ul>
    </div>
  );
}
