import type { JSX, PropsWithChildren } from "react";
import { createContext, useCallback, useContext, useMemo, useState } from "react";

export type WalletName = "phantom" | "solflare" | "backpack";

const WALLET_ADDRESSES: Record<WalletName, string> = {
  phantom: "Gh9Z…k3mP",
  solflare: "Bx3K…7pRq",
  backpack: "Kx7P…2mJc",
};

interface WalletContextValue {
  connected: boolean;
  address: string | null;
  connect: (wallet: WalletName) => void;
  disconnect: () => void;
}

const WalletContext = createContext<WalletContextValue | null>(null);

export function WalletProvider({ children }: PropsWithChildren): JSX.Element {
  const [address, setAddress] = useState<string | null>(null);

  const connect = useCallback((wallet: WalletName) => {
    setAddress(WALLET_ADDRESSES[wallet]);
  }, []);

  const disconnect = useCallback(() => {
    setAddress(null);
  }, []);

  const value = useMemo<WalletContextValue>(
    () => ({ connected: address !== null, address, connect, disconnect }),
    [address, connect, disconnect],
  );

  return <WalletContext.Provider value={value}>{children}</WalletContext.Provider>;
}

export function useWallet(): WalletContextValue {
  const ctx = useContext(WalletContext);
  if (!ctx) throw new Error("useWallet must be used within a WalletProvider");
  return ctx;
}
