"use client";

import { useState, useMemo, useCallback } from "react";
import type { Order } from "@/types/models";
import { cn } from "@/lib/utils";
import { Wallet, Info } from "lucide-react";

type OrderSide = "buy" | "sell";
type OrderType = "limit" | "market" | "stop";

interface OrderFormProps {
  symbols: string[];
  selectedSymbol: string;
  onSymbolChange: (symbol: string) => void;
  availableBalance: number;
  currentPrice: number;
  onSubmitOrder: (
    order: Omit<Order, "id" | "status" | "timestamp" | "filledQuantity">,
  ) => void;
}

export function OrderForm({
  symbols,
  selectedSymbol,
  onSymbolChange,
  availableBalance,
  currentPrice,
  onSubmitOrder,
}: OrderFormProps) {
  const [side, setSide] = useState<OrderSide>("buy");
  const [orderType, setOrderType] = useState<OrderType>("limit");
  const [price, setPrice] = useState<string>(currentPrice.toFixed(2));
  const [stopPrice, setStopPrice] = useState<string>("");
  const [quantity, setQuantity] = useState<string>("");
  const [isSubmitting, setIsSubmitting] = useState(false);

  const effectivePrice = useMemo(() => {
    if (orderType === "market") return currentPrice;
    const parsed = parseFloat(price);
    return isNaN(parsed) ? 0 : parsed;
  }, [orderType, currentPrice, price]);

  const total = useMemo(() => {
    const qty = parseFloat(quantity) || 0;
    return qty * effectivePrice;
  }, [quantity, effectivePrice]);

  const maxQuantity = useMemo(() => {
    if (effectivePrice <= 0) return 0;
    return availableBalance / effectivePrice;
  }, [availableBalance, effectivePrice]);

  const handleSetPercentage = (percentage: number) => {
    const qty = (maxQuantity * percentage) / 100;
    setQuantity(qty.toFixed(6));
  };

  const handleSubmit = useCallback(async () => {
    const qty = parseFloat(quantity);
    const prc = parseFloat(price);

    if (isNaN(qty) || qty <= 0) return alert("数量无效");
    if (orderType !== "market" && (isNaN(prc) || prc <= 0))
      return alert("价格无效");

    setIsSubmitting(true);
    try {
      await onSubmitOrder({
        symbol: selectedSymbol,
        side,
        type: orderType,
        quantity: qty,
        price: orderType === "market" ? undefined : prc,
        total: qty * (orderType === "market" ? currentPrice : prc),
      });
      setQuantity("");
    } finally {
      setIsSubmitting(false);
    }
  }, [
    quantity,
    price,
    orderType,
    side,
    selectedSymbol,
    currentPrice,
    onSubmitOrder,
  ]);

  return (
    <div className="flex flex-col">
      <div className="space-y-5">
        {/* Buy/Sell Switch */}
        <div className="flex p-1 bg-[#2c2c2c]/30 rounded-xl">
          <button
            onClick={() => setSide("buy")}
            className={cn(
              "flex-1 py-3 rounded-lg text-xs font-black uppercase tracking-widest transition-all",
              side === "buy"
                ? "bg-[#00ffcc] text-[#121212] shadow-lg"
                : "text-[#666666] hover:text-[#e1e1e1]",
            )}
          >
            买入 / 做多
          </button>
          <button
            onClick={() => setSide("sell")}
            className={cn(
              "flex-1 py-3 rounded-lg text-xs font-black uppercase tracking-widest transition-all",
              side === "sell"
                ? "bg-[#ff5252] text-[#e1e1e1] shadow-lg"
                : "text-[#666666] hover:text-[#e1e1e1]",
            )}
          >
            卖出 / 做空
          </button>
        </div>

        {/* Symbol & Type */}
        <div className="grid grid-cols-2 gap-3">
          <div className="space-y-2">
            <label className="text-[9px] font-black text-[#666666] uppercase tracking-widest ml-1">
              交易对
            </label>
            <select
              value={selectedSymbol}
              onChange={(e) => onSymbolChange(e.target.value)}
              className="w-full bg-[#2c2c2c]/30 border border-[#2c2c2c] rounded-xl px-3 py-2.5 text-xs font-bold text-[#e1e1e1] focus:border-[#00ffcc] focus:outline-none appearance-none cursor-pointer"
            >
              {symbols.map((s) => (
                <option key={s} value={s}>
                  {s}
                </option>
              ))}
            </select>
          </div>
          <div className="space-y-2">
            <label className="text-[9px] font-black text-[#666666] uppercase tracking-widest ml-1">
              类型
            </label>
            <select
              value={orderType}
              onChange={(e) => setOrderType(e.target.value as any)}
              className="w-full bg-[#2c2c2c]/30 border border-[#2c2c2c] rounded-xl px-3 py-2.5 text-xs font-bold text-[#e1e1e1] focus:border-[#00ffcc] focus:outline-none appearance-none cursor-pointer"
            >
              <option value="limit">限价</option>
              <option value="market">市价</option>
              <option value="stop">止损</option>
            </select>
          </div>
        </div>

        {/* Inputs */}
        <div className="space-y-4">
          {orderType !== "market" && (
            <div className="space-y-2">
              <label className="text-[9px] font-black text-[#666666] uppercase tracking-widest ml-1">
                委托价格
              </label>
              <div className="relative">
                <input
                  type="text"
                  value={price}
                  onChange={(e) => setPrice(e.target.value)}
                  className="w-full bg-[#2c2c2c]/30 border border-[#2c2c2c] rounded-xl pl-4 pr-12 py-3 text-sm font-black text-[#e1e1e1] focus:border-[#00ffcc] focus:outline-none transition-all"
                  placeholder="0.00"
                />
                <span className="absolute right-4 top-1/2 -translate-y-1/2 text-[10px] font-black text-[#666666]">
                  USD
                </span>
              </div>
            </div>
          )}

          <div className="space-y-2">
            <label className="text-[9px] font-black text-[#666666] uppercase tracking-widest ml-1">
              数量
            </label>
            <div className="relative">
              <input
                type="text"
                value={quantity}
                onChange={(e) => setQuantity(e.target.value)}
                className="w-full bg-[#2c2c2c]/30 border border-[#2c2c2c] rounded-xl pl-4 pr-12 py-3 text-sm font-black text-[#e1e1e1] focus:border-[#00ffcc] focus:outline-none transition-all"
                placeholder="0.0000"
              />
              <span className="absolute right-4 top-1/2 -translate-y-1/2 text-[10px] font-black text-[#666666] uppercase">
                {selectedSymbol.replace("USDT", "")}
              </span>
            </div>
            <div className="flex gap-1.5 mt-2">
              {[25, 50, 75, 100].map((p) => (
                <button
                  key={p}
                  onClick={() => handleSetPercentage(p)}
                  className="flex-1 py-1.5 rounded-lg border border-[#2c2c2c] text-[9px] font-black text-[#666666] hover:text-[#00ffcc] hover:border-[#00ffcc] transition-all"
                >
                  {p}%
                </button>
              ))}
            </div>
          </div>
        </div>

        {/* Balance Info */}
        <div className="bg-[#2c2c2c]/20 p-4 rounded-xl space-y-2">
          <div className="flex justify-between items-center">
            <span className="text-[9px] font-black text-[#666666] uppercase tracking-widest flex items-center gap-1">
              <Wallet className="w-3 h-3" /> 可用余额
            </span>
            <span className="text-xs font-black text-[#e1e1e1]">
              ${availableBalance.toLocaleString()}
            </span>
          </div>
          <div className="flex justify-between items-center border-t border-[#2c2c2c]/50 pt-2">
            <span className="text-[9px] font-black text-[#666666] uppercase tracking-widest flex items-center gap-1">
              <Info className="w-3 h-3" /> 预估金额
            </span>
            <span className="text-sm font-black text-[#00ffcc] italic tracking-tighter">
              ${total.toLocaleString(undefined, { minimumFractionDigits: 2 })}
            </span>
          </div>
        </div>
      </div>

      <button
        onClick={handleSubmit}
        disabled={isSubmitting}
        className={cn(
          "w-full py-4 mt-6 rounded-xl text-xs font-black uppercase tracking-widest transition-all shadow-xl disabled:opacity-30",
          side === "buy"
            ? "bg-[#00ffcc] text-[#121212] hover:bg-[#00e6b8]"
            : "bg-[#ff5252] text-[#e1e1e1] hover:bg-[#ff1a1a]",
        )}
      >
        {isSubmitting ? "提交中..." : `${side === "buy" ? "买入" : "卖出"}`}
      </button>
    </div>
  );
}
