import { ReactNode, useEffect } from "react"
import { Navigate, Outlet, useLocation } from "react-router-dom"
import { useKeyring } from "../hooks"

export const ProtectedRoute = ({ children }: { children?: ReactNode }) => {
    const location = useLocation()
    const {
        lock,
        keyring: { isLocked, hasPassword },
    } = useKeyring()

    useEffect(() => {
        if (!isLocked && hasPassword && location.key === "default") {
            lock()
        }
    }, []);

    return !hasPassword ? (
        <Navigate to="/welcome" replace />
    ) : isLocked ? (
        <Navigate
            to="/unlock-keyring"
            replace
            state={{
                from: location,
                pathname: location.pathname,
                search: location.search,
            }}
        />
    ) : (
        (children ?? <Outlet />)
    )
}
