// src/components/trade/TradeBuy.tsx
import {
 IonCard,
 IonCardHeader,
 IonCardTitle,
 IonCardContent,
 IonInput,
 IonItem,
 IonLabel,
 IonButton,
 IonText,
 IonGrid,
 IonRow,
 IonCol,
 useIonRouter,
 IonSegment,
 IonSelect,
 IonSegmentButton,
 IonSelectOption,
 IonIcon,
} from "@ionic/react";
import { copyOutline } from "ionicons/icons";
import QRcode from "../../../components/Qrcode";

import { useState } from "react";
import { Context } from "../../../context/contex";
import { shortenAddress, hasCurrency } from "../../../utils/index";
type BuyCryptoProps = {
 context: NonNullable<React.ContextType<typeof Context>>;
};
interface TokenDetails {
 currency: string;
 balance: number;
 chain: string;
 deposit_address: string;
}

const tokensDeposit = [
 { 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", "erc20"] },
 { name: "USDT", symbol: "usdt", chains: ["bep20", "erc20", "trc20"] },
];
const Deposit: React.FC<BuyCryptoProps> = ({ context }) => {
 const {
  userInfo,
 
  userWallets,
apiRequest,
  copy,
 } = context;
 const [tokenDetails, setTokenDetails] = useState<TokenDetails | null>(null);


 const [amount, setAmount] = useState("");
 const router = useIonRouter();

const useTrc = (array: any) => {
  let t = null;
  const f = array.find((t: any) => t.currency == 'usdt' && t.network == "trc20");
  if(f){
    t = f.address;
  }
  return t;
}
type Wallet = {
  currency: string;
  network: string;
  address?: string;
};

const getTrc20UsdtAddress = (wallets: Wallet[]): string | null => {
  const found = wallets.find(
    w => w.currency === "usdt" && w.network === "trc20"
  );

  return found?.address ?? null;
};

 const getQuidaxWalletBalance = async (token: string, chain: string) => {
  if (!userInfo) {
   router.push("/login", "forward", "replace");
   return;
  }
  setTokenDetails(null);
  setAmount("");

   const data = await apiRequest(
  "POST",
  "", //url
  {
 action: "get_quidax_single_wallet",
     id: userInfo.id.toString(),
     token: token,
     chain: chain,
  },
  true,       // require auth
  false    // show success or error messages
) as any;
if(data?.success){
  setTokenDetails(data.message);
}

 };

 return (
  <>
 
    <IonGrid>
     <IonRow className="ion-justify-content-center">
      <IonCol size="12" className="ion-text-center">
       <h2 className="ion-margin-bottom">Deposit Crypto Assets</h2>
      </IonCol>
      <IonCol size="12" sizeMd="8">
       <IonCard>
        <IonCardContent className="ion-text-center">
         <h5 className="ion-margin-bottom">
          Select the crypto token and chain to deposit
         </h5>

         {/* Token Selector */}
         <IonItem className="ion-margin-vertical ion-text-center">
          <IonSelect
           interface="action-sheet"
           placeholder="Choose token"
           onIonChange={(e) => {
            const [symbol, chain] = e.detail.value.split(":");
            getQuidaxWalletBalance(symbol, chain);
           }}
          >
           {tokensDeposit
            .filter(({ symbol }) => hasCurrency(userWallets, symbol))
            .flatMap(({ name, symbol, chains }) =>
             chains.map((chain) => (
              <IonSelectOption
               key={`deposit-${symbol}-${chain}`}
               value={`${symbol}:${chain}`}
              >
               {name} on {chain.toUpperCase()}
              </IonSelectOption>
             ))
            )}
          </IonSelect>
         </IonItem>

         {tokenDetails && Object.keys(tokenDetails).length > 0 && (
          <>
           <h3 className="ion-margin-top">
            {tokenDetails.currency.toUpperCase()} balance:{" "}
            {tokenDetails.balance}
           </h3>

           <IonCard className="ion-margin-top">
            <IonCardHeader className="ion-text-center">
             <IonCardTitle>
              {tokenDetails.currency.toUpperCase()} ({tokenDetails.chain})
              <br />
              Deposit Address
             </IonCardTitle>
            </IonCardHeader>
            <IonCardContent className="ion-text-center">
             <div className="ion-margin-bottom ion-justify-content-center">
              <QRcode text={tokenDetails.chain === "TRC20"
    ? getTrc20UsdtAddress(userWallets) ?? tokenDetails.deposit_address
    : tokenDetails.deposit_address} />
             </div>
             <p>
            {shortenAddress(
  tokenDetails.chain === "TRC20"
    ? getTrc20UsdtAddress(userWallets) ?? tokenDetails.deposit_address
    : tokenDetails.deposit_address
)}
{" "}
              <IonIcon
               icon={copyOutline}
               color="primary"
               style={{ cursor: "pointer" }}
               onClick={() => copy(tokenDetails.chain === "TRC20"
    ? getTrc20UsdtAddress(userWallets) ?? tokenDetails.deposit_address
    : tokenDetails.deposit_address)}
              />
             </p>
            </IonCardContent>
           </IonCard>
          </>
         )}
        </IonCardContent>
       </IonCard>
      </IonCol>
     </IonRow>
    </IonGrid>
  


  </>
 );
};

export default Deposit;
