import { useEffect, useState } from 'react';
import { Accounts } from '../bindings/'
import { Account } from '../bindings/Account';

export default function Root() {
  const [existingAccounts, setExistingAccounts] = useState<Account[]>([])
  const [signedIn, setSignedIn] = useState<{serverDomain: string, username: string} | null>(null)
  const [accountData, setAccountData] = useState('')

  async function signIn() {
    let [serverDomain, username] = await Accounts.startAccountAuth('social.tempest.dev')

    setSignedIn({serverDomain, username})
  }

  async function getSelf() {
    if (!signedIn) throw new Error("Not signed in")
    const {serverDomain, username} = signedIn;
    let result = await Accounts.getSelf(serverDomain, username)
    setAccountData(JSON.parse(result))
  }

  useEffect(() => {
    (async () => {
      const result = await Accounts.getAllAccounts()
      setExistingAccounts(result)
    })()
  }, [])

  return (
    <>
      {!signedIn ? (
        <>
          <p>Existing accounts:</p>
          {existingAccounts.map(({username, domain}) => (
            <>
              <button key={username + domain} onClick={() => setSignedIn({serverDomain: domain, username})}>@{username}@{domain}</button>
              <br/>
            </>
          ))}
          <button onClick={signIn}>Add another account</button>
        </>
      ) : (!accountData ? (
        <button onClick={getSelf}>Retrieve account data</button>
      ):(
        <p>Result from rust: <pre style={{whiteSpace:'pre'}}>{JSON.stringify(accountData, null, 2)}</pre></p>
      ))}
    </>
  )
}
