import React, {useEffect} from 'react'
import Legacy from './Legacy'
import {UStoreProvider} from "@ustore/core";
import {useNavigate, useParams} from 'react-router-dom'
import urlGenerator from '$ustoreinternal/services/urlGenerator'


const Product = (props) => {
    const params = useParams()
    const navigate = useNavigate()

    useEffect(() => {
        (async () => {
            try {
                const productID = await UStoreProvider.api.products.getProductIDByFriendlyID(params.id)
                const currentProduct = await UStoreProvider.api.products.getProductByID(productID, false)
                UStoreProvider.state.customState.setBulk({currentProduct})
            } catch (e) {
                navigate(`${urlGenerator.get({page: 'product-offline'})}`)
            }
        })()
        return () => {
            UStoreProvider.state.customState.delete('currentProduct')
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [])

    if (!props.customState?.currentProduct) {
        return null
    }
    return <Legacy {...props}/>
}
export default Product
