import React, { useEffect, useState } from "react";
import { formatUnits } from "ethers";
import {
  ArrowUp,
  ShoppingCart,
  Tag,
  ArrowLeftRight,
  CircleUserRound,
  QrCode,
  ChevronDown,
  LogOut,
  Send,
  HandCoins,
} from "lucide-react";
import { QRNetworks } from "../ui/QRNetworks";
import Activity from "../Activity/Activity";
import Spinner from "../ui/Spinner";
import { useWallet } from "../WalletProvider";
import { TokenLogo } from "../ui/TokenLogo";
import { borderRadiusStyles, ThemeMode, themeStyles } from "../../types/theme";

interface ChainBalance {
  chainId: number;
  address: string;
  balance: string;
}

interface TokenBalance {
  name: string;
  symbol: string;
  decimals: number;
  balance: string;
  amount: number;
  chainIds: ChainBalance[];
  logoURI: string;
  valueUsd?: number;
  priceUsd?: number;
  priceChangePercentage24h?: number;
  valueChange24h?: number;
}

interface BalanceResponse {
  success: boolean;
  data: TokenBalance[];
}

interface Asset {
  name: string;
  icon: string;
  amount: string;
  valueUSD: string;
  symbol: string;
  priceUsd?: number;
  priceChange: number;
  type: "token" | "crypto";
}

