import { useMemo } from 'react';
import { RadialBarChart, RadialBar, PolarAngleAxis } from 'recharts';

function getCssVar(name: string): string {
  return getComputedStyle(document.documentElement).getPropertyValue(name).trim();
}

interface Props {
  label: string;
  value: number;
  max?: number;
  thresholds?: { warn: number; danger: number };
}

export function RiskGauge({
  label,
  value,
  max = 100,
  thresholds = { warn: 60, danger: 80 },
}: Props) {
  const colors = useMemo(() => ({
    border: getCssVar('--color-border'),
  }), []);

  const pct = Math.min((value / max) * 100, 100);

  const color =
    pct >= thresholds.danger
      ? 'var(--color-red)'
      : pct >= thresholds.warn
        ? 'var(--color-yellow)'
        : 'var(--color-green)';

  const data = [{ value: pct, fill: color }];

  return (
    <div className="flex flex-col items-center justify-center h-full p-2">
      <RadialBarChart
        width={140}
        height={140}
        cx={70}
        cy={70}
        innerRadius={45}
        outerRadius={65}
        barSize={12}
        data={data}
        startAngle={180}
        endAngle={0}
      >
        <PolarAngleAxis type="number" domain={[0, 100]} tick={false} />
        <RadialBar dataKey="value" cornerRadius={6} background={{ fill: colors.border }} />
      </RadialBarChart>
      <div className="text-center -mt-8">
        <div className="text-lg font-bold" style={{ color }}>
          {pct.toFixed(1)}%
        </div>
        <div className="text-xs text-[var(--color-text-secondary)]">{label}</div>
      </div>
    </div>
  );
}
