import React, { useState } from "react";
import {
  ArrowLeft,
  ChevronDown,
  ChevronUp,
  SendHorizontal,
} from "lucide-react";
import Spinner from "../ui/Spinner";
import {
  formatAmount,
  getContrastingTextColor,
  NETWORK_NAME_TO_CHAIN_ID,
} from "../utils";
import { NETWORK_LOGO_URLS } from "../utils";
import { useWallet } from "../WalletProvider";
import { ThemeMode, themeStyles, borderRadiusStyles } from "../../types/theme";

interface Token {
  symbol: string;
  name: string;
  icon?: string;
  logoURI?: string;
  address: string;
  chainId: number;
  decimals: number;
  balance?: string;
  amount?: string;
  chainIds?: any[];
  price?: number;
  priceUsd?: number;
}

interface SendToUser {
  status: boolean;
  username?: string;
  walletAddress?: string;
  solanaWalletAddress?: string;
  ensName?: string;
  sns?: string;
  bitcoinWalletAddress?: string;
}

interface NetworkSelection {
  name: string;
  chainId: number;
  amount?: string;
}

interface ReviewTransferProps {
  selectedToken: Token;
  amount: string;
  recipient: string;
  sendToUser: SendToUser;
  addressToSend: string;
  selectedFromNetworksPay: NetworkSelection[];
  selectedToNetworksPay: NetworkSelection[];
  isTransferring: boolean;
  transferError: string | null;
  onBack: () => void;
  onConfirm: () => void;
  proActive: boolean;
  theme?: ThemeMode;
}

