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

interface Position {
  pnl: string;
  time_exit: string;
}

interface EquityCurvePoint {
  time: number;          // unix ms, for XAxis
  label: string;         // formatted date, for tooltip
  cumulative_pnl: number;
}

interface Props {
  positions: Position[];
}

function buildCurve(positions: Position[]): EquityCurvePoint[] {
  let cumulative = 0;
  const points: EquityCurvePoint[] = [{ time: 0, label: '', cumulative_pnl: 0 }];

  for (const pos of positions) {
    const pnl = parseFloat(pos.pnl) || 0;
    cumulative += pnl;
    const t = new Date(pos.time_exit).getTime();
    points.push({
      time: t,
      label: new Date(pos.time_exit).toLocaleString(undefined, { year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit', hour12: false }),
      cumulative_pnl: parseFloat(cumulative.toFixed(6)),
    });
  }

  // Set the phantom first point to the same time as the first real point
  if (points.length > 1) {
    points[0].time = points[1].time;
    points[0].label = points[1].label;
  }

  return points;
}

function formatXAxis(unixMs: number): string {
  if (unixMs === 0) return '';
  const d = new Date(unixMs);
  return d.toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: '2-digit' });
}

function formatPnl(value: number): string {
  return value >= 0 ? `+${value.toFixed(4)}` : value.toFixed(4);
}

function buildTicks(data: EquityCurvePoint[], count: number): number[] {
  if (data.length < 2) return [];
  const start = data[1].time; // skip phantom
  const end = data[data.length - 1].time;
  const step = (end - start) / (count - 1);
  return Array.from({ length: count }, (_, i) => Math.round(start + i * step));
}

export default function EquityCurveChart({ positions }: Props) {
  if (positions.length === 0) return null;

  const data = buildCurve(positions);
  const finalPnl = data[data.length - 1].cumulative_pnl;
  const color = finalPnl >= 0 ? '#198754' : '#dc3545';  // Bootstrap success/danger
  const ticks = buildTicks(data, 6);

  return (
    <ResponsiveContainer width="100%" height={260}>
      <AreaChart data={data} margin={{ top: 8, right: 16, left: 8, bottom: 0 }}>
        <defs>
          <linearGradient id="pnlGradient" x1="0" y1="0" x2="0" y2="1">
            <stop offset="5%" stopColor={color} stopOpacity={0.25} />
            <stop offset="95%" stopColor={color} stopOpacity={0.02} />
          </linearGradient>
        </defs>
        <CartesianGrid strokeDasharray="3 3" stroke="#dee2e6" />
        <XAxis
          dataKey="time"
          type="number"
          domain={['dataMin', 'dataMax']}
          scale="time"
          ticks={ticks}
          tickFormatter={formatXAxis}
          tick={{ fontSize: 11 }}
        />
        <YAxis
          tickFormatter={(v) => v.toFixed(2)}
          tick={{ fontSize: 11 }}
          width={72}
        />
        <Tooltip
          formatter={(value) => [formatPnl(value as number), 'Cumulative PnL']}
          labelFormatter={(label) => new Date(label as number).toLocaleString(undefined, { year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit', hour12: false })}
          contentStyle={{ fontSize: '0.82em' }}
        />
        <ReferenceLine y={0} stroke="#6c757d" strokeDasharray="4 2" />
        <Area
          type="monotone"
          dataKey="cumulative_pnl"
          stroke={color}
          strokeWidth={1.5}
          fill="url(#pnlGradient)"
          dot={false}
          activeDot={{ r: 3 }}
          isAnimationActive={false}
        />
      </AreaChart>
    </ResponsiveContainer>
  );
}
