"use client"

import { Bar, BarChart, CartesianGrid, XAxis, YAxis, Tooltip, ResponsiveContainer, Cell } from "recharts"
import { useMemo } from "react"
import type { Trade, TradeExecution } from "@/generated/prisma/client"

interface PerformanceByAssetChartProps {
  trades: (Trade & { executions: TradeExecution[] })[]
}

export function PerformanceByAssetChart({ trades }: PerformanceByAssetChartProps) {
  const data = useMemo(() => {
    const assetMap = new Map<string, number>();
    
    trades.forEach(trade => {
      const profit = trade.executions.reduce((acc, exec) => acc + (exec.profitLoss || 0), 0);
      const current = assetMap.get(trade.instrument) || 0;
      assetMap.set(trade.instrument, current + profit);
    });

    return Array.from(assetMap.entries())
      .map(([asset, profit]) => ({ asset, profit }))
      .sort((a, b) => b.profit - a.profit)
      .slice(0, 10); // Top 10
  }, [trades]);

  return (
    <ResponsiveContainer width="100%" height={350}>
      <BarChart data={data} layout="vertical">
        <CartesianGrid strokeDasharray="3 3" className="stroke-muted" />
        <XAxis
          type="number"
          stroke="hsl(var(--muted-foreground))"
          fontSize={12}
          tickLine={false}
          tickFormatter={(value) => `$${value}`}
        />
        <YAxis
          dataKey="asset"
          type="category"
          stroke="hsl(var(--muted-foreground))"
          fontSize={12}
          tickLine={false}
          width={80}
        />
        <Tooltip
          cursor={{ fill: 'transparent' }}
          content={({ active, payload }) => {
            if (active && payload && payload.length) {
              const data = payload[0].payload;
              return (
                <div className="rounded-lg border bg-card p-3 shadow-sm">
                  <p className="text-sm font-medium">{data.asset}</p>
                  <p className={`text-lg font-bold ${data.profit >= 0 ? 'text-green-600' : 'text-red-600'}`}>
                    {data.profit >= 0 ? '+' : ''}{data.profit.toFixed(2)}
                  </p>
                </div>
              )
            }
            return null
          }}
        />
        <Bar dataKey="profit" radius={[0, 4, 4, 0]}>
           {data.map((entry, index) => (
            <Cell key={`cell-${index}`} fill={entry.profit >= 0 ? "hsl(var(--success))" : "hsl(var(--destructive))"} />
          ))}
        </Bar>
      </BarChart>
    </ResponsiveContainer>
  )
}
