import React, { useState } from "react";
import { ArrowLeft, QrCode, Copy, X, Link, Check, Info } from "lucide-react";
import { QRCodeSVG } from "qrcode.react";
import {
  NETWORK_LOGO_URLS,
  availableNetworks,
  getContrastingTextColor,
} from "../utils";
import { borderRadiusStyles, ThemeMode } from "../../types/theme";
import { useWallet } from "../WalletProvider";

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

export const QRNetworks: React.FC<{
  walletAddress: string;
  solanaAddress: string;
  bitcoinWalletAddress: string;
  onBack: () => void;
  theme?: ThemeMode;
}> = ({
  walletAddress,
  solanaAddress,
  bitcoinWalletAddress,
  onBack,
  theme = "dark",
}) => {
  const { currentTheme } = useWallet();

  const networks = [
    {
      name: "EVM",
      symbol: "ETH",
      icon: "https://media.socket.tech/tokens/all/ETH",
      address: walletAddress,
    },
    {
      name: "Solana",
      symbol: "SOL",
      icon: NETWORK_LOGO_URLS["792703809"],
      address: solanaAddress,
    },
    {
      name: "Bitcoin",
      symbol: "BTC",
      icon: "https://storage.googleapis.com/enclave_assets/bitcoin.webp",
      address: bitcoinWalletAddress,
    },
  ];
  const [qrNetwork, setQrNetwork] = useState<null | (typeof networks)[0]>(null);
  const [copiedAddress, setCopiedAddress] = useState<string | null>(null);
  const [showNetworkTooltip, setShowNetworkTooltip] = useState(false);

  const { walletCornerRadius } = useWallet();
  const currentRadius = borderRadiusStyles[walletCornerRadius];

  const handleCopy = (address: string) => {
    navigator.clipboard.writeText(address);
    setCopiedAddress(address);
    setTimeout(() => setCopiedAddress(null), 1200);
  };

  if (qrNetwork) {
    return (
      <div
        style={{
          width: "100%",

          background: currentTheme.surface,
          color: currentTheme.text,
        }}
      >
        {/* Header */}
        <div
          style={{
            display: "flex",
            alignItems: "center",
          }}
        >
          <button
            onClick={() => setQrNetwork(null)}
            style={{
              background: "none",
              border: "none",
              cursor: "pointer",
              marginRight: 12,
              padding: 0,
              display: "flex",
              alignItems: "center",
            }}
          >
            <ArrowLeft size={24} color={currentTheme.text} />
          </button>
          <span
            style={{
              fontWeight: 600,
              fontSize: 20,
              flex: 1,
              textAlign: "center",
              color: currentTheme.text,
            }}
          >
            Deposit {qrNetwork.symbol}
          </span>
          <button
            onClick={onBack}
            style={{
              background: "none",
              border: "none",
              cursor: "pointer",
              marginLeft: 12,
              padding: 0,
              display: "flex",
              alignItems: "center",
            }}
          >
            <X size={22} color={currentTheme.textSecondary} />
          </button>
        </div>
        {/* QR Code */}
        <div
          style={{
            display: "flex",
            flexDirection: "column",
            alignItems: "center",
            margin: "24px 0 0 0",
          }}
        >
          <div
            style={{
              background: "white",
              borderRadius: 16,
              padding: 16,
            }}
          >
            <QRCodeSVG value={qrNetwork.address || ""} size={160} />
          </div>
        </div>
        {/* Divider and Wallet Address */}
        <div style={{ margin: "24px 0 0 0", padding: "0" }}>
          <div
            style={{
              borderTop: `1px solid ${currentTheme.border}`,
              marginBottom: 12,
              position: "relative",
              textAlign: "center",
            }}
          >
            <span
              style={{
                position: "relative",
                top: -12,
                background: currentTheme.surface,
                padding: "0 12px",
                color: currentTheme.textSecondary,
                fontSize: 14,
              }}
            >
              or
            </span>
          </div>
          <div
            style={{
              fontWeight: 500,
              fontSize: 15,
              marginBottom: 6,
              color: currentTheme.text,
            }}
          >
            Wallet Address
          </div>
          <div
            style={{
              display: "flex",
              alignItems: "center",
              background: currentTheme.surface,
              borderRadius: `${currentRadius.innerRadius}px`,
              padding: "12px",
              marginBottom: 8,
              border: `1px solid ${currentTheme.border}`,
            }}
          >
            <span
              style={{
                fontWeight: 500,
                fontSize: 15,
                color: currentTheme.text,
                flex: 1,
              }}
            >
              {truncateAddress(qrNetwork.address || "")}
            </span>
            <button
              onClick={() => handleCopy(qrNetwork.address || "")}
              style={{
                background:
                  copiedAddress === qrNetwork.address
                    ? currentTheme.primary
                    : currentTheme.surfaceActive,
                color:
                  copiedAddress === qrNetwork.address
                    ? getContrastingTextColor(currentTheme.primary)
                    : currentTheme.primary,
                border: "none",
                borderRadius: `${currentRadius.innerRadius}px`,
                fontWeight: 600,
                fontSize: 15,
                padding: "6px 18px",
                cursor: "pointer",
                transition: "all 0.2s",
              }}
            >
              {copiedAddress === qrNetwork.address ? "Copied" : "Copy"}
            </button>
          </div>
          <div
            style={{
              color: currentTheme.textSecondary,
              fontSize: 13,
              display: "flex",
              alignItems: "center",
              gap: 6,
            }}
          >
            <span style={{ fontSize: 16 }}>ⓘ</span> This address can only be
            used to receive compatible tokens.
          </div>
        </div>
        <button
          onClick={() => setQrNetwork(null)}
          style={{
            margin: "32px 0px 24px 0px",
            width: "100%",
            background: currentTheme.surface,
            color: currentTheme.primary,
            fontWeight: 600,
            fontSize: 16,
            border: `1.5px solid ${currentTheme.primary}`,
            borderRadius: `${currentRadius.innerRadius}px`,
            padding: "16px 0",
            cursor: "pointer",
            boxShadow: "none",
          }}
        >
          Go Back
        </button>
      </div>
    );
  }

  return (
    <div
      style={{
        height: "500px",
        background: currentTheme.surface,
        color: currentTheme.text,
      }}
    >
      {/* Header */}
      <div
        style={{
          display: "flex",
          alignItems: "center",
          padding: "0px 0px 16px 0px",
        }}
      >
        <button
          onClick={onBack}
          style={{
            background: "none",
            border: "none",
            cursor: "pointer",

            padding: 0,
            display: "flex",
            alignItems: "center",
          }}
        >
          <ArrowLeft size={24} color={currentTheme.text} />
        </button>
        <span
          style={{
            fontWeight: 600,
            fontSize: 20,
            flex: 1,
            textAlign: "center",
            color: currentTheme.text,
          }}
        >
          Networks
        </span>
      </div>

      {/* Token List */}
      <div style={{ padding: "0 0 8px 0" }}>
        {networks.map((network, idx) => (
          <div
            key={network.symbol}
            style={{
              display: "flex",
              alignItems: "center",
              padding: "18px 0px",
              borderBottom:
                idx !== networks.length - 1
                  ? `1px solid ${currentTheme.border}`
                  : "none",
              gap: 16,
            }}
          >
            <img
              src={network.icon}
              alt={network.name}
              style={{
                width: 40,
                height: 40,
                borderRadius: 12,
                background: currentTheme.surface,
              }}
            />

            <div style={{ flex: 1, color: currentTheme.text }}>
              <div style={{ fontWeight: 600, fontSize: 16 }}>
                {network.name}
              </div>
              <div style={{ fontSize: 13, color: currentTheme.textSecondary }}>
                {truncateAddress(network.address || "")}
              </div>
            </div>
            <div style={{ display: "flex", gap: 12, position: "relative" }}>
              {network.name === "EVM" && (
                <div
                  style={{ position: "relative", display: "inline-block" }}
                  onMouseEnter={() => setShowNetworkTooltip(true)}
                  onMouseLeave={() => setShowNetworkTooltip(false)}
                >
                  <button
                    style={{
                      background: "none",
                      border: "none",
                      cursor: "pointer",
                      padding: 0,
                      display: "flex",
                      alignItems: "center",
                    }}
                    title="Available Networks"
                  >
                    <Info size={20} color={currentTheme.textSecondary} />
                  </button>
                  {showNetworkTooltip && (
                    <div
                      style={{
                        position: "absolute",
                        top: "100%",
                        right: 0,
                        marginTop: 8,
                        background: currentTheme.surface,
                        border: `1px solid ${currentTheme.border}`,
                        borderRadius: 12,
                        padding: 16,
                        boxShadow: "0 4px 20px rgba(0, 0, 0, 0.1)",
                        zIndex: 1000,
                        width: 320,
                      }}
                    >
                      <div
                        style={{
                          fontWeight: 600,
                          fontSize: 16,
                          marginBottom: 16,
                          color: currentTheme.text,
                        }}
                      >
                        Supported EVM Networks
                      </div>
                      <div
                        style={{
                          display: "grid",
                          gridTemplateColumns: "1fr 1fr",
                          gap: 12,
                          marginBottom: 16,
                        }}
                      >
                        {availableNetworks
                          .filter((network) => network.name !== "Solana")
                          .map((availableNetwork) => (
                            <div
                              key={availableNetwork.name}
                              style={{
                                display: "flex",
                                alignItems: "center",
                                gap: 8,
                                padding: "8px 12px",
                                background: currentTheme.surfaceActive,
                                borderRadius: 8,
                              }}
                            >
                              <img
                                src={availableNetwork.icon}
                                alt={availableNetwork.name}
                                style={{
                                  width: 20,
                                  height: 20,
                                  borderRadius: 4,
                                }}
                              />
                              <span
                                style={{
                                  fontSize: 13,
                                  fontWeight: 500,
                                  color: currentTheme.text,
                                }}
                              >
                                {availableNetwork.name}
                              </span>
                            </div>
                          ))}
                      </div>
                      <div
                        style={{
                          fontSize: 12,
                          color: currentTheme.textSecondary,
                          textAlign: "center",
                          lineHeight: 1.4,
                        }}
                      >
                        Your Ethereum address works on all these networks
                      </div>
                    </div>
                  )}
                </div>
              )}
              <button
                style={{
                  background: "none",
                  border: "none",
                  cursor: "pointer",
                  padding: 0,
                  display: "flex",
                  alignItems: "center",
                }}
                title="Show QR"
                onClick={() => setQrNetwork(network)}
              >
                <QrCode size={20} color={currentTheme.textSecondary} />
              </button>
              <button
                style={{
                  background: "none",
                  border: "none",
                  cursor: "pointer",
                  padding: 0,
                  display: "flex",
                  alignItems: "center",
                  borderRadius: `${currentRadius.innerRadius}px`,
                }}
                title="Copy address"
                onClick={() => handleCopy(network.address || "")}
              >
                {copiedAddress === network.address ? (
                  <Check size={20} color={currentTheme.successText} />
                ) : (
                  <Copy size={20} color={currentTheme.textSecondary} />
                )}
              </button>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
};
