"use client";

import * as React from "react";
import { PieChart as PieChartIcon } from "lucide-react";
import { Cell, Pie, PieChart } from "recharts";

import { Card, CardContent } from "@/components/ui/card";
import { ChartContainer, ChartTooltip, ChartTooltipContent, type ChartConfig } from "@/components/ui/chart";
import { Skeleton } from "@/components/ui/skeleton";
import { buildPositivePieSlices, pieGeometryForSliceCount } from "@/lib/chart/positive-pie-slices";
import { cn } from "@/lib/utils";

import { resolveAssetClassColor } from "@/lib/chart/asset-class-colors";

import type { AssetAllocationSummaryRow } from "../../_lib/use-asset-allocation-summary";
import { formatUsdCompact } from "./utils";

function allocationTooltipContent(name: string, value: number, reportingCurrency: string, pct: number | null) {
  return (
    <div className="flex min-w-0 flex-col gap-0.5">
      <span className="max-w-[220px] break-words text-foreground">{name}</span>
      <span className="font-medium tabular-nums text-foreground/80">
        {formatUsdCompact(value)} {reportingCurrency}
        {pct != null ? ` (${pct.toFixed(1)}%)` : ""}
      </span>
    </div>
  );
}

export function AssetAllocationSummaryCard({
  rows,
  grandTotal,
  reportingCurrency,
  isLoading,
  errorMessage,
}: {
  rows: AssetAllocationSummaryRow[];
  grandTotal: number;
  reportingCurrency: string;
  isLoading: boolean;
  errorMessage: string | null;
}) {
  const slices = React.useMemo(
    () =>
      buildPositivePieSlices(
        rows.map((row, index) => ({
          name: row.assetClass,
          value: row.valueUsd,
          fill: resolveAssetClassColor(row.assetClass, index),
        })),
      ).map((slice) => ({
        name: slice.name,
        value: slice.value,
        fill: slice.fill ?? resolveAssetClassColor(slice.name),
      })),
    [rows],
  );

  const pieConfig = React.useMemo(() => {
    const config: ChartConfig = {};
    slices.forEach((s) => {
      config[s.name] = { label: s.name, color: s.fill };
    });
    return config;
  }, [slices]);

  const { paddingAngle, cornerRadius } = pieGeometryForSliceCount(slices.length);

  const chartTotal = React.useMemo(
    () => slices.reduce((sum, slice) => sum + slice.value, 0),
    [slices],
  );

  return (
    <Card className="gap-0 overflow-hidden border-border/80 py-0 shadow-sm transition-shadow hover:shadow-md">
      <div className="flex items-center gap-2.5 border-b bg-muted/20 px-4 py-3.5">
        <div className="flex size-9 shrink-0 items-center justify-center rounded-xl border bg-background/80">
          <PieChartIcon className="size-4 text-muted-foreground" />
        </div>
        <div className="min-w-0">
          <p className="font-semibold text-[11px] uppercase tracking-[0.14em]">Asset allocation</p>
          <p className="mt-0.5 text-muted-foreground text-xs">
            Positive holdings · {reportingCurrency}
          </p>
        </div>
      </div>
      <CardContent className="flex flex-col gap-3 p-4">
        {isLoading && rows.length === 0 ? (
          <div className="flex flex-col items-center gap-4 py-6">
            <Skeleton className="size-[200px] rounded-full" />
            <Skeleton className="h-4 w-3/4" />
            <Skeleton className="h-4 w-2/3" />
          </div>
        ) : errorMessage ? (
          <p className="py-16 text-center text-destructive text-sm">{errorMessage}</p>
        ) : slices.length === 0 ? (
          <p className="py-16 text-center text-muted-foreground text-sm">No allocation data available.</p>
        ) : (
          <>
            <div className="relative mx-auto h-[260px] w-full max-w-[300px]">
              <ChartContainer config={pieConfig} className="mx-auto aspect-square h-[260px] w-full max-w-[300px]">
                <PieChart>
                  <ChartTooltip
                    content={
                      <ChartTooltipContent
                        hideLabel
                        nameKey="name"
                        formatter={(value, _name, item) => {
                          const sliceValue = Number(value);
                          const pct = chartTotal > 0 ? (sliceValue / chartTotal) * 100 : null;
                          return allocationTooltipContent(
                            String(item?.payload?.name ?? _name ?? ""),
                            sliceValue,
                            reportingCurrency,
                            pct,
                          );
                        }}
                      />
                    }
                  />
                  <Pie
                    data={slices}
                    dataKey="value"
                    nameKey="name"
                    innerRadius="58%"
                    outerRadius="88%"
                    paddingAngle={paddingAngle}
                    cornerRadius={cornerRadius}
                    stroke="hsl(var(--card))"
                    strokeWidth={2}
                    isAnimationActive={false}
                  >
                    {slices.map((slice) => (
                      <Cell key={slice.name} fill={slice.fill} className="outline-none" />
                    ))}
                  </Pie>
                </PieChart>
              </ChartContainer>
              <div className="pointer-events-none absolute inset-0 flex flex-col items-center justify-center">
                <p className="text-muted-foreground text-[10px] uppercase tracking-wide">Total</p>
                <p className="font-semibold text-lg tabular-nums tracking-tight">
                  {formatUsdCompact(chartTotal > 0 ? chartTotal : grandTotal)}
                </p>
                <p className="text-muted-foreground text-[10px]">{reportingCurrency}</p>
              </div>
            </div>

            <div className="mt-4 space-y-2.5 border-t pt-3">
              {rows.map((row, index) => {
                const basis = chartTotal > 0 ? chartTotal : grandTotal;
                const pct = basis > 0 ? Math.round((row.valueUsd / basis) * 1000) / 10 : 0;
                const fill = resolveAssetClassColor(row.assetClass, index);
                const negative = row.valueUsd < 0;
                return (
                  <div key={row.assetClass} className="space-y-1.5">
                    <div className="flex items-center justify-between gap-3 text-sm">
                      <span className="inline-flex min-w-0 items-center gap-2">
                        <span className="size-2.5 shrink-0 rounded-sm" style={{ background: fill }} />
                        <span className="truncate font-medium">{row.assetClass}</span>
                      </span>
                      <div
                        className={cn(
                          "flex shrink-0 items-center gap-2 tabular-nums",
                          negative && "text-rose-600 dark:text-rose-400",
                        )}
                      >
                        <span className={cn("text-xs", !negative && "text-muted-foreground")}>{pct}%</span>
                        <span className="font-medium">{formatUsdCompact(row.valueUsd)}</span>
                      </div>
                    </div>
                    <div className="h-1.5 overflow-hidden rounded-full bg-muted">
                      <div
                        className="h-full rounded-full transition-all"
                        style={{
                          width: `${Math.min(Math.max(pct, 0), 100)}%`,
                          background: fill,
                        }}
                      />
                    </div>
                  </div>
                );
              })}
              <div
                className={cn(
                  "mt-1 flex items-center justify-between rounded-lg bg-muted/40 px-2.5 py-2 text-sm font-semibold",
                )}
              >
                <span>Total</span>
                <span className="tabular-nums">{formatUsdCompact(grandTotal)}</span>
              </div>
            </div>
          </>
        )}
      </CardContent>
    </Card>
  );
}
