// src/components/trade/TradeBuy.tsx
import {
  IonCard,
  IonCardContent,
  IonInput,
  IonItem,
  IonLabel,
  IonButton,
  IonGrid,
  IonRow,
  IonCol,
  useIonRouter,
  IonSelect,
  IonSelectOption,
  IonIcon,
} from "@ionic/react";
import { alertCircle, copyOutline } from "ionicons/icons";
import { useState, useEffect } from "react";
import { Context } from "../../../context/contex";
import {
  formatNumber,
  hasCurrencyAndNetwork,
  shortenAddress,
} from "../../../utils/index";

type BuyCryptoProps = {
  context: NonNullable<React.ContextType<typeof Context>>;
};

interface TokenDetails {
  currency: string;
  balance: number;
  chain: string;
  deposit_address: string;
}

const tokens = [
  { name: "Bitcoin", symbol: "btc", chains: ["btc"] },
  { name: "Litecoin", symbol: "ltc", chains: ["ltc"] },
  { name: "Ethereum", symbol: "eth", chains: ["erc20", "bep20"] },
  { name: "Solana", symbol: "sol", chains: ["bep20"] },
  { name: "USDC", symbol: "usdc", chains: ["bep20", "trc20", "erc20"] },
  { name: "USDT", symbol: "usdt", chains: ["bep20", "trc20", "erc20"] },
];

const tokenIcons: Record<string, string> = {
  btc: "₿",
  ltc: "Ł",
  eth: "Ξ",
  sol: "◎",
  usdc: "$",
  usdt: "₮",
};



