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

import useApiUrlStore from '../../../app/store/apiStore'
import type { MoneyManagement } from '../../../generated/ManagingApi'
import { MoneyManagementClient } from '../../../generated/ManagingApi'

import MoneyManagementModal from './moneyManagementModal'
import MoneyManagementTable from './moneymanagementTable'

const MoneyManagementSettings: React.FC = () => {
  const [moneyManagements, setMoneyManagements] = useState<MoneyManagement[]>(
    []
  )
  const [showModal, setShowModal] = useState(false)
  const { apiUrl } = useApiUrlStore()

  useEffect(() => {
    const client = new MoneyManagementClient({}, apiUrl)
    client.moneyManagement_GetMoneyManagements().then((data) => {
      setMoneyManagements(data)
    })
  }, [])

  function toggleModal() {
    setShowModal(!showModal)
  }

  function openModal() {
    setShowModal(true)
  }

  function closeModal() {
    setShowModal(false)
  }

  return (
    <div>
      <div className="container mx-auto">
        <button className="btn" onClick={openModal}>
          Create new money management
        </button>
        <MoneyManagementTable list={moneyManagements} />
        <MoneyManagementModal
          showModal={showModal}
          toggleModal={toggleModal}
          onClose={closeModal}
        />
      </div>
    </div>
  )
}
export default MoneyManagementSettings
