import { useMemo } from 'react';
import { AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts';

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

interface DrawdownPoint {
  time: string;
  drawdown: number;
}

interface Props {
  data?: DrawdownPoint[];
}

export function DrawdownChart({ data = [] }: Props) {
  const colors = useMemo(() => ({
    border: getCssVar('--color-border'),
    textSecondary: getCssVar('--color-text-secondary'),
    bgCard: getCssVar('--color-bg-card'),
    red: getCssVar('--color-red'),
  }), []);
  return (
    <div className="flex flex-col h-full">
      <div className="px-3 py-1.5 border-b border-[var(--color-border)]">
        <span className="text-sm font-medium">Portfolio Drawdown</span>
      </div>
      <div className="flex-1 min-h-0 p-2">
        {data.length > 0 ? (
          <ResponsiveContainer width="100%" height="100%">
            <AreaChart data={data}>
              <CartesianGrid strokeDasharray="3 3" stroke={colors.border} />
              <XAxis dataKey="time" tick={{ fontSize: 10, fill: colors.textSecondary }} />
              <YAxis
                tick={{ fontSize: 10, fill: colors.textSecondary }}
                tickFormatter={(v: number) => `${v.toFixed(1)}%`}
                domain={['dataMin', 0]}
              />
              <Tooltip
                contentStyle={{
                  backgroundColor: colors.bgCard,
                  border: `1px solid ${colors.border}`,
                  borderRadius: 4,
                  fontSize: 12,
                }}
              />
              <Area
                type="monotone"
                dataKey="drawdown"
                stroke={colors.red}
                fill={`${colors.red}33`}
                strokeWidth={2}
              />
            </AreaChart>
          </ResponsiveContainer>
        ) : (
          <div className="flex items-center justify-center h-full text-sm text-[var(--color-text-secondary)]">
            No drawdown data
          </div>
        )}
      </div>
    </div>
  );
}
