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";
import { WalletSDKConfig, ThemeMode, CornerRadius } from "./types/theme";

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;
  private config: WalletSDKConfig;

  constructor(walletSDKKey: string, config: WalletSDKConfig = {}) {
    this.walletSDKKey = walletSDKKey;

    // Try to get theme from localStorage first, then use config, then default to "light"
    let savedTheme: ThemeMode = "light";
    if (typeof window !== "undefined") {
      const storedTheme = localStorage.getItem("sdkTheme");
      if (storedTheme && (storedTheme === "light" || storedTheme === "dark")) {
        savedTheme = storedTheme as ThemeMode;
      } else if (config.theme) {
        savedTheme = config.theme;
      }
    } else if (config.theme) {
      savedTheme = config.theme;
    }

    // Try to get cornerRadius from localStorage first, then use config, then default to "medium"
    let savedCornerRadius: CornerRadius = "medium";
    if (typeof window !== "undefined") {
      const storedCornerRadius = localStorage.getItem("sdkCornerRadius");
      if (
        storedCornerRadius &&
        (storedCornerRadius === "small" ||
          storedCornerRadius === "medium" ||
          storedCornerRadius === "large")
      ) {
        savedCornerRadius = storedCornerRadius as CornerRadius;
      } else if (config.cornerRadius) {
        savedCornerRadius = config.cornerRadius;
      }
    } else if (config.cornerRadius) {
      savedCornerRadius = config.cornerRadius;
    }

    this.config = {
      theme: savedTheme,
      cornerRadius: savedCornerRadius,
      ...config,
    };

    // Save both theme and cornerRadius to localStorage
    if (typeof window !== "undefined") {
      localStorage.setItem("sdkTheme", this.config.theme || "light");
      localStorage.setItem(
        "sdkCornerRadius",
        this.config.cornerRadius || "medium"
      );
    }

    console.log("savedTheme", this.config.theme);

    // 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 = `
      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 update theme dynamically
  setTheme(theme: ThemeMode) {
    this.config.theme = theme;
    if (typeof window !== "undefined") {
      localStorage.setItem("sdkTheme", theme);
    }
  }

  // Method to update cornerRadius dynamically
  setCornerRadius(cornerRadius: CornerRadius) {
    this.config.cornerRadius = cornerRadius;
    if (typeof window !== "undefined") {
      localStorage.setItem("sdkCornerRadius", cornerRadius);
    }
  }

  // Method to get current theme
  getTheme(): ThemeMode {
    return this.config.theme || "light";
  }

  // Method to get current cornerRadius
  getCornerRadius(): CornerRadius {
    return this.config.cornerRadius || "medium";
  }

  // 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;
  }

  getUserSession() {
    return this.userSession.result;
  }

  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) {
      console.log("modalContainer!!!!!!!", this.config.cornerRadius);

      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, swapParams, theme, and cornerRadius
    this.root.render(
      <WalletModal
        isOpen={true}
        onClose={handleClose}
        walletSDKKey={this.walletSDKKey}
        swapParams={swapParams}
        theme={this.config.theme}
        cornerRadius={this.config.cornerRadius}
      />
    );
  }

  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;
