import { h, type FunctionComponent } from 'preact'
import { useLocation, type RouteProps } from 'preact-iso'
import { useAuth } from '../../shared/contexts/auth.tsx'

type AuthRouteProps = {
  auth?: boolean
  user?: any
} & RouteProps<any>

export const Refresh: FunctionComponent<{ path: string }> = () => {
  location.replace(location.href)
}

export const Redirect: FunctionComponent<{ to: string; replace: boolean }> = ({ to, replace = false }) => {
  const { route } = useLocation()

  route(to, replace)
}

export const AuthRoute: FunctionComponent<AuthRouteProps> = ({ auth, component, ...props }) => {
  const { user } = useAuth()

  if (auth === true && !user.value) {
    return <Redirect to='/login' replace={true} />
  } else if (auth === false && user.value) {
    const url = localStorage.getItem('lastVisit') || '/'

    localStorage.removeItem('lastVisit')

    return <Redirect to={url} replace={true} />
  } else {
    return h(component, props)
  }
}
