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

import Modal from './modal'
import constants from '../constants.json'

import styles from './dbSelector.module.css'

export default function DbSelector({ onDbSelect, closeClick, text, showAll }) {
  const [qdbs, setQdbs] = useState(null)

  useEffect(() => {
    fetch(`${constants.apiUrl}getDbs`, {
      credentials: 'include',
    })
      .then((resp) => {
        return resp.json()
      })
      .then((data) => {
        setQdbs(data)
      })
  }, [])

  return React.createElement(
    Modal,
    closeClick
      ? {
          closeClick: () => {
            closeClick()
          },
        }
      : {},
    <>
      {text && <div className={styles.text}>{text}</div>}
      <div className={styles.container}>
        {qdbs ? (
          <>
            {' '}
            {qdbs.map((qdb) => {
              return (
                <div
                  className={styles.listItem}
                  onClick={() => {
                    onDbSelect(qdb)
                    closeClick()
                  }}
                  key={qdb.name}
                >
                  {qdb.name}
                </div>
              )
            })}
            {showAll && (
              <div
                className={styles.listItem}
                onClick={() => {
                  onDbSelect('all')
                  closeClick()
                }}
              >
                {'Összes'}
              </div>
            )}
          </>
        ) : (
          '...'
        )}
      </div>
    </>
  )
}