const Buy: React.FC<BuyCryptoProps> = ({ context }) => {
  const {
    userInfo,
    setBusy,
    getUserInfo,
    userWallets,
    userWalletsGroup,
    quidaxBalance,
    reportLowBalance,
    presentToast,
    copy,
    storage,
    apiRequest,
  } = context;

  const [tradeType, setTradeType] = useState<string>("buy");
  const [token, setToken] = useState("");
  const [tokenDetails, setTokenDetails] = useState<TokenDetails | null>(null);
  const [wallet, setWallet] = useState("");
  const [pin, setPin] = useState<number | string>("");
  const [amount, setAmount] = useState("");
  const [quote, setQuote] = useState<any>({});
  const [selectedBuyToken, setSelectedBuyToken] = useState<string>("");
  const router = useIonRouter();

  const placeOrder = async (
    pin: number,
    pay: string,
    receive: string,
    amount: number
  ) => {
    if (!userInfo) { router.push("/login", "forward", "replace"); return; }
    if (userInfo?.quidax_id === null) return presentToast("top", "You must enable crypto features on your account.", () => null, "danger", alertCircle);
    if (userInfo?.tx_pin === null) return presentToast("top", "Please set a transaction PIN", () => null, "danger", alertCircle);
    if (+pin !== +userInfo.tx_pin) return presentToast("top", "Incorrect PIN!", () => null, "danger", alertCircle);
    if (!amount || +amount <= 0) return presentToast("top", "Please enter an amount.", () => null, "danger", alertCircle);
    if (tradeType === "buy" && +userInfo?.ngn_balance < +amount) return presentToast("top", "Insufficient funds", () => null, "danger", alertCircle);
    if (tradeType === "buy" && +quidaxBalance < +amount) {
      await reportLowBalance(+amount, "Quidax", quidaxBalance);
      return presentToast("top", "There has been an error with this purchase and our team has been notified. They are working on it currently. Please try again in about 5 minutes time.", () => null, "danger", alertCircle);
    }
    setToken(receive);
    setQuote({});
    const data = await apiRequest("POST", "", {
      action: "get_buy_order_quote",
      id: userInfo?.id.toString(),
      amount: amount.toString(),
      bid: pay,
      ask: receive,
      type: tradeType,
    }, true, false) as any;
   // console.log(data)
    if (data?.success) setQuote(data?.message);
    else presentToast("top", 'Failed to get quote. Amount might be too small.', () => null, "danger", alertCircle);
  };

  useEffect(() => {
    let interval: any;
    if (quote && Object.keys(quote).length > 0) {
      const pay = tradeType === "buy" ? "ngn" : quote?.from_currency.toLowerCase();
      const receive = quote?.to_currency.toLowerCase();
      interval = setInterval(() => { placeOrder(+pin, pay, receive, +amount); }, 10000);
    }
    return () => clearInterval(interval);
  }, [quote, amount]);

const confirmOrder = async () => {
  if (!userInfo) {
    router.push("/login", "forward", "replace");
    return;
  }

  if (!quote || !quote.id) {
    presentToast("top", "Invalid order.", () => null, "danger", alertCircle);
    return;
  }

  if (tradeType === "sell") {
    const amount = Number(quote?.to_amount || 0);
    const kycLevel = Number(userInfo?.kyc || 0);

    if (amount < 5000) {
      presentToast(
        "top",
        "Minimum crypto to sell must be 5000 Naira and above.",
        () => null,
        "danger",
        alertCircle
      );
      return;
    }

    if (kycLevel === 0 && amount > 2000000) {
      presentToast(
        "top",
        "Maximum crypto to sell must not be more than 2 million Naira. Contact support to increase your limit.",
        () => null,
        "danger",
        alertCircle
      );
      return;
    }

    if (kycLevel >= 1 && amount > 10000000) {
      presentToast(
        "top",
        "Maximum crypto to sell must not be more than 10 million Naira. Contact support for custom limits.",
        () => null,
        "danger",
        alertCircle
      );
      return;
    }
  }

  try {
    const data = await apiRequest(
      "POST",
      "",
      {
        action: "confirm_instant_order",
        order_id: quote.id,
        amount: quote.from_amount,
        receive: quote.to_amount,
        currency: quote.to_currency,
        type: tradeType,
        email: userInfo.email,
        wallet: userInfo.quidax_id,
      },
      true,
      true
    ) as any;

    if (data?.success) {
      setQuote({});
      setTokenDetails(null);
      setAmount("");
      await getUserInfo();
    } else {
      presentToast("top", data?.message || "Order failed", () => null, "danger");
    }
  } catch (error) {
    presentToast("top", "Something went wrong", () => null, "danger");
  }
};

  const cancelOrder = () => {
    setWallet("");
    setAmount("");
    setQuote({});
    setTokenDetails(null);
    setPin("");
    setSelectedBuyToken("");
  };

  const getQuidaxWalletBalance = async (token: string, chain: string) => {
    if (!userInfo) { router.push("/login", "forward", "replace"); return; }
    setTokenDetails(null);
    setAmount("");
    const t = await storage?.get("vin_auth_token");
    setBusy(true);
    const data = await apiRequest("POST", "", {
      action: "get_quidax_single_wallet",
      id: userInfo.id.toString(),
      token,
      chain,
    }, true, false) as any;
    if (data?.success) setTokenDetails(data?.message);
  };

  const hasQuote = Object.keys(quote).length > 0;

  return (
    <>

      <div className="vtx-page">

        {/* Header */}
        <div className="vtx-header">
          <div className="vtx-eyebrow">Instant Exchange</div>
          <h2 className="vtx-title">Trade Crypto with Naira</h2>
          <p className="vtx-subtitle">Real-time quotes · Instant settlement</p>
        </div>

        {/* Tab switcher */}
        <div className="vtx-tab-row">
          <IonButton
            expand="block"
            className={tradeType === "buy" ? "vtx-btn-buy-on" : "vtx-btn-buy-off"}
            onClick={() => { setTradeType("buy"); cancelOrder(); }}
          >
            ↗ Buy
          </IonButton>
          <IonButton
            expand="block"
            className={tradeType === "sell" ? "vtx-btn-sell-on" : "vtx-btn-sell-off"}
            onClick={() => { setTradeType("sell"); cancelOrder(); }}
          >
            ↙ Sell
          </IonButton>
        </div>

        {/* ═══ BUY PANEL ═══ */}
        {tradeType === "buy" && (
          <IonCard className="vtx-card">
            <IonCardContent>
              <div className="vtx-panel-head">
                <span className="vtx-panel-title">Buy Order</span>
                <span className="vtx-badge vtx-badge-buy">NGN → Crypto</span>
              </div>

              <div className="vtx-form-pad">
                <IonGrid>
                  <IonRow>
                    {/* PIN */}
                    <IonCol size="12" sizeMd="4">
                      <IonItem lines="none" className="vtx-item">
                        <IonLabel position="stacked">🔐 Transaction PIN</IonLabel>
                        <IonInput
                          type="password"
                          maxlength={4}
                          placeholder="••••"
                          value={pin}
                          onIonInput={(e) => setPin(e.detail.value!)}
                        />
                      </IonItem>
                    </IonCol>

                    {/* Amount */}
                    <IonCol size="12" sizeMd="4">
                      <IonItem lines="none" className="vtx-item">
                        <IonLabel position="stacked">Amount to Spend</IonLabel>
                        <IonInput
                          type="number"
                          min="0"
                          placeholder="0.00"
                          value={amount}
                          onIonInput={(e) => setAmount(e.detail.value!)}
                        />
                      </IonItem>
                      <div className="vtx-bal-hint">
                        Balance:&nbsp;<span className="vtx-bal-val">{formatNumber(userInfo?.ngn_balance)}</span>&nbsp;NGN
                      </div>
                    </IonCol>

                    {/* Token */}
                    <IonCol size="12" sizeMd="4">
                      <IonItem lines="none" className="vtx-item">
                        <IonLabel position="stacked">Select Asset</IonLabel>
                        <IonSelect
                          placeholder="Choose token"
                          interface="popover"
                          value={selectedBuyToken}
                          onIonChange={(e) => { setSelectedBuyToken(e.detail.value); setQuote({}); }}
                        >
                          <IonSelectOption value="btc" disabled={!(userWalletsGroup as any)?.wallets.btc?.deposit_address}>₿ Bitcoin (BTC)</IonSelectOption>
                          <IonSelectOption value="ltc" disabled={!(userWalletsGroup as any)?.wallets.ltc?.deposit_address}>Ł Litecoin (LTC)</IonSelectOption>
                          <IonSelectOption value="eth" disabled={!(userWalletsGroup as any)?.wallets.eth?.deposit_address}>Ξ Ethereum (ETH)</IonSelectOption>
                          <IonSelectOption value="sol" disabled={!(userWalletsGroup as any)?.wallets.sol?.deposit_address}>◎ Solana (SOL)</IonSelectOption>
                          <IonSelectOption value="usdt" disabled={!(userWalletsGroup as any)?.wallets.usdt?.deposit_address}>₮ Tether (USDT)</IonSelectOption>
                          <IonSelectOption value="usdc" disabled={!(userWalletsGroup as any)?.wallets.usdc?.deposit_address}>$ USD Coin (USDC)</IonSelectOption>
                        </IonSelect>
                      </IonItem>
                    </IonCol>
                  </IonRow>
                </IonGrid>

                <IonButton
                  expand="block"
                  className="vtx-quote-btn"
                  disabled={!selectedBuyToken || !amount || +amount <= 0}
                  onClick={() => placeOrder(+pin, "ngn", selectedBuyToken, +amount)}
                >
                  Get Live Quote →
                </IonButton>
              </div>

              {/* Quote */}
              {hasQuote && (
                <>
                  <div className="vtx-divider" />
                  <IonCard className="vtx-quote-card">
                    <IonCardContent>
                      <div className="vtx-quote-head">
                        <div className="vtx-pulse" />
                        <span className="vtx-quote-head-text">Live Quote · Refreshes every 10s</span>
                      </div>
                      {quote.to_currency !== "USDT" && (
                        <div className="vtx-quote-row">
                          <span className="vtx-qlabel">{quote.to_currency} Price</span>
                          <span className="vtx-qval">1 {quote.to_currency} = {formatNumber(quote.quoted_price)} {quote.quoted_currency}</span>
                        </div>
                      )}
                      <div className="vtx-quote-row">
                        <span className="vtx-qlabel">USD Rate</span>
                        <span className="vtx-qval">1 USD = ₦{formatNumber(quote.usd_rate)}</span>
                      </div>
                      <div className="vtx-quote-row">
                        <span className="vtx-qlabel">You Pay</span>
                        <span className="vtx-qval">{formatNumber(quote.from_amount)} {quote.from_currency}</span>
                      </div>
                      <div className="vtx-quote-row vtx-quote-row-receive">
                        <span className="vtx-qlabel">You Receive</span>
                        <span className="vtx-qval">{quote.to_amount.toFixed(6)} {quote.to_currency}</span>
                      </div>
                      <div className="vtx-quote-actions">
                        <IonButton expand="block" className="vtx-btn-confirm" onClick={confirmOrder}>✓ Confirm</IonButton>
                        <IonButton expand="block" fill="outline" className="vtx-btn-cancel" onClick={cancelOrder}>Cancel</IonButton>
                      </div>
                    </IonCardContent>
                  </IonCard>
                </>
              )}
            </IonCardContent>
          </IonCard>
        )}

        {/* ═══ SELL PANEL ═══ */}
        {tradeType === "sell" && (
          <IonCard className="vtx-card">
            <IonCardContent>
              <div className="vtx-panel-head">
                <span className="vtx-panel-title">Sell Order</span>
                <span className="vtx-badge vtx-badge-sell">Crypto → NGN</span>
              </div>

              <div className="vtx-form-pad">
                <IonGrid>
                  <IonRow>
                    {/* PIN */}
                    <IonCol size="12" sizeMd="6">
                      <IonItem lines="none" className="vtx-item">
                        <IonLabel position="stacked">🔐 Transaction PIN</IonLabel>
                        <IonInput
                          type="password"
                          maxlength={4}
                          placeholder="••••"
                          value={pin}
                          onIonInput={(e) => setPin(e.detail.value!)}
                        />
                      </IonItem>
                    </IonCol>

                    {/* Token select */}
                    <IonCol size="12" sizeMd="6">
                      <IonItem lines="none" className="vtx-item">
                        <IonLabel position="stacked">Select Token</IonLabel>
                        <IonSelect
                          placeholder="Choose asset to sell"
                          interface="popover"
                          onIonChange={(e) =>
                            getQuidaxWalletBalance(
                              e.detail.value.split("-")[0],
                              e.detail.value.split("-")[1]
                            )
                          }
                        >
                          {tokens.flatMap(({ name, symbol, chains }) =>
                            chains.map((chain) => (
                              <IonSelectOption
                                key={`sell-${symbol}-${chain}`}
                                value={`${symbol}-${chain}`}
                                disabled={!hasCurrencyAndNetwork(userWallets, symbol, chain)}
                              >
                                {tokenIcons[symbol]} {name} · {chain.toUpperCase()}
                              </IonSelectOption>
                            ))
                          )}
                        </IonSelect>
                      </IonItem>
                    </IonCol>
                  </IonRow>
                </IonGrid>
              </div>

              {/* Token detail */}
              {tokenDetails && (
                <>
                  <div className="vtx-divider" />
                  <IonCard className="vtx-token-card">
                    <IonCardContent>
                      <div className="vtx-token-top">
                        <div className="vtx-token-left">
                          <div className="vtx-tok-icon">
                            {tokenIcons[tokenDetails.currency.toLowerCase()] ?? tokenDetails.currency[0].toUpperCase()}
                          </div>
                          <div>
                            <div className="vtx-tok-name">{tokenDetails.currency.toUpperCase()}</div>
                            <div className="vtx-tok-chain">{tokenDetails.chain}</div>
                          </div>
                        </div>
                        <div className="vtx-tok-bal">
                          <div className="vtx-tok-bal-label">Available</div>
                          <div className="vtx-tok-bal-value">{tokenDetails.balance}</div>
                        </div>
                      </div>

                      <div className="vtx-addr-row">
                        <span className="vtx-addr-text">{shortenAddress(tokenDetails.deposit_address)}</span>
                        <IonButton fill="clear" size="small" className="vtx-copy-btn" onClick={() => copy(tokenDetails.deposit_address)}>
                          <IonIcon slot="start" icon={copyOutline} />
                          Copy
                        </IonButton>
                      </div>

                      <span className="vtx-amt-label">Amount to Sell</span>
                      <div className="vtx-amt-row">
                        <IonItem lines="none" className="vtx-item">
                          <IonInput
                            type="number"
                            placeholder="0.00"
                            value={amount}
                            onIonInput={(e) => setAmount(e.detail.value!)}
                          />
                        </IonItem>
                        <IonButton className="vtx-max-btn" onClick={() => setAmount(String(tokenDetails.balance))}>
                          MAX
                        </IonButton>
                      </div>

                      <IonButton
                        expand="block"
                        className="vtx-quote-btn"
                        disabled={tokenDetails.balance === 0}
                        onClick={() => placeOrder(+pin, tokenDetails.currency, "ngn", +amount)}
                      >
                        Get Live Quote →
                      </IonButton>
                    </IonCardContent>
                  </IonCard>
                </>
              )}

              {/* Quote */}
              {hasQuote && (
                <>
                  <div className="vtx-divider" />
                  <IonCard className="vtx-quote-card vtx-sell-quote">
                    <IonCardContent>
                      <div className="vtx-quote-head vtx-sell-head">
                        <div className="vtx-pulse vtx-sell-pulse" />
                        <span className="vtx-quote-head-text vtx-sell-text">Sale Quote · Refreshes every 10s</span>
                      </div>
                      <div className="vtx-quote-row">
                        <span className="vtx-qlabel">USD Rate</span>
                        <span className="vtx-qval">₦{formatNumber(quote.usd_rate)}</span>
                      </div>
                      <div className="vtx-quote-row">
                        <span className="vtx-qlabel">You Sell</span>
                        <span className="vtx-qval">{formatNumber(quote.from_amount, 6)} {quote.from_currency}</span>
                      </div>
                      <div className="vtx-quote-row vtx-quote-row-receive">
                        <span className="vtx-qlabel">You Receive</span>
                        <span className="vtx-qval">₦{formatNumber(quote.to_amount)}</span>
                      </div>
                      <div className="vtx-quote-actions">
                        <IonButton expand="block" className="vtx-btn-confirm" onClick={confirmOrder}>✓ Confirm Sale</IonButton>
                        <IonButton expand="block" fill="outline" className="vtx-btn-cancel" onClick={cancelOrder}>Cancel</IonButton>
                      </div>
                    </IonCardContent>
                  </IonCard>
                </>
              )}
            </IonCardContent>
          </IonCard>
        )}

      </div>
    </>
  );
};

export default Buy;