"use client"

import { useState, useEffect, useMemo } from "react"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Calendar } from "@/components/ui/calendar"
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { CalendarIcon, Download } from "lucide-react"
import { format } from "date-fns"
import { cn } from "@/lib/utils"
import { WinLossChart } from "@/components/charts/win-loss-chart"
import { PerformanceByAssetChart } from "@/components/charts/performance-by-asset-chart"
import { PerformanceByTimeChart } from "@/components/charts/performance-by-time-chart"
import { toast } from "sonner"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import type { TradingWallet, TradingAccount, Trade, TradeExecution } from "@/generated/prisma/client"

interface ReportContentProps {
  wallets: (TradingWallet & { tradingAccount: TradingAccount })[];
}

export function ReportContent({ wallets }: ReportContentProps) {
  const [date, setDate] = useState<Date>()
  const [selectedWalletId, setSelectedWalletId] = useState<string>(wallets[0]?.id || "")
  const [trades, setTrades] = useState<(Trade & { executions: TradeExecution[] })[]>([])
  const [loading, setLoading] = useState(false)

  const selectedWallet = wallets.find(w => w.id === selectedWalletId);
  const currency = selectedWallet?.currency || "USD";

  useEffect(() => {
    const fetchTrades = async () => {
      if (!selectedWalletId) return;
      
      setLoading(true);
      try {
        const params = new URLSearchParams();
        params.set("walletId", selectedWalletId);
        if (date) {
          params.set("date", date.toISOString());
        }

        const res = await fetch(`/api/user/report-trades?${params.toString()}`);
        if (res.ok) {
          const data = await res.json();
          setTrades(data.trades);
        }
      } catch (error) {
        console.error(error);
        toast.error("Failed to fetch report data");
      } finally {
        setLoading(false);
      }
    };

    fetchTrades();
  }, [selectedWalletId, date]);

  const handleExport = () => {
    toast("Export started", { description: "Your report is being exported to PDF" })
  }

  const stats = useMemo(() => {
    let totalProfit = 0;
    let winCount = 0;
    let lossCount = 0;
    let grossProfit = 0;
    let grossLoss = 0;
    let largestWin = 0;
    let largestLoss = 0;

    trades.forEach(trade => {
      const profit = trade.executions.reduce((acc, exec) => acc + (exec.profitLoss || 0), 0);
      totalProfit += profit;
      if (profit > 0) {
        winCount++;
        grossProfit += profit;
        if (profit > largestWin) largestWin = profit;
      } else if (profit < 0) {
        lossCount++;
        grossLoss += Math.abs(profit);
        if (profit < largestLoss) largestLoss = profit;
      }
    });

    const totalTrades = winCount + lossCount; // Excluding break-even for win rate usually, or include? Let's include all non-zero
    const winRate = totalTrades > 0 ? (winCount / totalTrades) * 100 : 0;
    const profitFactor = grossLoss > 0 ? grossProfit / grossLoss : grossProfit > 0 ? Infinity : 0;
    const avgTrade = totalTrades > 0 ? totalProfit / totalTrades : 0;

    return {
      totalProfit,
      winRate,
      profitFactor,
      avgTrade,
      winCount,
      lossCount,
      largestWin,
      largestLoss,
      totalTrades,
      grossProfit,
      grossLoss
    };
  }, [trades]);

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">Reports</h1>
          <p className="text-muted-foreground">Analyze your trading performance</p>
        </div>
        <div className="flex gap-2">
          <Select value={selectedWalletId} onValueChange={setSelectedWalletId}>
            <SelectTrigger className="w-50">
              <SelectValue placeholder="Select Wallet" />
            </SelectTrigger>
            <SelectContent>
              {wallets.map((wallet) => (
                <SelectItem key={wallet.id} value={wallet.id}>
                  {wallet.currency} - {wallet.tradingAccount.name}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
          <Popover>
            <PopoverTrigger asChild>
              <Button variant="outline" className={cn(!date && "text-muted-foreground")}>
                <CalendarIcon className="mr-2 h-4 w-4" />
                {date ? format(date, "PPP") : "Pick a date"}
              </Button>
            </PopoverTrigger>
            <PopoverContent className="w-auto p-0">
              <Calendar 
                mode="single" 
                selected={date} 
                onSelect={setDate} 
                initialFocus 
              />
              <div className="p-3 border-t">
                <Button variant="ghost" size="sm" className="w-full" onClick={() => setDate(undefined)}>
                  Clear Date
                </Button>
              </div>
            </PopoverContent>
          </Popover>
          <Button onClick={handleExport}>
            <Download className="mr-2 h-4 w-4" />
            Export Report
          </Button>
        </div>
      </div>

      {/* Performance Summary */}
      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
        <Card>
          <CardHeader className="space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Total Profit</CardTitle>
          </CardHeader>
          <CardContent>
            <div className={cn("text-2xl font-bold", stats.totalProfit >= 0 ? "text-green-600" : "text-red-600")}>{currency} {stats.totalProfit.toFixed(2)}</div>
            <p className="text-xs text-muted-foreground mt-1">From {stats.totalTrades} trades</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Win Rate</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{stats.winRate.toFixed(1)}%</div>
            <p className="text-xs text-muted-foreground mt-1">{stats.winCount} wins / {stats.lossCount} losses</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Profit Factor</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{stats.profitFactor === Infinity ? "∞" : stats.profitFactor.toFixed(2)}</div>
            <p className="text-xs text-muted-foreground mt-1">Good risk/reward ratio</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Avg Trade</CardTitle>
          </CardHeader>
          <CardContent>
            <div className={cn("text-2xl font-bold", stats.avgTrade >= 0 ? "text-green-600" : "text-red-600")}>{currency} {stats.avgTrade.toFixed(2)}</div>
            <p className="text-xs text-muted-foreground mt-1">Per trade average</p>
          </CardContent>
        </Card>
      </div>

      {/* Charts */}
      <Tabs defaultValue="distribution" className="space-y-4">
        <TabsList>
          <TabsTrigger value="distribution">Win/Loss Distribution</TabsTrigger>
          <TabsTrigger value="asset">By Asset</TabsTrigger>
          <TabsTrigger value="time">By Time</TabsTrigger>
        </TabsList>

        <TabsContent value="distribution" className="space-y-4">
          <Card>
            <CardHeader>
              <CardTitle>Win/Loss Distribution</CardTitle>
              <CardDescription>Overview of your trading outcomes</CardDescription>
            </CardHeader>
            <CardContent className="pl-2">
              <WinLossChart data={[
                { name: 'Win', value: stats.winCount },
                { name: 'Loss', value: stats.lossCount }
              ]} />
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="asset" className="space-y-4">
          <Card>
            <CardHeader>
              <CardTitle>Performance by Asset</CardTitle>
              <CardDescription>See which assets are most profitable</CardDescription>
            </CardHeader>
            <CardContent className="pl-2">
              <PerformanceByAssetChart trades={trades} />
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="time" className="space-y-4">
          <Card>
            <CardHeader>
              <CardTitle>Performance by Time of Day</CardTitle>
              <CardDescription>Identify your best trading hours</CardDescription>
            </CardHeader>
            <CardContent className="pl-2">
              <PerformanceByTimeChart trades={trades} />
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>

      {/* Detailed Statistics */}
      <Card>
        <CardHeader>
          <CardTitle>Detailed Statistics</CardTitle>
          <CardDescription>Comprehensive performance metrics</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
            <div className="space-y-2">
              <p className="text-sm font-medium text-muted-foreground">Largest Win</p>
              <p className="text-2xl font-bold text-green-600">+{stats.largestWin.toFixed(2)}</p>
            </div>
            <div className="space-y-2">
              <p className="text-sm font-medium text-muted-foreground">Largest Loss</p>
              <p className="text-2xl font-bold text-red-600">{stats.largestLoss.toFixed(2)}</p>
            </div>
            <div className="space-y-2">
              <p className="text-sm font-medium text-muted-foreground">Average Win</p>
              <p className="text-2xl font-bold">{(stats.winCount > 0 ? stats.grossProfit / stats.winCount : 0).toFixed(2)}</p>
            </div>
            <div className="space-y-2">
              <p className="text-sm font-medium text-muted-foreground">Average Loss</p>
              <p className="text-2xl font-bold">{(stats.lossCount > 0 ? stats.grossLoss / stats.lossCount : 0).toFixed(2)}</p>
            </div>
            <div className="space-y-2">
              <p className="text-sm font-medium text-muted-foreground">Best Streak</p>
              <p className="text-2xl font-bold">-</p>
            </div>
            <div className="space-y-2">
              <p className="text-sm font-medium text-muted-foreground">Worst Streak</p>
              <p className="text-2xl font-bold">-</p>
            </div>
          </div>
        </CardContent>
      </Card>
    </div>
  )
}