export const Dashboard: React.FC<{
  result: any;
  onLogout: () => void;
  onShowSwap: () => void;
  onShowTransfer: () => void;
  sdkKey: string;
  theme?: ThemeMode;
}> = ({
  result,
  onLogout,
  onShowSwap,
  onShowTransfer,
  sdkKey,
  theme = "dark",
}) => {
  const currentTheme = themeStyles[theme];
  const { walletCornerRadius } = useWallet();
  const currentRadius = borderRadiusStyles[walletCornerRadius];
  const [activeTab, setActiveTab] = useState<"assets" | "activity">("assets");
  const [showQRCode, setShowQRCode] = useState(false);
  const [drawerOpen, setDrawerOpen] = useState(false);
  const {
    cryptoBalance,
    loading,
    refreshBalance,
    username,
    evmWalletAddress,
    solanaAddress,
    bitcoinWalletAddress,
  } = useWallet();

  // Trigger immediate balance refresh when dashboard mounts
  useEffect(() => {
    if (username && !cryptoBalance) {
      refreshBalance();
    }
  }, [username]);

  // Add CSS to hide scrollbars
  React.useEffect(() => {
    const style = document.createElement("style");
    style.textContent = `
      .hide-scrollbar {
        -ms-overflow-style: none;  /* IE and Edge */
        scrollbar-width: none;  /* Firefox */
      }
      .hide-scrollbar::-webkit-scrollbar {
        display: none;  /* Chrome, Safari, Opera */
      }
      
      .dashboard-button {
        transition: all 0.2s ease-in-out;
      }
      
      .dashboard-button:hover {
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        border-color: ${currentTheme.primary};
        color: ${currentTheme.text} !important;
        opacity: 0.8 !important;
      }
      
      .dashboard-button:hover svg {
        color: ${currentTheme.text};
      }
    `;
    document.head.appendChild(style);
    return () => {
      document.head.removeChild(style);
    };
  }, []);

  const truncateAddress = (address: string) => {
    if (!address) return "";
    return address.slice(0, 6) + "..." + address.slice(-4);
  };

  const calculateTotalBalance = () => {
    let total = 0;
    if (cryptoBalance?.data) {
      total += cryptoBalance.data.reduce(
        (sum: number, token: any) => sum + (token.valueUsd || 0),
        0
      );
    }
    return total.toFixed(2);
  };

  const assets: any[] = [
    ...(cryptoBalance?.data?.map((token: TokenBalance) => ({
      name: token.name,
      icon: token.logoURI,
      amount: token.amount,
      valueUSD: token.valueUsd ? token.valueUsd.toFixed(2) : 0,
      symbol: token.symbol,
      priceUsd: token.priceUsd,
      priceChange: 0,
      priceChangePercentage24h: token.priceChangePercentage24h,
      valueChange24h: token.valueChange24h,
      type: "crypto" as const,
    })) || []),
  ];

  // Sort assets by USD value in descending order
  const sortedAssets = assets.sort((a, b) => {
    const valueA = parseFloat(a.valueUSD) || 0;
    const valueB = parseFloat(b.valueUSD) || 0;
    return valueB - valueA; // Descending order (highest value first)
  });

  const dasboardButtons = [
    {
      label: "Deposit",
      icon: <QrCode size={16} />,
      onClick: () => {
        setShowQRCode(true);
      },
    },
    {
      label: "Transfer",
      icon: <Send size={16} />,
      onClick: () => onShowTransfer(),
    },
    // {
    //   label: "Buy",
    //   icon: <ShoppingCart size={18} />,
    //   onClick: () => {},
    // },
    // {
    //   label: "Sell",
    //   icon: <Tag size={18} />,
    //   onClick: () => {},
    // },
    {
      label: "Swap",
      icon: <ArrowLeftRight size={16} />,
      onClick: () => {
        onShowSwap();
      },
    },
  ];

  const handleLogout = () => {
    // Get the SDK instance from window
    const walletSDK = (window as any).__walletSDKInstance;
    if (walletSDK) {
      walletSDK.logout();
    }
    // Call the parent's onLogout callback
    onLogout();
  };

  return (
    <div
      style={{
        width: "100%",
        margin: "0 auto",
        background: currentTheme.surface,
        borderRadius: 20,
        height: "550px",
      }}
    >
      {showQRCode ? (
        <QRNetworks
          walletAddress={evmWalletAddress || ""}
          solanaAddress={solanaAddress || ""}
          bitcoinWalletAddress={bitcoinWalletAddress || ""}
          onBack={() => setShowQRCode(false)}
          theme={theme}
        />
      ) : (
        <div>
          <div
            style={{
              fontWeight: 600,
              fontSize: 18,
              marginBottom: 10,
              display: "flex",
              alignItems: "center",
              justifyContent: "space-between",
              width: "100%",
            }}
          >
            <span
              style={{
                fontSize: 18,
                color: currentTheme.text,
                fontWeight: 400,
              }}
            >
              Wallet Dashboard
            </span>
            <span
              style={{
                padding: "4px 8px",
                fontSize: 14,
                fontWeight: 400,
                color: currentTheme.text,
                borderRadius: 40,
                background: currentTheme.surface,
                display: "flex",
                alignItems: "center",
                gap: 4,
                position: "relative",
                cursor: "pointer",
                border: `1px solid ${currentTheme.border}`,
              }}
              onClick={() => setDrawerOpen((v) => !v)}
            >
              <div
                style={{
                  background: currentTheme.surface,
                  width: 16,
                  height: 16,
                  borderRadius: 100,
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center",
                }}
              >
                {result?.photoURL ? (
                  <img
                    src={result?.photoURL}
                    alt="user"
                    style={{ width: 16, height: 16, borderRadius: 100 }}
                  />
                ) : (
                  <CircleUserRound
                    style={{ width: 16, height: 16, color: currentTheme.text }}
                  />
                )}
              </div>
              {username}
              <ChevronDown size={16} />
              {drawerOpen && (
                <div
                  style={{
                    position: "absolute",
                    top: 36,
                    right: 0,
                    background: currentTheme.surface,
                    boxShadow: "0 4px 16px rgba(0,0,0,0.10)",
                    borderRadius: 10,
                    minWidth: 120,
                    zIndex: 10,
                    padding: "8px 0",
                    display: "flex",
                    flexDirection: "column",
                    alignItems: "stretch",
                    border: `1px solid ${currentTheme.border}`,
                  }}
                >
                  <button
                    onClick={handleLogout}
                    style={{
                      background: "none",
                      border: "none",
                      color: "#E53E3E",
                      fontWeight: 400,
                      fontSize: 15,
                      padding: "10px 20px",
                      textAlign: "left",
                      cursor: "pointer",
                      display: "flex",
                      alignItems: "center",
                      gap: 8,
                    }}
                  >
                    <LogOut size={16} /> Logout
                  </button>
                </div>
              )}
            </span>
          </div>

          <div
            style={{
              fontSize: 32,
              fontWeight: 500,
              color: currentTheme.text,
            }}
          >
            ${cryptoBalance?.portfolioSummary?.totalValueUsd.toFixed(2)}
          </div>
          <div
            style={{
              display: "flex",
              alignItems: "center",
              gap: 12,
              justifyContent: "space-between",
              marginBottom: 12,
            }}
          >
            <div
              style={{
                color:
                  cryptoBalance?.portfolioSummary
                    ?.weightedPriceChangePercentage24h > 0
                    ? currentTheme.successText
                    : currentTheme.errorText,
                fontSize: 14,
              }}
            >
              {cryptoBalance?.portfolioSummary
                ?.weightedPriceChangePercentage24h > 0
                ? "↑"
                : "↓"}{" "}
              {cryptoBalance?.portfolioSummary?.weightedPriceChangePercentage24h.toFixed(
                2
              )}
              % ($
              {cryptoBalance?.portfolioSummary?.weightedPriceChange24hUsd.toFixed(
                2
              )}
              ){" "}
              <span style={{ color: currentTheme.textSecondary }}>
                in last 24hrs
              </span>
            </div>
            {/* <div
              style={{
                padding: "4px 8px",
                border: `1px solid ${currentTheme.border}`,
                borderRadius: 8,
                display: "flex",
                alignItems: "center",
                gap: 3,
                cursor: "pointer",
                background: currentTheme.surface,
              }}
              onClick={() => {
                setShowQRCode(true);
              }}
            >
              <QrCode color={currentTheme.text} size={16} />
              <span
                style={{
                  fontSize: 12,
                  fontWeight: 600,
                  color: currentTheme.text,
                }}
              >
                Deposit
              </span>
            </div> */}
          </div>

          {/* Action buttons */}
          <div
            style={{
              display: "grid",
              gridTemplateColumns: "repeat(3, 1fr)",
              gap: 8,
              marginBottom: 16,
            }}
          >
            {dasboardButtons.map((action, i) => (
              <button
                key={i}
                onClick={action.onClick}
                style={{
                  padding: "16px 2px",
                  borderRadius: currentRadius.innerRadius,
                  border: `1px solid ${currentTheme.border}`,
                  background:
                    theme === "dark" ? currentTheme.surfaceActive : "#FAFAFA",
                  fontSize: 13,
                  fontWeight: 400,
                  cursor: "pointer",
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center",
                  gap: 4,
                  color: currentTheme.textSecondary,
                  outline: "none",
                }}
                className="dashboard-button"
              >
                {action.icon}
                {action.label}
              </button>
            ))}
          </div>

          {/* Toggle: Assets/Activity */}
          <div
            style={{
              display: "flex",
              justifyContent: "space-between",
              marginBottom: 12,
              border: `1px solid ${currentTheme.border}`,
              borderRadius: currentRadius.innerRadius,
              overflow: "hidden",
              background:
                theme === "dark" ? currentTheme.surfaceHover : "#FAFAFA",
              height: 56,
            }}
          >
            <button
              onClick={() => setActiveTab("assets")}
              style={{
                fontSize: 14,
                flex: 1,
                borderRadius: currentRadius.innerRadius,
                margin: 4,
                background:
                  activeTab === "assets"
                    ? currentTheme.surface
                    : theme === "dark"
                    ? currentTheme.surfaceHover
                    : "#FAFAFA",
                fontWeight: 600,
                border: "none",
                color:
                  activeTab === "assets"
                    ? currentTheme.text
                    : currentTheme.textSecondary,
                boxShadow:
                  activeTab === "assets"
                    ? "0 4px 12px rgba(0,0,0,0.05)"
                    : "none",
                cursor: "pointer",
              }}
            >
              Assets
            </button>
            <button
              onClick={() => setActiveTab("activity")}
              style={{
                fontSize: 14,
                flex: 1,
                borderRadius: currentRadius.innerRadius,
                margin: 4,
                boxShadow:
                  activeTab === "activity"
                    ? "0 4px 12px rgba(0,0,0,0.05)"
                    : "none",
                background:
                  activeTab === "activity"
                    ? currentTheme.surface
                    : theme === "dark"
                    ? currentTheme.surfaceHover
                    : "#FAFAFA",
                fontWeight: 600,
                border: "none",
                color:
                  activeTab === "activity"
                    ? currentTheme.text
                    : currentTheme.textSecondary,
                position: "relative",
                cursor: "pointer",
              }}
            >
              Activity
            </button>
          </div>

          {/* Content based on active tab */}
          {activeTab === "assets" ? (
            <div
              className="hide-scrollbar"
              style={{
                minHeight: 320,
                maxHeight: 320,
                overflowY: sortedAssets.length > 0 ? "auto" : "hidden",
                marginBottom: 24,
              }}
            >
              {loading && !cryptoBalance ? (
                <div
                  style={{
                    height: 320,
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "center",
                  }}
                >
                  <Spinner theme={theme} />
                </div>
              ) : sortedAssets.length === 0 ? (
                <div
                  style={{
                    height: 260,
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "center",
                    color: currentTheme.textSecondary,
                    fontSize: 16,
                    marginBottom: 24,
                    gap: 8,
                    flexDirection: "column",
                  }}
                >
                  <HandCoins size={20} />
                  No assets found
                </div>
              ) : (
                sortedAssets.map((asset, idx) => (
                  <div
                    key={idx}
                    style={{
                      padding: "2px 0px",
                      borderBottom:
                        idx !== sortedAssets.length - 1
                          ? `1px solid ${currentTheme.border}`
                          : "none",
                    }}
                  >
                    <div
                      style={{
                        display: "flex",
                        alignItems: "center",
                        padding: "12px",
                      }}
                    >
                      <div style={{ marginRight: 12 }}>
                        <TokenLogo
                          logoURI={asset.icon}
                          symbol={asset.symbol}
                          name={asset.name}
                          size={36}
                        />
                      </div>

                      <div style={{ flexGrow: 1 }}>
                        <div
                          style={{
                            fontWeight: 600,
                            color: currentTheme.text,
                            fontSize: 16,
                          }}
                        >
                          {asset.name}
                        </div>
                        <div
                          style={{
                            color:
                              asset.priceChangePercentage24h > 0
                                ? currentTheme.successText
                                : currentTheme.errorText,
                            fontSize: 13,
                          }}
                        >
                          {asset.priceChangePercentage24h > 0 ? "↑" : "↓"}{" "}
                          {asset.priceChangePercentage24h.toFixed(2)}% ($
                          {asset.valueChange24h.toFixed(2)})
                        </div>
                      </div>
                      <div style={{ textAlign: "right" }}>
                        <div
                          style={{ fontWeight: 600, color: currentTheme.text }}
                        >
                          {Number(asset.valueUSD) < 0.01
                            ? "$<0.01"
                            : `$${asset.valueUSD}`}
                        </div>
                        <div
                          style={{
                            fontSize: 13,
                            color: currentTheme.textSecondary,
                          }}
                        >
                          {Number(asset.amount).toFixed(6)} {asset.symbol}
                        </div>
                      </div>
                    </div>
                  </div>
                ))
              )}
            </div>
          ) : (
            <div
              className="hide-scrollbar"
              style={{
                textAlign: "center",
                height: 320,
                color: currentTheme.textSecondary,
                fontSize: 16,
                marginBottom: 24,
              }}
            >
              <Activity sdkKey={sdkKey} theme={theme} />
            </div>
          )}
        </div>
      )}
    </div>
  );
};