function ReviewTransfer({
  selectedToken,
  amount,
  recipient,
  sendToUser,
  addressToSend,
  selectedFromNetworksPay,
  selectedToNetworksPay,
  isTransferring,
  transferError,
  onBack,
  onConfirm,
  proActive,
  theme = "light",
}: ReviewTransferProps) {
  const [showPreviewNetworks, setShowPreviewNetworks] = useState(false);
  const { walletCornerRadius, currentTheme } = useWallet();

  const currentRadius = borderRadiusStyles[walletCornerRadius];

  const NetworkAllocationDisplay = ({
    network,
    amount,
    symbol,
  }: {
    network: string;
    amount: string;
    symbol: string;
  }) => (
    <div
      style={{
        display: "flex",
        justifyContent: "space-between",
        alignItems: "center",
        width: "100%",
        padding: "8px 0",
      }}
    >
      <div
        style={{
          display: "flex",
          alignItems: "center",
          gap: "8px",
        }}
      >
        <img
          src={NETWORK_LOGO_URLS[NETWORK_NAME_TO_CHAIN_ID[network]]}
          alt={network}
          style={{ width: 24, height: 24, borderRadius: "50%" }}
        />
        <span
          style={{ fontSize: 14, color: currentTheme.text, fontWeight: 500 }}
        >
          {network}
        </span>
      </div>
      <span style={{ fontSize: 14, color: currentTheme.textSecondary }}>
        {amount} {symbol}
      </span>
    </div>
  );

  return (
    <div
      style={{
        width: "100%",
        background: currentTheme.surface,
        borderRadius: currentRadius.outerRadius,

        paddingBottom: 24,
        color: currentTheme.text,
      }}
    >
      <div
        style={{
          display: "flex",
          alignItems: "center",
          marginBottom: 18,
          position: "relative",
        }}
      >
        <button
          onClick={onBack}
          style={{
            background: "none",
            border: "none",
            fontSize: 22,
            color: currentTheme.text,
            cursor: "pointer",
            position: "absolute",
            left: 0,
          }}
        >
          <ArrowLeft
            style={{ width: 24, height: 24, color: currentTheme.textSecondary }}
          />
        </button>
        <span
          style={{
            fontWeight: 600,
            fontSize: 20,
            width: "100%",
            textAlign: "center",
            color: currentTheme.text,
          }}
        >
          Confirm transaction
        </span>
      </div>
      <div
        style={{
          display: "flex",
          flexDirection: "column",
          alignItems: "center",
          marginBottom: 24,
          border: proActive ? `1px solid ${currentTheme.primary}` : "none",
          borderRadius: currentRadius.innerRadius,
          padding: 16,
          background: proActive ? currentTheme.surfaceActive : "transparent",
        }}
      >
        <div
          style={{
            background: currentTheme.surfaceActive,
            borderRadius: currentRadius.outerRadius,
            padding: 16,
            marginBottom: 16,
          }}
        >
          <SendHorizontal size={36} color={currentTheme.primary} />
        </div>
        <div
          style={{
            fontWeight: 700,
            fontSize: 32,
            marginBottom: 4,
            color: currentTheme.text,
          }}
        >
          {formatAmount(amount)} {selectedToken.symbol}
        </div>
        <div
          style={{
            color: currentTheme.textSecondary,
            fontSize: 18,
            marginBottom: 16,
          }}
        >
          ${(parseFloat(amount || "0") * (selectedToken.price || 0)).toFixed(2)}
        </div>
        {proActive && (
          <div
            style={{
              borderRadius: `${currentRadius.innerRadius}px`,
              overflow: "hidden",
              background: currentTheme.surface,
              width: "100%",
            }}
          >
            <button
              onClick={() => setShowPreviewNetworks((v) => !v)}
              style={{
                width: "100%",
                background: currentTheme.surface,
                border: "none",
                padding: "12px 16px",
                display: "flex",
                justifyContent: "space-between",
                alignItems: "center",
                cursor: "pointer",
                textAlign: "left",
              }}
            >
              <span
                style={{
                  fontSize: 16,
                  color: currentTheme.text,
                  fontWeight: 400,
                }}
              >
                {selectedFromNetworksPay.length} Network
              </span>
              {showPreviewNetworks ? (
                <ChevronUp
                  style={{
                    width: 16,
                    height: 16,
                    color: currentTheme.textSecondary,
                  }}
                />
              ) : (
                <ChevronDown
                  style={{
                    width: 16,
                    height: 16,
                    color: currentTheme.textSecondary,
                  }}
                />
              )}
            </button>
            {showPreviewNetworks && (
              <>
                <div style={{ padding: "1px 16px" }}>
                  {selectedFromNetworksPay.map((network, index) => (
                    <div
                      key={network.name}
                      style={{
                        borderTop:
                          index === 0
                            ? `1px solid ${currentTheme.border}`
                            : "none",
                      }}
                    >
                      <NetworkAllocationDisplay
                        network={network.name}
                        amount={network.amount || "0"}
                        symbol={selectedToken?.symbol || ""}
                      />
                    </div>
                  ))}
                </div>
              </>
            )}
          </div>
        )}
      </div>
      <div
        style={{
          background: currentTheme.surfaceActive,
          borderRadius: `${currentRadius.innerRadius}px`,
          padding: 16,
          marginBottom: 24,
        }}
      >
        <div
          style={{
            display: "flex",
            justifyContent: "space-between",
            marginBottom: 8,
          }}
        >
          <span
            style={{ color: currentTheme.text, fontSize: 16, fontWeight: 500 }}
          >
            Recipient
          </span>
          <span style={{ color: currentTheme.textSecondary, fontSize: 16 }}>
            {(() => {
              const displayName = sendToUser.username || recipient;
              return displayName.length > 8
                ? displayName.slice(0, 8) + "..."
                : displayName;
            })()}{" "}
            <span style={{ color: currentTheme.textSecondary, opacity: 0.7 }}>
              (
              {addressToSend
                ? selectedToNetworksPay[0].chainId ===
                  NETWORK_NAME_TO_CHAIN_ID.Solana
                  ? `${sendToUser.solanaWalletAddress?.slice(
                      0,
                      6
                    )}...${sendToUser.solanaWalletAddress?.slice(-4)}`
                  : selectedToNetworksPay[0].chainId ===
                    NETWORK_NAME_TO_CHAIN_ID.Bitcoin
                  ? `${sendToUser?.bitcoinWalletAddress?.slice(
                      0,
                      6
                    )}...${sendToUser?.bitcoinWalletAddress?.slice(-4)}`
                  : `${sendToUser.walletAddress?.slice(
                      0,
                      6
                    )}...${sendToUser.walletAddress?.slice(-4)}`
                : "Unknown"}
              )
            </span>
          </span>
        </div>
        <div
          style={{
            display: "flex",
            justifyContent: "space-between",
            marginBottom: 8,
          }}
        >
          <span
            style={{ color: currentTheme.text, fontSize: 16, fontWeight: 500 }}
          >
            Recipient Network
          </span>
          <span style={{ color: currentTheme.textSecondary, fontSize: 16 }}>
            {selectedToNetworksPay[0].name || "None"}
          </span>
        </div>
        <div
          style={{
            display: "flex",
            justifyContent: "space-between",
          }}
        >
          <span
            style={{ color: currentTheme.text, fontSize: 16, fontWeight: 500 }}
          >
            Total
          </span>
          <span style={{ color: currentTheme.textSecondary, fontSize: 16 }}>
            {formatAmount(amount)} {selectedToken.symbol}
          </span>
        </div>
      </div>
      <div style={{ display: "flex", gap: 12 }}>
        <button
          onClick={onBack}
          style={{
            flex: 1,
            border: `1px solid ${currentTheme.border}`,
            background: currentTheme.surface,
            color: currentTheme.text,
            fontWeight: 600,
            fontSize: 16,
            borderRadius: currentRadius.innerRadius,
            padding: "10px 0",
            cursor: "pointer",
          }}
          disabled={isTransferring}
        >
          Cancel
        </button>
        <button
          onClick={onConfirm}
          style={{
            flex: 1,
            border: "none",
            background: currentTheme.primary,
            color: getContrastingTextColor(currentTheme.primary),
            fontWeight: 600,
            fontSize: 16,
            borderRadius: currentRadius.innerRadius,
            padding: "10px 0",
            cursor: isTransferring ? "not-allowed" : "pointer",
            opacity: isTransferring ? 0.7 : 1,
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            gap: 8,
          }}
          disabled={isTransferring}
        >
          {isTransferring ? (
            <>
              <Spinner />
              Sending...
            </>
          ) : (
            "Confirm"
          )}
        </button>
      </div>
      {transferError && (
        <div
          style={{
            color: "#DC2626",
            fontSize: 14,
            marginTop: 12,
            textAlign: "center",
          }}
        >
          {transferError}
        </div>
      )}
    </div>
  );
}

export default ReviewTransfer;
