import { PnLChart } from '../components/charts/PnLChart';
import { ComponentErrorBoundary } from '../components/common/ComponentErrorBoundary';
import { MetricCard } from '../components/charts/MetricCard';
import { usePerformanceMetrics } from '../hooks/useApi';

export function PerformanceDashboard() {
  const metricsQuery = usePerformanceMetrics();

  // The gRPC response is GetMetricsResponse with a `metrics` array of Metric objects.
  // We try to find known metric names in the array for display.
  const metricsList = metricsQuery.data?.metrics ?? [];
  const findMetric = (name: string) =>
    metricsList.find((m) => m.name === name);

  const sharpe = findMetric('sharpe_ratio');
  const sortino = findMetric('sortino_ratio');
  const maxDD = findMetric('max_drawdown');
  const winRate = findMetric('win_rate');
  const totalTrades = findMetric('total_trades');

  return (
    <div className="space-y-4">
      {metricsQuery.isError && (
        <div className="px-3 py-2 rounded border border-[var(--color-red)] bg-red-500/10 text-sm text-[var(--color-red)] flex items-center justify-between">
          <span>Failed to load metrics: {metricsQuery.error.message}</span>
          <button onClick={() => metricsQuery.refetch()} className="text-xs underline">Retry</button>
        </div>
      )}

      {/* Top: Metric cards */}
      <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-4">
        <div className="rounded border border-[var(--color-border)] bg-[var(--color-bg-card)]">
          <MetricCard label="Sharpe Ratio" value={sharpe?.value?.toFixed(2) ?? '--'} />
        </div>
        <div className="rounded border border-[var(--color-border)] bg-[var(--color-bg-card)]">
          <MetricCard label="Sortino Ratio" value={sortino?.value?.toFixed(2) ?? '--'} />
        </div>
        <div className="rounded border border-[var(--color-border)] bg-[var(--color-bg-card)]">
          <MetricCard
            label="Max Drawdown"
            value={maxDD?.value?.toFixed(2) ?? '--'}
            suffix="%"
          />
        </div>
        <div className="rounded border border-[var(--color-border)] bg-[var(--color-bg-card)]">
          <MetricCard
            label="Win Rate"
            value={winRate?.value !== undefined ? (winRate.value * 100).toFixed(1) : '--'}
            suffix="%"
          />
        </div>
        <div className="rounded border border-[var(--color-border)] bg-[var(--color-bg-card)]">
          <MetricCard label="Total Trades" value={totalTrades?.value ?? '--'} />
        </div>
      </div>

      {/* Middle: P&L Chart */}
      <div className="h-64 rounded border border-[var(--color-border)] bg-[var(--color-bg-card)]">
        <ComponentErrorBoundary name="P&L Chart">
          <PnLChart title="Cumulative P&L" data={undefined} />
        </ComponentErrorBoundary>
      </div>

      {/* Bottom: Daily returns + Heatmap */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        <div className="h-48 rounded border border-[var(--color-border)] bg-[var(--color-bg-card)]">
          <ComponentErrorBoundary name="Daily Returns Chart">
            <PnLChart title="Daily Returns" data={undefined} />
          </ComponentErrorBoundary>
        </div>
        <div className="h-48 rounded border border-[var(--color-border)] bg-[var(--color-bg-card)]">
          <div className="px-3 py-1.5 border-b border-[var(--color-border)]">
            <span className="text-sm font-medium">P&L Heatmap</span>
          </div>
          <div className="flex items-center justify-center h-full text-sm text-[var(--color-text-secondary)]">
            Strategy x Time heatmap
          </div>
        </div>
      </div>
    </div>
  );
}
