import React, { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { UStoreProvider } from '@ustore/core'
import themeContext from '$ustoreinternal/services/themeContext'
import DraftsModel from '../components/drafts/model/DraftsModel'
import DraftsNG from '../components/drafts/DraftsNG'
import Layout from '../components/layout'
import './Drafts.scss'

const Drafts = (props) => {
  const { state: { currentStore } } = props
  const { storeBaseUrl, languageCode } = themeContext.get()
  const navigate = useNavigate()
  const [draftsModel, setDraftsModel] = useState(null)

  useEffect(() => {
    const currentStoreFromState = UStoreProvider.state.get()['currentStore']
    const maxDraftsFromStore = currentStoreFromState?.Attributes?.find(
      (attr) => attr.Name === 'MaxDrafts'
    )?.Value

    const model = new DraftsModel({
      UStoreProvider,
      storeBaseUrl,
      storeApiUrl: UStoreProvider.contextService.getValue('apiUrl'),
      navigate,
      maxDrafts: maxDraftsFromStore ?? 3
    })

    setDraftsModel(model)
    model.init()

    return () => {
      setDraftsModel(null)
    }
  }, [currentStore?.Attributes, navigate, storeBaseUrl])

  return (
    <Layout className="drafts-page" {...props}>
      <DraftsNG model={draftsModel} />
    </Layout>
  )
}

export default Drafts
