import React, { useEffect, useState } from 'react'

import useApiUrlStore from '../../../app/store/apiStore'
import type { Account } from '../../../generated/ManagingApi'
import { AccountClient } from '../../../generated/ManagingApi'

import AccountModal from './accountModal'
import AccountTable from './accountTable'

const AccountSettings: React.FC = () => {
  const [accounts, setAccounts] = useState<Account[]>([])
  const [showModal, setShowModal] = useState(false)
  const { apiUrl } = useApiUrlStore()
  const [isFetching, setIsFetching] = useState(false)

  useEffect(() => {
    const client = new AccountClient({}, apiUrl)
    setIsFetching(true)
    client
      .account_GetAccountsBalances()
      .then((data) => {
        setAccounts(data)
      })
      .finally(() => setIsFetching(false))
  }, [])

  function toggleModal() {
    setShowModal(!showModal)
  }

  function openModal() {
    setShowModal(true)
  }

  return (
    <div>
      <div className="container mx-auto">
        <button className="btn" onClick={openModal}>
          Create account
        </button>
        <AccountTable list={accounts} isFetching={isFetching} />
        <AccountModal showModal={showModal} toggleModal={toggleModal} />
      </div>
    </div>
  )
}
export default AccountSettings
