"use client"

import { useState } from "react"
import { useRouter } from "next/navigation"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Badge } from "@/components/ui/badge"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Search, ArrowUpDown, MoreVertical, Pencil, Trash2 } from "lucide-react"
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
import { Dialog, DialogContent, DialogTitle, DialogHeader, DialogFooter, DialogDescription } from "@/components/ui/dialog"
import { TradeForm } from "@/components/trade-form"
import { cn } from "@/lib/utils"
import { format } from "date-fns"
import { toast } from "sonner"

export function TradeHistory({ initialTrades = [], accounts = [], systems = [] }: { initialTrades?: any[], accounts?: any[], systems?: any[] }) {
  const router = useRouter()
  const [searchQuery, setSearchQuery] = useState("")
  const [filterType, setFilterType] = useState("all")
  const [filterAccount, setFilterAccount] = useState("all")
  const [editingTrade, setEditingTrade] = useState<any>(null)
  const [deletingTrade, setDeletingTrade] = useState<any>(null)
  const [loading, setLoading] = useState(false)

  const filteredTrades = initialTrades.filter((trade) => {
    const matchesSearch = trade.instrument.toLowerCase().includes(searchQuery.toLowerCase())
    // const matchesType = filterType === "all" || trade.type === filterType
    const matchesType = true; // TODO: Implement type filtering based on executions
    // const matchesAccount = filterAccount === "all" || trade.account === filterAccount
    const matchesAccount = true; // TODO: Implement account filtering
    return matchesSearch && matchesType && matchesAccount
  })

  const handleDelete = async () => {
    if (!deletingTrade) return
    setLoading(true)
    try {
      const res = await fetch(`/api/user/trades?id=${deletingTrade.id}`, {
        method: "DELETE",
      })
      if (!res.ok) throw new Error("Failed to delete trade")
      toast.success("Trade deleted")
      router.refresh()
      setDeletingTrade(null)
    } catch (error) {
      toast.error("Failed to delete trade")
    } finally {
      setLoading(false)
    }
  }

  const handleEdit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault()
    if (!editingTrade) return
    setLoading(true)
    const formData = new FormData(e.currentTarget)
    const data: {[key: string]: any} = Object.fromEntries(formData.entries())

    const trade = {
      id: editingTrade.id,
      market: data.market as string,
      tradingWalletId: data.wallet as string,
      tradingSystemId: data.system as string,
      instrument: data.instrument as string,
      timeframe: (function() {
        let timeframe: number = +data.timeframe < 1 ? 1 : +data.timeframe;
        switch (data.timeframe_unit) {
          case 'minute': timeframe *= 60; break;
          case 'hour':   timeframe *= 60 * 60; break;
          case 'day':    timeframe *= 60 * 60 * 24; break;
          case 'week':   timeframe *= 60 * 60 * 24 * 7; break;
          case 'month':  timeframe *= 60 * 60 * 24 * 30; break;
          default: timeframe = 0;
        }
        return timeframe;
      })(),
      duration: +data.duration === 0 ? undefined : +data.duration,
      takeProfit: +data.take_profit === 0 ? undefined : +data.take_profit,
      stopLoss: +data.stop_loss === 0 ? undefined : +data.stop_loss,
      highestPrice: +data.high === 0 ? undefined : +data.high,
      lowestPrice: +data.low === 0 ? undefined : +data.low,
      comment: (data.comment + '').length > 0 ? data.comment + '' : undefined,
      executions: (function() {
        const tradeExecutions: {[key: string]: any}[] = [];
        const indices = new Set<string>();
        for (const key of Object.keys(data)) {
            if (key.startsWith('action-')) indices.add(key.split('-')[1]);
        }
        indices.forEach((index) => {
          const execution: {[key: string]: any} = {};
          execution.action = data[`action-${index}`];
          
          const dateStr = data[`date-${index}`];
          const timeStr = data[`time-${index}`];
          if (dateStr && timeStr) {
              const d = new Date(dateStr);
              const [hours, mins] = timeStr.split(':');
              d.setHours(+(hours || 0), +(mins || 0));
              execution.datetime = d.toISOString();
          }

          execution.shares = +data[`shares-${index}`];
          execution.price = +data[`price-${index}`];
          execution.pl = +data[`pl-${index}`];
          execution.fees = +data[`fees-${index}`];
          tradeExecutions.push(execution);
        });

        return tradeExecutions;
      })(),
    };

    try {
      const res = await fetch("/api/user/trades", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(trade),
      })
      if (!res.ok) throw new Error("Failed to update trade")
      toast.success("Trade updated")
      router.refresh()
      setEditingTrade(null)
    } catch (error) {
      toast.error("Failed to update trade")
    } finally {
      setLoading(false)
    }
  }

  return (
    <div>
      <div className="flex flex-col gap-4 md:flex-row md:items-center mb-6">
        <div className="relative flex-1">
          <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
          <Input
            placeholder="Search by asset..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="pl-10"
          />
        </div>
        <Select value={filterType} onValueChange={setFilterType}>
          <SelectTrigger className="w-full md:w-45">
            <SelectValue placeholder="Type" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">All Types</SelectItem>
            <SelectItem value="Call">Call</SelectItem>
            <SelectItem value="Put">Put</SelectItem>
          </SelectContent>
        </Select>
        <Select value={filterAccount} onValueChange={setFilterAccount}>
          <SelectTrigger className="w-full md:w-45">
            <SelectValue placeholder="Account" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">All Accounts</SelectItem>
            <SelectItem value="Live Account">Live Account</SelectItem>
            <SelectItem value="Demo Account">Demo Account</SelectItem>
          </SelectContent>
        </Select>
        <Button variant="outline" size="icon">
          <ArrowUpDown className="h-4 w-4" />
        </Button>
      </div>

      <div className="rounded-md border">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>Date & Time</TableHead>
              <TableHead>Asset</TableHead>
              <TableHead>Action</TableHead>
              <TableHead className="text-right">Price</TableHead>
              <TableHead className="text-right">P&L</TableHead>
              <TableHead className="text-right">Duration</TableHead>
              <TableHead>Account</TableHead>
              <TableHead className="w-12.5"></TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {filteredTrades.map((trade) => {
              const firstExec = trade.executions?.[0];
              const profit = trade.executions?.reduce((acc: number, exec: any) => acc + (exec.profitLoss || 0), 0) || 0;
              const duration = trade.duration ? `${trade.duration}s` : "-";
              
              return (
                <TableRow key={trade.id}>
                  <TableCell className="font-medium">
                    {firstExec ? format(new Date(firstExec.executionDate), "PP p") : format(new Date(trade.createdAt), "PP p")}
                  </TableCell>
                  <TableCell className="font-semibold">{trade.instrument}</TableCell>
                  <TableCell>
                    <Badge variant="secondary">{firstExec?.action || "UNKNOWN"}</Badge>
                  </TableCell>
                  <TableCell className="text-right font-mono">{firstExec?.executionPrice || "-"}</TableCell>
                  <TableCell className="text-right">
                    <span className={cn("font-semibold", profit >= 0 ? "text-green-600" : "text-red-600")}>
                      {profit >= 0 ? "+" : ""}{profit.toFixed(2)}
                    </span>
                  </TableCell>
                  <TableCell className="text-right text-muted-foreground">{duration}</TableCell>
                  <TableCell>
                    <Badge variant="outline">{trade.wallet?.tradingAccount?.name || "Unknown"}</Badge>
                  </TableCell>
                  <TableCell>
                    <DropdownMenu>
                      <DropdownMenuTrigger asChild>
                        <Button variant="ghost" size="icon" className="h-8 w-8">
                          <MoreVertical className="h-4 w-4" />
                        </Button>
                      </DropdownMenuTrigger>
                      <DropdownMenuContent align="end">
                        <DropdownMenuItem onClick={() => setEditingTrade(trade)}>
                          <Pencil className="mr-2 h-4 w-4" /> Edit
                        </DropdownMenuItem>
                        <DropdownMenuItem className="text-destructive" onClick={() => setDeletingTrade(trade)}>
                          <Trash2 className="mr-2 h-4 w-4" /> Delete
                        </DropdownMenuItem>
                      </DropdownMenuContent>
                    </DropdownMenu>
                  </TableCell>
                </TableRow>
              )
            })}
            {filteredTrades.length === 0 && (
              <TableRow>
                <TableCell colSpan={8} className="text-center py-8 text-muted-foreground">
                  No trades found.
                </TableCell>
              </TableRow>
            )}
          </TableBody>
        </Table>
      </div>

      <div className="flex items-center justify-between mt-4">
        <p className="text-sm text-muted-foreground">
          Showing {filteredTrades.length} of {initialTrades.length} trades
        </p>
        <div className="flex gap-2">
          <Button variant="outline" size="sm">
            Previous
          </Button>
          <Button variant="outline" size="sm">
            Next
          </Button>
        </div>
      </div>

      <Dialog open={!!editingTrade} onOpenChange={(open) => !open && setEditingTrade(null)}>
        <DialogContent className="sm:max-w-106.25 overflow-hidden max-h-[calc(100vh-2.5rem)] flex flex-col px-0! pb-0! gap-0">
          <div className="flex-1 overflow-y-auto px-6">
            <DialogHeader className="pb-6 pt-6">
              <DialogTitle>Edit Trade</DialogTitle>
              <DialogDescription>Make changes to your trade here.</DialogDescription>
            </DialogHeader>
            <form id="edit-trade-form" onSubmit={handleEdit} className="pb-4">
              <TradeForm accounts={accounts} systems={systems} initialData={editingTrade} />
            </form>
          </div>
          <div className="px-6 py-4 flex justify-end gap-3 border-t border-border">
            <Button variant="outline" onClick={() => setEditingTrade(null)}>Cancel</Button>
            <Button type="submit" form="edit-trade-form" disabled={loading}>
              {loading ? "Saving..." : "Save Changes"}
            </Button>
          </div>
        </DialogContent>
      </Dialog>

      <Dialog open={!!deletingTrade} onOpenChange={(open) => !open && setDeletingTrade(null)}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Delete Trade</DialogTitle>
            <DialogDescription>Are you sure you want to delete this trade? This action cannot be undone.</DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button variant="outline" onClick={() => setDeletingTrade(null)}>Cancel</Button>
            <Button variant="destructive" onClick={handleDelete} disabled={loading}>
              {loading ? "Deleting..." : "Delete"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
      
    </div>
  )
}
