"use client"

import { useState, useMemo, useEffect } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea"
import { InputGroup, InputGroupAddon, InputGroupInput, InputGroupText } from "@/components/ui/input-group";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Label } from "@/components/ui/label";
import { Popover, PopoverTrigger, PopoverContent } from '@/components/ui/popover';
import { Calendar } from '@/components/ui/calendar';
import { Plus, Trash2, ChevronDownIcon } from "lucide-react";
import { cn } from "@/lib/utils";
import { format } from "date-fns";

export interface Execution {
  id: number | string;
  date?: Date;
  action?: string;
  shares?: number;
  price?: number;
  pl?: number;
  fees?: number;
}

export interface TradeFormProps {
  className?: string;
  accounts: { id: string; name: string; walletId: string; currency: string }[];
  systems: { id: string; name: string }[];
  initialData?: any;
  onSubmit?: (data: any) => void;
  id?: string;
}

export function TradeForm({ 
  className,
  accounts,
  systems,
  initialData,
  id
}: TradeFormProps) {
  const [executions, setExecutions] = useState<Execution[]>(
    initialData?.executions?.map((e: any) => ({
      id: e.id,
      date: new Date(e.executionDate),
      action: e.action,
      shares: e.volume,
      price: e.executionPrice,
      pl: e.profitLoss,
      fees: e.fee
    })) || [{ id: Date.now(), date: new Date() }]
  );
  const [openDtIndex, setOpenDtIndex] = useState<number | null>(null);
  
  const initialAccountId = useMemo(() => {
    if (initialData?.wallet?.tradingAccountId) return initialData.wallet.tradingAccountId;
    if (initialData?.tradingWalletId) {
      const account = accounts.find(a => a.walletId === initialData.tradingWalletId);
      if (account) return account.id;
    }
    return accounts.length > 0 ? accounts[0].id : "";
  }, [initialData, accounts]);

  const [selectedAccount, setSelectedAccount] = useState<string>(initialAccountId);
  const [selectedMarket, setSelectedMarket] = useState<string>(initialData?.market || "FOREX");

  const uniqueAccounts = useMemo(() => {
    const map = new Map();
    accounts.forEach(a => {
      if (!map.has(a.id)) map.set(a.id, a.name);
    });
    return Array.from(map.entries()).map(([id, name]) => ({ id, name }));
  }, [accounts]);

  const accountWallets = useMemo(() => {
    return accounts.filter(a => a.id === selectedAccount);
  }, [accounts, selectedAccount]);

  const addExecution = () => {
    setExecutions([...executions, { id: Date.now(), date: new Date() }]);
  }

  const removeExecution = (id: number | string) => {
    if (executions.length > 1) {
      setExecutions(executions.filter((e) => e.id !== id));
    }
  }

  const updateAction = (index: number, value: string) => {
    const newExecutions = [...executions];
    newExecutions[index].action = value;
    setExecutions(newExecutions);
  }

  useEffect(() => {
    if (selectedMarket === 'OPTIONS') {
      setExecutions(prev => {
        const newExecs = prev.slice(0, 1);
        if (newExecs.length > 0 && newExecs[0].action !== 'CALL' && newExecs[0].action !== 'PUT') {
             newExecs[0] = { ...newExecs[0], action: 'CALL' };
        }
        return newExecs;
      });
    } else {
       setExecutions(prev => {
         let changed = false;
         const newExecs = prev.map(e => {
            if (e.action === 'CALL' || e.action === 'PUT') {
                changed = true;
                return { ...e, action: 'BUY' };
            }
            return e;
         });
         return changed ? newExecs : prev;
       });
    }
  }, [selectedMarket]);

  const updateDate = (index: number, newDate: Date | undefined) => {
    const newExecutions = [...executions];
    newExecutions[index].date = newDate;
    setExecutions(newExecutions);
  }

  return (
    <div className={cn("grid items-start gap-4", className)}>
      <div className="grid gap-2">
        <Label htmlFor="market" className="gap-1">Market<span className="text-primary">*</span></Label>
        <Select name="market" value={selectedMarket} onValueChange={setSelectedMarket}>
          <SelectTrigger className="w-full">
            <SelectValue placeholder="Select" />
          </SelectTrigger>
          <SelectContent className="w-full">
            <SelectItem value="FOREX">Forex</SelectItem>
            <SelectItem value="STOCKS">Stocks</SelectItem>
            <SelectItem value="COMMODITIES">Commodities</SelectItem>
            <SelectItem value="CRYPTOCURRENCY">Cryptocurrency</SelectItem>
            <SelectItem value="INDICES">Indices</SelectItem>
            <SelectItem value="FUTURES">Futures</SelectItem>
            <SelectItem value="OPTIONS">Options</SelectItem>
          </SelectContent>
        </Select>
      </div>

      <div className="grid gap-2">
        <Label htmlFor="account" className="gap-1">Account<span className="text-primary">*</span></Label>
        <Select value={selectedAccount} onValueChange={setSelectedAccount}>
          <SelectTrigger className="w-full">
            <SelectValue placeholder="Select" />
          </SelectTrigger>
          <SelectContent className="w-full">
            {uniqueAccounts.length > 0 ? (
              uniqueAccounts.map((acc) => <SelectItem key={acc.id} value={acc.id}>{acc.name}</SelectItem>)
            ) : (
              <div className="px-2 py-1 text-xs text-muted-foreground">No accounts found</div>
            )}
          </SelectContent>
        </Select>
      </div>

      <div className="grid gap-2">
        <Label htmlFor="wallet" className="gap-1">Wallet<span className="text-primary">*</span></Label>
        <Select name="wallet" defaultValue={initialData?.tradingWalletId || (accountWallets.length > 0 ? accountWallets[0].walletId : "")} key={selectedAccount}>
          <SelectTrigger className="w-full">
            <SelectValue placeholder="Select" />
          </SelectTrigger>
          <SelectContent className="w-full">
            {accountWallets.length > 0 ? (
              accountWallets.map((w) => <SelectItem key={w.walletId} value={w.walletId}>{w.currency}</SelectItem>)
            ) : (
              <div className="px-2 py-1 text-xs text-muted-foreground">No wallets found</div>
            )}
          </SelectContent>
        </Select>
      </div>

      <div className="grid gap-2">
        <Label htmlFor="system" className="gap-1">Trading System<span className="text-primary">*</span></Label>
        <Select name="system" defaultValue={initialData?.tradingSystemId || "none"}>
          <SelectTrigger className="w-full">
            <SelectValue placeholder="Select" />
          </SelectTrigger>
          <SelectContent className="w-full">
            <SelectItem value="none">None</SelectItem>
            {systems.length > 0 && (
              systems.map((sys) => <SelectItem key={sys.id} value={sys.id}>{sys.name}</SelectItem>)
            )}
          </SelectContent>
        </Select>
      </div>

      <div className="grid grid-cols-2 gap-3">
        <div className="grid gap-2">
          <Label htmlFor="instrument" className="gap-1">Instrument<span className="text-primary">*</span></Label>
          <Input required id="instrument" name="instrument" defaultValue={initialData?.instrument} placeholder="e.g. EUR/USD" />
        </div>
        
        <div className="grid gap-2">
          <Label htmlFor="timeframe" className="gap-1">Timeframe<span className="text-primary">*</span></Label>
          <InputGroup>
            <InputGroupInput type="number" required id="timeframe" min="1" step="1" name="timeframe" defaultValue={initialData?.timeframe ? initialData.timeframe / 60 : undefined} placeholder="0" />
            <InputGroupAddon align="inline-end">
              <Select name="timeframe_unit" defaultValue="minute" required>
                <SelectTrigger className="border-0 border-l rounded-none">
                  <SelectValue placeholder="Select" />
                </SelectTrigger>
                <SelectContent className="">
                  <SelectItem value="second">Second</SelectItem>
                  <SelectItem value="minute">Minute</SelectItem>
                  <SelectItem value="hour">Hour</SelectItem>
                  <SelectItem value="day">Day</SelectItem>
                  <SelectItem value="week">Week</SelectItem>
                  <SelectItem value="month">Month</SelectItem>
                </SelectContent>
              </Select>
            </InputGroupAddon>
          </InputGroup>
        </div>
      </div>

      {selectedMarket === 'OPTIONS' ? (
        <div className="grid gap-2">
           <Label htmlFor="duration" className="gap-1">Duration<span className="text-primary">*</span></Label>
           <InputGroup>
             <InputGroupInput type="number" required id="duration" name="duration" min="1" step="1" defaultValue={initialData?.duration} placeholder="0" />
             <InputGroupAddon align="inline-end">
               <InputGroupText>Sec</InputGroupText>
             </InputGroupAddon>
           </InputGroup>
        </div>
      ) : (
        <>
          <div className="grid grid-cols-2 gap-3">
            <div className="grid gap-2">
              <Label htmlFor="take_profit">Take Profit</Label>
              <InputGroup>
                <InputGroupInput type="number" id="take_profit" name="take_profit" defaultValue={initialData?.takeProfit} min="0" step="0.01" placeholder="0.00" className="pl-1!" />
                {/* <InputGroupAddon align="inline-end">
                  <InputGroupText>USD</InputGroupText>
                </InputGroupAddon> */}
              </InputGroup>
            </div>
            
            <div className="grid gap-2">
              <Label htmlFor="stop_loss">Stop Loss</Label>
              <InputGroup>
                <InputGroupInput type="number" id="stop_loss" name="stop_loss" defaultValue={initialData?.stopLoss} min="0" step="0.01" placeholder="0.00" className="pl-1!" />
                {/* <InputGroupAddon align="inline-end">
                  <InputGroupText>USD</InputGroupText>
                </InputGroupAddon> */}
              </InputGroup>
            </div>
          </div>
          
          <div className="grid grid-cols-2 gap-3">
            <div className="grid gap-2">
              <Label htmlFor="high">Highest Price</Label>
              <InputGroup>
                <InputGroupInput type="number" id="high" name="high" defaultValue={initialData?.highestPrice} min="0" step="0.00001" placeholder="0.00000" className="pl-1!" />
                {/* <InputGroupAddon align="inline-end">
                  <InputGroupText>USD</InputGroupText>
                </InputGroupAddon> */}
              </InputGroup>
            </div>
            
            <div className="grid gap-2">
              <Label htmlFor="low">Lowest Price</Label>
              <InputGroup>
                <InputGroupInput type="number" id="low" name="low" defaultValue={initialData?.lowestPrice} min="0" step="0.00001" placeholder="0.00000" className="pl-1!" />
                {/* <InputGroupAddon align="inline-end">
                  <InputGroupText>USD</InputGroupText>
                </InputGroupAddon> */}
              </InputGroup>
            </div>
          </div>
        </>
      )}

      <div className="">
        <h4 className="text-sm font-medium text-gray-900 mb-1">Executions</h4>
        <div className="grid gap-3">
          {executions.map((exec, index) => (
            <div key={exec.id} className="grid gap-4 p-3 border rounded-lg relative bg-gray-50/50">
              <div className="flex items-center justify-between">
                <span>Execution {index + 1}</span>
                {executions.length > 1 && (
                  <Button type="button" variant="ghost" size="sm" className="p-0! bg-transparent hover:bg-transparent hover:text-muted-foreground text-destructive" onClick={() => removeExecution(exec.id)}>
                    <Trash2 className="h-4 w-4" />
                    Remove
                  </Button>
                )}
              </div>
              <div className="grid gap-2">
                <Label htmlFor={`action-${exec.id}`}>Action</Label>
                <Select name={`action-${index}`} value={exec.action || (selectedMarket === 'OPTIONS' ? "CALL" : "BUY")} onValueChange={(val) => updateAction(index, val)}>
                  <SelectTrigger id={`action-${exec.id}`} className="w-full">
                    <SelectValue placeholder="Select" />
                  </SelectTrigger>
                  <SelectContent>
                    {selectedMarket === 'OPTIONS' ? (
                      <>
                        <SelectItem value="CALL">Call</SelectItem>
                        <SelectItem value="PUT">Put</SelectItem>
                      </>
                    ) : (
                      <>
                        <SelectItem value="BUY">Buy</SelectItem>
                        <SelectItem value="SELL">Sell</SelectItem>
                      </>
                    )}
                  </SelectContent>
                </Select>
              </div>
              <div className="grid grid-cols-2 gap-3">
                <div className="grid gap-2">
                  <Label>Date</Label>
                  <Popover open={openDtIndex === index} onOpenChange={(open) => setOpenDtIndex(open ? index : null)}>
                    <PopoverTrigger asChild>
                      <Button variant="outline" className="justify-between font-normal">
                        {exec.date ? format(exec.date, 'P') : "Select date"}
                        <ChevronDownIcon />
                      </Button>
                    </PopoverTrigger>
                    <PopoverContent className="w-auto overflow-hidden p-0" align="start">
                      <Calendar mode="single" selected={exec.date} onSelect={(date) => { updateDate(index, date); setOpenDtIndex(null); }} disabled={(date) => date > new Date()} />
                    </PopoverContent>
                  </Popover>
                  <input type="hidden" name={`date-${index}`} value={exec.date ? exec.date.toISOString() : ''} />
                </div>
                <div className="grid gap-2">
                  <Label>Time</Label>
                  <Input type="time" name={`time-${index}`} step="1" defaultValue={exec.date ? format(exec.date, 'HH:mm:ss') : ''} />
                </div>
              </div>
              <div className="grid grid-cols-2 gap-3">
                <div className="grid gap-2">
                  <Label>Volume</Label>
                  <Input name={`volume-${index}`} type="number" min="0.01" step="0.01" defaultValue={exec.shares} placeholder="0" />
                </div>
                <div className="grid gap-2">
                  <Label>Price</Label>
                  <Input required name={`price-${index}`} type="number" min="0" step="0.00001" defaultValue={exec.price} placeholder="0.00001" />
                </div>
              </div>
              
              <div className="grid gap-2">
                <Label>Fees</Label>
                <Input required name={`fees-${index}`} type="number" step="0.01" defaultValue={exec.fees} placeholder="0.00" />
              </div>

              {(index === executions.length - 1) && (
                <div className="grid gap-2">
                  <Label>Profit/Loss</Label>
                  <Input required name={`pl-${index}`} type="number" step="0.01" defaultValue={exec.pl} placeholder="0.00" />
                </div>
              )}
            </div>
          ))}
        </div>
        {selectedMarket !== 'OPTIONS' && <Button type="button" variant="secondary" size="sm" className="w-full mt-4" onClick={addExecution}>
          <Plus className="mr-1 h-4 w-4" />
          Add Execution
        </Button>}
      </div>
    
      <div className="grid gap-2">
        <Label htmlFor="comments">Comments</Label>
        <Textarea className="max-h-50" placeholder="Type here..." id="comments" name="comments" rows={4} defaultValue={initialData?.comment || ""} />
      </div>
    </div>
  )
}