"use client";

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

import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
  ChartContainer,
  ChartTooltip,
  ChartTooltipContent,
  type ChartConfig,
} from "@/components/ui/chart";
import { ErrorBanner } from "@/components/shared/error-banner";
import { formatAmount } from "@/lib/format/numbers";
import { buildPositivePieSlices, pieGeometryForSliceCount } from "@/lib/chart/positive-pie-slices";
import { CHART_FALLBACK_PALETTE } from "@/lib/chart/asset-class-colors";

import type {
  StructuredProductChartPoint,
  StructuredProductCharts,
} from "../../_lib/structured-product-types";

const chartConfig = { y: { label: "Value" } } satisfies ChartConfig;
const CHART_COLORS = CHART_FALLBACK_PALETTE;

function DonutCard({
  title,
  data,
  currency,
}: {
  title: string;
  data: StructuredProductChartPoint[];
  currency: string;
}) {
  const [expanded, setExpanded] = React.useState(false);
  const chartData = React.useMemo(
    () =>
      buildPositivePieSlices(
        data.map((item, index) => ({
          name: item.name,
          value: item.y,
          fill: CHART_COLORS[index % CHART_COLORS.length],
        })),
      ).map((slice, index) => ({
        name: slice.name,
        y: slice.value,
        pct: slice.pct,
        fill: slice.fill ?? CHART_COLORS[index % CHART_COLORS.length],
      })),
    [data],
  );
  const { paddingAngle, cornerRadius } = pieGeometryForSliceCount(chartData.length);
  const visible = expanded ? chartData : chartData.slice(0, 10);
  return (
    <Card className="overflow-hidden border-border/80 shadow-sm">
      <CardHeader className="border-b bg-muted/30 px-4 py-3">
        <CardTitle className="text-center font-semibold text-sm">{title}</CardTitle>
      </CardHeader>
      <CardContent className="flex flex-col items-center gap-3 p-4">
        {chartData.length ? (
          <>
            <ChartContainer
              config={chartConfig}
              className="mx-auto aspect-square h-[260px] w-full max-w-[300px]"
            >
              <PieChart>
                <ChartTooltip content={<ChartTooltipContent hideLabel />} />
                <Pie
                  data={chartData}
                  dataKey="y"
                  nameKey="name"
                  innerRadius={62}
                  outerRadius={92}
                  paddingAngle={paddingAngle}
                  cornerRadius={cornerRadius}
                  stroke="hsl(var(--card))"
                  strokeWidth={2}
                  isAnimationActive={false}
                >
                  {chartData.map((entry) => (
                    <Cell key={entry.name} fill={entry.fill} />
                  ))}
                </Pie>
              </PieChart>
            </ChartContainer>
            <ul className="w-full space-y-1 text-xs">
              {visible.map((item) => (
                <li
                  key={item.name}
                  className="grid grid-cols-[minmax(0,1fr)_auto] gap-2 rounded border px-2 py-1.5 tabular-nums"
                >
                  <span className="flex min-w-0 items-center gap-1.5">
                    <span
                      className="size-2 shrink-0 rounded-full"
                      style={{ backgroundColor: item.fill }}
                    />
                    <span className="truncate" title={item.name}>{item.name}</span>
                  </span>
                  <span className="text-right font-medium">
                    {currency}{" "}
                    {formatAmount(item.y, {
                      minimumFractionDigits: 2,
                      maximumFractionDigits: 2,
                    })}
                    <span className="ml-1 text-muted-foreground">
                      ({item.pct.toFixed(2)}%)
                    </span>
                  </span>
                </li>
              ))}
            </ul>
            {chartData.length > 10 ? (
              <button
                type="button"
                className="text-blue-600 text-xs"
                onClick={() => setExpanded((value) => !value)}
              >
                {expanded ? "Show less" : "Show more"}
              </button>
            ) : null}
          </>
        ) : (
          <p className="py-20 text-center text-muted-foreground text-sm">No chart data.</p>
        )}
      </CardContent>
    </Card>
  );
}

export function StructuredProductChartsPanel({
  charts,
  graphError,
  isGraphLoading,
}: {
  charts: StructuredProductCharts;
  graphError: string | null;
  isGraphLoading: boolean;
}) {
  return (
    <>
      <ErrorBanner message={graphError} />
      {isGraphLoading ? (
        <div className="flex min-h-72 items-center justify-center overflow-hidden rounded-xl border border-border/80 bg-card shadow-sm">
          <Loader2 className="size-6 animate-spin text-muted-foreground" />
        </div>
      ) : (
        <div className="grid gap-3 md:grid-cols-2 xl:grid-cols-4">
          <DonutCard
            title={`By Industry in ${charts.reportingCurrency}`}
            data={charts.industry}
            currency={charts.reportingCurrency}
          />
          <DonutCard
            title={`By Sector in ${charts.reportingCurrency}`}
            data={charts.sector}
            currency={charts.reportingCurrency}
          />
          <DonutCard
            title={`By Product Type in ${charts.reportingCurrency}`}
            data={charts.productType}
            currency={charts.reportingCurrency}
          />
          <DonutCard
            title={`By Issuer in ${charts.reportingCurrency}`}
            data={charts.issuer}
            currency={charts.reportingCurrency}
          />
        </div>
      )}
    </>
  );
}
