import React, { useEffect, useState } from "react";
import { formatUnits } from "ethers";
import {
  ArrowUp,
  ShoppingCart,
  Tag,
  ArrowLeftRight,
  CircleUserRound,
  QrCode,
  ChevronDown,
  LogOut,
} 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";

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;
}> = ({ result, onLogout, onShowSwap, onShowTransfer, sdkKey }) => {
  const [activeTab, setActiveTab] = useState<"assets" | "activity">("assets");
  const [showQRCode, setShowQRCode] = useState(false);
  const [drawerOpen, setDrawerOpen] = useState(false);
  const { cryptoBalance, loading, refreshBalance } = useWallet();

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

  // 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 */
      }
    `;
    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: "Transfer",
      icon: <ArrowUp size={18} />,
      onClick: () => onShowTransfer(),
    },
    {
      label: "Buy",
      icon: <ShoppingCart size={18} />,
      onClick: () => {},
    },
    {
      label: "Sell",
      icon: <Tag size={18} />,
      onClick: () => {},
    },
    {
      label: "Swap",
      icon: <ArrowLeftRight size={18} />,
      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: "#fff",
        borderRadius: 20,
        fontFamily: "Inter, sans-serif",
        height: "550px",
      }}
    >
      {showQRCode ? (
        <QRNetworks
          walletAddress={result?.wallet?.scw_address}
          solanaAddress={result?.wallet?.solana_program_wallet}
          bitcoinWalletAddress={
            result?.wallet?.bitcoin_wallet?.native_segwit_address
          }
          onBack={() => setShowQRCode(false)}
        />
      ) : (
        <div>
          <div
            style={{
              fontWeight: 600,
              fontSize: 18,
              marginBottom: 10,
              display: "flex",
              alignItems: "center",
              justifyContent: "space-between",
              width: "100%",
            }}
          >
            <span style={{ fontSize: 18, color: "black", fontWeight: 600 }}>
              Wallet Dashboard
            </span>
            <span
              style={{
                padding: "4px 8px",
                fontSize: 14,
                color: "#175CD3",
                borderRadius: 40,
                background: "#EFF8FF",
                display: "flex",
                alignItems: "center",
                gap: 4,
                position: "relative",
                cursor: "pointer",
              }}
              onClick={() => setDrawerOpen((v) => !v)}
            >
              <div
                style={{
                  background: "white",
                  width: 16,
                  height: 16,
                  borderRadius: 100,
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center",
                }}
              >
                <CircleUserRound
                  style={{ width: 16, height: 16, color: "#175CD3" }}
                />
              </div>
              {result?.displayName || result?.username}
              <ChevronDown size={16} />
              {drawerOpen && (
                <div
                  style={{
                    position: "absolute",
                    top: 36,
                    right: 0,
                    background: "#fff",
                    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",
                  }}
                >
                  <button
                    onClick={handleLogout}
                    style={{
                      background: "none",
                      border: "none",
                      color: "#E53E3E",
                      fontWeight: 600,
                      fontSize: 15,
                      padding: "10px 20px",
                      textAlign: "left",
                      cursor: "pointer",
                      display: "flex",
                      alignItems: "center",
                      fontFamily: "Inter, sans-serif",
                      gap: 8,
                    }}
                  >
                    <LogOut size={16} /> Logout
                  </button>
                </div>
              )}
            </span>
          </div>

          <div
            style={{
              fontSize: 28,
              fontWeight: "bold",
            }}
          >
            ${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
                    ? "#027A48"
                    : "#E53E3E",
                fontSize: 14,
              }}
            >
              {cryptoBalance?.portfolioSummary
                ?.weightedPriceChangePercentage24h > 0
                ? "↑"
                : "↓"}{" "}
              {cryptoBalance?.portfolioSummary?.weightedPriceChangePercentage24h.toFixed(
                2
              )}
              % ($
              {cryptoBalance?.portfolioSummary?.weightedPriceChange24hUsd.toFixed(
                2
              )}
              ) <span style={{ color: "#535862" }}>in last 24hrs</span>
            </div>
            <div
              style={{
                padding: "4px 8px",
                border: "1px solid #D5D7DA",
                borderRadius: 8,
                display: "flex",
                alignItems: "center",
                gap: 3,
                cursor: "pointer",
              }}
              onClick={() => {
                setShowQRCode(true);
              }}
            >
              <QrCode color="#414651" size={16} />
              <span style={{ fontSize: 12, fontWeight: 600, color: "#414651" }}>
                Deposit
              </span>
            </div>
          </div>

          {/* Action buttons */}
          <div
            style={{
              display: "grid",
              gridTemplateColumns: "repeat(4, 1fr)",
              gap: 8,
              marginBottom: 16,
            }}
          >
            {dasboardButtons.map((action, i) => (
              <button
                key={i}
                onClick={action.onClick}
                style={{
                  padding: "10px 0",
                  borderRadius: 10,
                  border: "1px solid #e0e0e0",
                  background: "#fff",
                  fontSize: 13,
                  fontWeight: 500,
                  cursor: "pointer",
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center",
                  gap: 4,
                  fontFamily: "Inter, sans-serif",
                  color: "#414651",
                  outline: "none",
                }}
              >
                {action.icon}
                {action.label}
              </button>
            ))}
          </div>

          {/* Toggle: Assets/Activity */}
          <div
            style={{
              display: "flex",
              justifyContent: "space-between",
              marginBottom: 12,
              border: "1px solid #eee",
              borderRadius: 8,
              overflow: "hidden",
              background: "#FAFAFA",
              height: 46,
            }}
          >
            <button
              onClick={() => setActiveTab("assets")}
              style={{
                fontSize: 14,
                fontFamily: "Inter, sans-serif",
                flex: 1,
                borderRadius: 8,
                margin: 4,
                background: activeTab === "assets" ? "#fff" : "#FAFAFA",
                fontWeight: 600,
                border: "none",
                color: activeTab === "assets" ? "#414651" : "#717680",
                boxShadow:
                  activeTab === "assets"
                    ? "0 4px 12px rgba(0,0,0,0.05)"
                    : "none",
                cursor: "pointer",
              }}
            >
              Assets
            </button>
            <button
              onClick={() => setActiveTab("activity")}
              style={{
                fontSize: 14,
                fontFamily: "Inter, sans-serif",
                flex: 1,
                borderRadius: 8,
                margin: 4,
                boxShadow:
                  activeTab === "activity"
                    ? "0 4px 12px rgba(0,0,0,0.05)"
                    : "none",
                background: activeTab === "activity" ? "#fff" : "#FAFAFA",
                fontWeight: 600,
                border: "none",
                color: activeTab === "activity" ? "#414651" : "#717680",
                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",
                    fontFamily: "Inter, sans-serif",
                  }}
                >
                  <Spinner />
                </div>
              ) : sortedAssets.length === 0 ? (
                <div
                  style={{
                    height: 260,
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "center",
                    color: "#666",
                    fontSize: 16,
                    marginBottom: 24,
                    fontFamily: "Inter, sans-serif",
                  }}
                >
                  No assets found
                </div>
              ) : (
                sortedAssets.map((asset, idx) => (
                  <div
                    style={{
                      padding: "2px 0px",
                      borderBottom:
                        idx !== sortedAssets.length - 1
                          ? "1px solid #E9EAEB"
                          : "none",
                    }}
                  >
                    <div
                      key={idx}
                      style={{
                        display: "flex",
                        alignItems: "center",
                        padding: "12px",
                      }}
                    >
                      <TokenLogo
                        logoURI={asset.icon}
                        symbol={asset.symbol}
                        name={asset.name}
                        size={36}
                        style={{ marginRight: 12 }}
                      />

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