"use client"

import { useState } from "react"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Badge } from "@/components/ui/badge"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { TrendingUp, TrendingDown, RotateCcw } from "lucide-react"
import { SimulatorChart } from "@/components/charts/simulator-chart"
import { toast } from "sonner"
import { cn } from "@/lib/utils"

const practiceHistory = [
  { id: 1, time: "14:32:15", asset: "EUR/USD", type: "Call", investment: 100, payout: 185, result: "win" },
  { id: 2, time: "14:28:43", asset: "BTC/USD", type: "Put", investment: 50, payout: 0, result: "loss" },
  { id: 3, time: "14:25:12", asset: "Gold", type: "Call", investment: 75, payout: 138, result: "win" },
]

export function SimulatorContent() {
  const [balance, setBalance] = useState(10000)
  const [investment, setInvestment] = useState("100")
  const [selectedAsset, setSelectedAsset] = useState("EUR/USD")

  const handleTrade = (type: "call" | "put") => {
    const amount = Number.parseFloat(investment)
    const isWin = Math.random() > 0.4 // 60% win rate for demo

    if (isWin) {
      const payout = amount * 1.85
      setBalance(balance + payout)
      toast("Trade Won! 🎉", { description: `You earned $${payout.toFixed(2)}` })
    } else {
      setBalance(balance - amount)
      toast.error("Trade Lost", { description: `You lost $${amount.toFixed(2)}` })
    }
  }

  const handleReset = () => {
    setBalance(10000)
    toast("Simulator reset", { description: "Your practice balance has been reset to $10,000" })
  }

  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">Trading Simulator</h1>
          <p className="text-muted-foreground">Practice trading without risking real money</p>
        </div>
        <Button variant="outline" onClick={handleReset}>
          <RotateCcw className="mr-2 h-4 w-4" />
          Reset Simulator
        </Button>
      </div>

      {/* Balance Display */}
      <Card>
        <CardHeader>
          <CardTitle>Practice Balance</CardTitle>
          <CardDescription>This is virtual money for practice only</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="text-4xl font-bold">${balance.toLocaleString()}</div>
          <p className="text-sm text-muted-foreground mt-2">
            {balance > 10000 ? (
              <span className="text-success">+${(balance - 10000).toLocaleString()} profit</span>
            ) : balance < 10000 ? (
              <span className="text-destructive">-${(10000 - balance).toLocaleString()} loss</span>
            ) : (
              "Starting balance"
            )}
          </p>
        </CardContent>
      </Card>

      {/* Trading Interface */}
      <div className="grid gap-4 lg:grid-cols-3">
        <Card className="lg:col-span-2">
          <CardHeader>
            <CardTitle>Price Chart</CardTitle>
            <CardDescription>Live market simulation</CardDescription>
          </CardHeader>
          <CardContent>
            <SimulatorChart />
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>Execute Trade</CardTitle>
            <CardDescription>Place a practice trade</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="asset">Asset</Label>
              <Select value={selectedAsset} onValueChange={setSelectedAsset}>
                <SelectTrigger id="asset">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="EUR/USD">EUR/USD</SelectItem>
                  <SelectItem value="GBP/USD">GBP/USD</SelectItem>
                  <SelectItem value="BTC/USD">BTC/USD</SelectItem>
                  <SelectItem value="Gold">Gold</SelectItem>
                  <SelectItem value="Oil">Oil</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div className="space-y-2">
              <Label htmlFor="investment">Investment Amount</Label>
              <Input
                id="investment"
                type="number"
                value={investment}
                onChange={(e) => setInvestment(e.target.value)}
                min="10"
                max={balance}
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="expiry">Expiry Time</Label>
              <Select defaultValue="5m">
                <SelectTrigger id="expiry">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="1m">1 Minute</SelectItem>
                  <SelectItem value="5m">5 Minutes</SelectItem>
                  <SelectItem value="15m">15 Minutes</SelectItem>
                  <SelectItem value="30m">30 Minutes</SelectItem>
                  <SelectItem value="1h">1 Hour</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div className="pt-4 space-y-2">
              <Button
                className="w-full bg-success hover:bg-success/90"
                onClick={() => handleTrade("call")}
                disabled={Number.parseFloat(investment) > balance}
              >
                <TrendingUp className="mr-2 h-4 w-4" />
                Call (Higher)
              </Button>
              <Button
                className="w-full"
                variant="destructive"
                onClick={() => handleTrade("put")}
                disabled={Number.parseFloat(investment) > balance}
              >
                <TrendingDown className="mr-2 h-4 w-4" />
                Put (Lower)
              </Button>
            </div>

            <div className="pt-4 border-t text-sm text-muted-foreground">
              <p>Potential Payout: ${(Number.parseFloat(investment) * 1.85).toFixed(2)}</p>
              <p>Profit: ${(Number.parseFloat(investment) * 0.85).toFixed(2)}</p>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Practice History */}
      <Card>
        <CardHeader>
          <CardTitle>Practice History</CardTitle>
          <CardDescription>Your recent practice trades</CardDescription>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Time</TableHead>
                <TableHead>Asset</TableHead>
                <TableHead>Type</TableHead>
                <TableHead className="text-right">Investment</TableHead>
                <TableHead className="text-right">Payout</TableHead>
                <TableHead>Result</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {practiceHistory.map((trade) => (
                <TableRow key={trade.id}>
                  <TableCell className="font-medium">{trade.time}</TableCell>
                  <TableCell>{trade.asset}</TableCell>
                  <TableCell>
                    <Badge variant={trade.type === "Call" ? "default" : "secondary"}>{trade.type}</Badge>
                  </TableCell>
                  <TableCell className="text-right">${trade.investment}</TableCell>
                  <TableCell className="text-right">${trade.payout}</TableCell>
                  <TableCell>
                    <Badge
                      variant="outline"
                      className={cn(
                        trade.result === "win"
                          ? "bg-success/10 text-success border-success/20"
                          : "bg-destructive/10 text-destructive border-destructive/20",
                      )}
                    >
                      {trade.result}
                    </Badge>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </CardContent>
      </Card>
    </div>
  )
}
