import { FC, useEffect } from 'react'
import { Route, Routes, useParams } from 'react-router-dom'
import { Pages } from '../config/Pages'
import Login from '../pages/auth/Login'
import Register from '../pages/auth/Register'
import { useGetSlugId } from '../pages/home/hooks/useHomeData'
import { ErrorType } from '../helpers/types'
import { toast } from '../components/Toast'

const AuthRouter: FC = () => {

    const { slug } = useParams()
    const getSlugId = useGetSlugId()
    useEffect(() => {
        if (slug) {
            const slug_id = localStorage.getItem(import.meta.env.VITE_SLUG_ID)
            const slug_parse = slug_id ? JSON.parse(slug_id) : null
            if (slug_parse && slug_parse.slug === slug) {

                return
            } else {
                getSlugId.mutate(slug, {
                    onSuccess: (data) => {
                        localStorage.setItem(import.meta.env.VITE_SLUG_ID, JSON.stringify(data?.data?.business))
                        window.location.reload()
                    },
                    onError: (error: ErrorType) => {
                        toast(error?.response?.data?.error?.message[0] || 'خطا در دریافت اطلاعات', 'error')
                        // window.location.href = 'https://danakcorp.com'
                    }
                })
            }
        }
    }, [slug])

    return (
        <Routes>
            <Route path={Pages.auth.login} element={<Login />} />
            <Route path={Pages.auth.register} element={<Register />} />
        </Routes>
    )
}

export default AuthRouter