import { useEffect, useState } from 'react';
import { invoke } from '@tauri-apps/api/core';

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

  async function signIn() {
    let [serverDomain, username] = await invoke('start_account_auth', {instanceDomain: 'social.tempest.dev'}) as string[]
    setSignedIn({serverDomain, username})
  }

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

  useEffect(() => {
    (async () => {
      setExistingAccounts(await invoke('get_all_accounts'))
    })()
  }, [])

  return (
    <>
      {!signedIn ? (
        <>
          <p>Existing accounts:</p>
          {existingAccounts.map(({username, server_domain}: {username: string, server_domain: string}) => (
            <>
              <button key={username + server_domain} onClick={() => setSignedIn({serverDomain: server_domain, username})}>@{username}@{server_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>
      ))}
    </>
  )
}
