import {useState, useEffect} from 'react'
import {useSession} from 'next-auth/client'

import HeadLayout from '../components/head-layout'
import Koneksyon from '../components/sesyon/koneksyon'
import Dekoneksyon from '../components/sesyon/dekoneksyon'
import EkriTeks from '../components/soumet/ekri-teks'

import {jwennTeksEpiUserId} from '../lib/oki-api'

export default function Soumet() {
  const [session] = useSession()
  const [teksEpiUserId, setTeksEpiUserId] = useState([])

  useEffect(() => {
    if (session && session.user) {
      const {_id} = session.user
      const jwennTeks = async userId => {
        const teks = await jwennTeksEpiUserId(userId)
        setTeksEpiUserId(teks)
      }

      jwennTeks(_id)
    }
  }, [session])

  return (
    <HeadLayout title='Soumèt' tab={3} slug='soumet'>
      {!session && (
        <Koneksyon
          detay
          tit='Soumèt an tèks'
          soutit='(soumettre un texte)'
          chimen='/soumet'
        />
      )}
      {session && session.user && (
        <>
          <Dekoneksyon position='absolute' top={95} left={5} chimen='/soumet' />
          <EkriTeks session={session} teks={teksEpiUserId} />
        </>
      )}
      {session && !session.user && (
        <Dekoneksyon position='absolute' top={95} left={5} chimen='/soumet' />
      )}
    </HeadLayout>
  )
}
