import React, { useState, useMemo } from "react";
import { ArrowLeft, Search, QrCode, Copy } from "lucide-react";
import Spinner from "./Spinner";

const styles = `
  .hide-scrollbar::-webkit-scrollbar {
    display: none;
  }
`;

export 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 TokenSelectorProps {
  title: string;
  tokens: Token[];
  onTokenSelect: (token: Token) => void;
  onBack: () => void;
  isLoading?: boolean;
  tokenFilter?: string[];
  showActions?: boolean;
}

const TokenSelector: React.FC<TokenSelectorProps> = ({
  title,
  tokens,
  onTokenSelect,
  onBack,
  isLoading = false,
  tokenFilter,
  showActions = true,
}) => {
  const [searchQuery, setSearchQuery] = useState("");

  // Filter tokens based on search query and optional token filter
  const filteredTokens = useMemo(() => {
    let filtered = tokens;

    // Apply token filter if provided
    if (tokenFilter && tokenFilter.length > 0) {
      filtered = filtered.filter((token) =>
        tokenFilter.includes(token.symbol)
      );
    }

    // Apply search filter
    if (searchQuery) {
      const query = searchQuery.toLowerCase();
      filtered = filtered.filter(
        (token) =>
          token.name.toLowerCase().includes(query) ||
          token.symbol.toLowerCase().includes(query) ||
          (token.address && token.address.toLowerCase().includes(query))
      );
    }

    return filtered;
  }, [tokens, searchQuery, tokenFilter]);

  return (
    <>
      <style>{styles}</style>
      <div
        style={{
          width: "100%",
          minWidth: 430,
          background: "#fff",
          borderRadius: 20,
          fontFamily: "Inter, sans-serif",
          display: "flex",
          flexDirection: "column",
          height: "550px",
        }}
      >
        {/* Header */}
        <div
          style={{
            display: "flex",
            alignItems: "center",
            marginBottom: 18,
            position: "relative",
          }}
        >
          <button
            onClick={onBack}
            style={{
              background: "none",
              border: "none",
              fontSize: 22,
              color: "#222",
              cursor: "pointer",
              position: "absolute",
              left: 0,
              fontFamily: "Inter, sans-serif",
            }}
          >
            <ArrowLeft style={{ width: 24, height: 24, color: "#717680" }} />
          </button>
          <span
            style={{
              fontWeight: 600,
              fontSize: 20,
              width: "100%",
              textAlign: "center",
            }}
          >
            {title}
          </span>
        </div>

        {/* Search Input */}
        <div style={{ position: "relative", marginBottom: 18 }}>
          <Search
            style={{
              position: "absolute",
              left: 14,
              top: "50%",
              transform: "translateY(-50%)",
              width: 18,
              height: 18,
              color: "#717680",
            }}
          />
          <input
            type="text"
            placeholder="Search name or paste address..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            style={{
              width: "100%",
              padding: "10px 14px 10px 40px",
              borderRadius: 10,
              border: "1px solid #E0E0E0",
              fontSize: 16,
              color: "#717680",
              outline: "none",
            }}
          />
        </div>

        {/* Token List */}
        <div>
          <div
            style={{
              flex: 1,
              overflowY: "auto",
              maxHeight: "400px",
              paddingRight: 8,
              msOverflowStyle: "none" /* IE and Edge */,
              scrollbarWidth: "none" /* Firefox */,
              WebkitOverflowScrolling: "touch",
            }}
            className="hide-scrollbar"
          >
            {isLoading ? (
              <div
                style={{
                  display: "flex",
                  flexDirection: "column",
                  alignItems: "center",
                  justifyContent: "center",
                  height: "200px",
                  gap: "16px",
                }}
              >
                <Spinner />
                <span style={{ color: "#717680", fontSize: 16 }}>
                  Loading Tokens...
                </span>
              </div>
            ) : (
              filteredTokens.map((token: Token, idx: number) => (
                <div
                  key={`${token.symbol}-${idx}`}
                  style={{
                    display: "flex",
                    alignItems: "center",
                    padding: "14px 0",
                    borderBottom:
                      idx !== filteredTokens.length - 1
                        ? "1px solid #E9EAEB"
                        : "none",
                    cursor: "pointer",
                    transition: "background 0.1s",
                  }}
                  onClick={() => onTokenSelect(token)}
                >
                  <div
                    style={{
                      width: 36,
                      height: 36,
                      borderRadius: 18,
                      background: "#eee",
                      display: "flex",
                      alignItems: "center",
                      justifyContent: "center",
                      fontSize: 18,
                      marginRight: 12,
                      overflow: "hidden",
                    }}
                  >
                    <img
                      src={token.logoURI || token.icon}
                      alt={token.name}
                      style={{
                        width: "100%",
                        height: "100%",
                        objectFit: "cover",
                      }}
                    />
                  </div>
                  <div style={{ flexGrow: 1 }}>
                    <div style={{ fontWeight: 600 }}>{token.name}</div>
                    <div style={{ color: "#666", fontSize: 12 }}>
                      {token.amount || "0"} {token.symbol}
                    </div>
                  </div>
                  {showActions && (
                    <div style={{ display: "flex", gap: 12 }}>
                      <QrCode
                        style={{
                          width: 18,
                          height: 18,
                          color: "#888",
                          cursor: "pointer",
                        }}
                      />
                      <Copy
                        style={{
                          width: 18,
                          height: 18,
                          color: "#888",
                          cursor: "pointer",
                        }}
                      />
                    </div>
                  )}
                </div>
              ))
            )}
          </div>
        </div>
      </div>
    </>
  );
};

export default TokenSelector; 