"use client"

import { Line, LineChart, CartesianGrid, XAxis, YAxis, Tooltip, ResponsiveContainer } from "recharts"
import { useMemo } from "react"
import type { Trade, TradeExecution } from "@/generated/prisma/client"
import { getHours } from "date-fns"

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

export function PerformanceByTimeChart({ trades }: PerformanceByTimeChartProps) {
  const data = useMemo(() => {
    const hourMap = new Map<number, number>();
    // Initialize all hours
    for (let i = 0; i < 24; i++) hourMap.set(i, 0);

    trades.forEach(trade => {
      const date = new Date(trade.createdAt);
      const hour = getHours(date);
      const profit = trade.executions.reduce((acc, exec) => acc + (exec.profitLoss || 0), 0);
      hourMap.set(hour, (hourMap.get(hour) || 0) + profit);
    });

    return Array.from(hourMap.entries())
      .map(([hour, profit]) => ({
        hour: `${hour}:00`,
        profit
      }));
  }, [trades]);

  return (
    <ResponsiveContainer width="100%" height={350}>
      <LineChart data={data}>
        <CartesianGrid strokeDasharray="3 3" className="stroke-muted" />
        <XAxis dataKey="hour" stroke="hsl(var(--muted-foreground))" fontSize={12} tickLine={false} />
        <YAxis
          stroke="hsl(var(--muted-foreground))"
          fontSize={12}
          tickLine={false}
          tickFormatter={(value) => `$${value}`}
        />
        <Tooltip
          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 text-muted-foreground">{data.hour}</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
          }}
        />
        <Line
          type="monotone"
          dataKey="profit"
          stroke="hsl(var(--chart-1))"
          strokeWidth={2}
          dot={{ fill: "hsl(var(--chart-1))", r: 4 }}
        />
      </LineChart>
    </ResponsiveContainer>
  )
}
