import { Link, useNavigate } from '@tanstack/react-router'
import { useEffect, useState } from 'react'
import { isAuthenticated } from '@/services/auth'

export function HomeRoute() {
  const navigate = useNavigate()
  const [isAuthChecked, setIsAuthChecked] = useState(false)
  const [isUserAuthenticated, setIsUserAuthenticated] = useState(false)

  useEffect(() => {
    const checkAuth = async () => {
      const authenticated = await isAuthenticated()
      setIsUserAuthenticated(authenticated)
      setIsAuthChecked(true)

      if (authenticated) {
        navigate({ to: '/user-home' as any })
      }
    }

    checkAuth()
  }, [navigate])

  if (!isAuthChecked) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-50">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto"></div>
          <p className="mt-4 text-gray-600">Checking authentication...</p>
        </div>
      </div>
    )
  }

  if (isUserAuthenticated) {
    return null // Will redirect via useEffect
  }

  return (
    <div className="min-h-screen flex items-center justify-center bg-gray-50">
      <div className="max-w-md w-full bg-white rounded-lg shadow-md p-8 text-center">
        <h1 className="text-3xl font-bold text-gray-900 mb-4">
          Welcome to Freshyo Admin
        </h1>
        <p className="text-gray-600 mb-8">
          Manage your meat delivery platform with ease
        </p>
        <Link
          to="/login"
          className="inline-block bg-blue-600 text-white px-6 py-3 rounded-md hover:bg-blue-700 font-medium transition-colors"
        >
          Login to Dashboard
        </Link>
      </div>
    </div>
  )
}