import { createAppKit } from '@reown/appkit'
import { WagmiAdapter } from '@reown/appkit-adapter-wagmi'
import { mainnet, arbitrum, base } from '@reown/appkit/networks'
import { RhinestoneSDK, walletClientToAccount } from '@rhinestone/sdk'
import { useAccount, useWalletClient } from 'wagmi'
// 1. Get projectId from https://dashboard.reown.com
const projectId = 'your-project-id'
// 2. Set up the Wagmi adapter
const wagmiAdapter = new WagmiAdapter({
  networks: [mainnet, arbitrum, base],
  projectId,
})
// 3. Configure the modal
createAppKit({
  adapters: [wagmiAdapter],
  networks: [mainnet, arbitrum, base],
  projectId,
  metadata: {
    name: 'Your dApp',
    description: 'Your dApp description',
    url: 'https://yourdapp.com',
    icons: ['https://yourdapp.com/icon.png']
  }
})
// 4. Use in your React component
export function WalletConnector() {
  const { isConnected } = useAccount()
  const { data: walletClient } = useWalletClient()
  const [rhinestoneAccount, setRhinestoneAccount] = useState(null)
  useEffect(() => {
    async function setupAccount() {
      if (!isConnected || !walletClient) return
      // wrap the wagmi client for the sdk
      const wrappedWalletClient = walletClientToAccount(walletClient)
      // Use the connected wallet client
      const rhinestone = new RhinestoneSDK({
        apiKey: process.env.RHINESTONE_API_KEY,
      })
      const account = await rhinestone.createAccount({
        owners: {
          type: "ecdsa",
          accounts: [wrappedWalletClient],
        },
      });
      setRhinestoneAccount(account)
    }
    setupAccount()
  }, [isConnected, walletClient])
  return (
    <div>
      <w3m-button />
      {rhinestoneAccount && (
        <p>Smart Account: {rhinestoneAccount.getAddress()}</p>
      )}
    </div>
  )
}