import React from "react";
import { createRoot } from "react-dom/client";
import { WalletModal } from "./components/WalletModal";
import {
  API_BASE_URL,
  getMultiRelayBuyQuote,
  getUserCryptoBalance,
  MultiRelayBuyQuoteParams,
  OutputDetails,
  BalanceResponse,
} from "./services/services";

interface Token {
  chainIds: {
    chainId: number;
    address: string;
  }[];
  tokenAddress: string;
  amount?: string;
  icon?: string;
  symbol: string;
  name: string;
  decimals: number;
}

interface swapToken {
  amount?: string;
  chainId: number;
  tokenAddress: string;
}

interface SwapParams {
  fromToken: swapToken;
  toToken: Omit<swapToken, "amount">;
}

class WalletSDK {
  private modalContainer: HTMLDivElement | null = null;
  private root: any = null;
  private walletSDKKey: string;
  private userSession: any = null;

  constructor(walletSDKKey: string) {
    this.walletSDKKey = walletSDKKey;
    // Create a container for the modal if it doesn't exist
    if (!document.getElementById("wallet-sdk-modal")) {
      this.modalContainer = document.createElement("div");
      this.modalContainer.id = "wallet-sdk-modal";
      document.body.appendChild(this.modalContainer);
    }

    // Inject the Inter font and styles
    this.injectStyles();

    // Try to restore session from localStorage
    if (typeof window !== "undefined") {
      const saved = localStorage.getItem("enclave_wallet_login");
      if (saved) {
        const parsed = JSON.parse(saved);
        this.userSession = parsed;
      }
    }
    // Set global reference for modal to update session
    (window as any).__walletSDKInstance = this;
  }

  private injectStyles() {
    // Add Google Fonts link
    const linkElement = document.createElement("link");
    linkElement.rel = "stylesheet";
    linkElement.href =
      "https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap";
    document.head.appendChild(linkElement);

    // Add our custom styles
    const styleElement = document.createElement("style");
    styleElement.textContent = `
      * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
        font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
      }

      body {
        font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
      }
    `;
    document.head.appendChild(styleElement);
  }

  // Method to get buy quote from multi relay using the services function
  async getMultiRelayBuyQuote(
    params: MultiRelayBuyQuoteParams
  ): Promise<OutputDetails | string> {
    return getMultiRelayBuyQuote(params, this.walletSDKKey);
  }

  setUserSession(session: any) {
    this.userSession = session;
  }

  // async getUserBalance(): Promise<BalanceResponse | null> {
  //   if (!this.userSession?.result?.username) return null;
  //   return getUserBalance(this.userSession.result.username, this.walletSDKKey);
  // }

  async getUserCryptoBalance(): Promise<BalanceResponse | null> {
    if (!this.userSession?.result?.username) return null;
    return getUserCryptoBalance(
      this.userSession.result.username,
      this.walletSDKKey
    );
  }

  getWalletAddress() {
    return this.userSession?.result?.wallet?.scw_address || null;
  }

  getUsername() {
    return this.userSession?.result?.username || null;
  }

  logout() {
    // Clear the session
    this.userSession = null;
    // Remove from localStorage
    if (typeof window !== "undefined") {
      localStorage.removeItem("enclave_wallet_login");
    }
    // Unmount the modal if it's open
    if (this.root) {
      this.root.unmount();
      this.root = null;
    }
  }

  openWalletModal(swapParams?: SwapParams) {
    if (!this.modalContainer) {
      this.modalContainer = document.getElementById(
        "wallet-sdk-modal"
      ) as HTMLDivElement;
    }

    const handleClose = () => {
      if (this.root) {
        this.root.unmount();
        this.root = null;
      }
    };

    // Create root if it doesn't exist
    if (!this.root) {
      this.root = createRoot(this.modalContainer!);
    }

    // Render the modal and pass walletSDKKey and swapParams
    this.root.render(
      <WalletModal
        isOpen={true}
        onClose={handleClose}
        walletSDKKey={this.walletSDKKey}
        swapParams={swapParams}
      />
    );
  }

  swap(params: SwapParams) {
    if (!this.userSession?.result?.username) {
      // If not logged in, open modal with swap params
      this.openWalletModal(params);
      return;
    }
    // If logged in, directly open modal with swap params
    this.openWalletModal(params);
  }
}

export default WalletSDK;
