/**
 * Protected Route Component
 * Checks authentication and token validity before rendering protected content
 */

import { useEffect, useState } from 'react'
import { Navigate, useLocation } from 'react-router-dom'
import { apiClientV2 } from '@/services/apiV2'

interface ProtectedRouteProps {
  children: React.ReactNode
  requireAdmin?: boolean
}

export default function ProtectedRoute({ children, requireAdmin = false }: ProtectedRouteProps) {
  const location = useLocation()
  const [isChecking, setIsChecking] = useState(true)
  const [isValid, setIsValid] = useState(false)
  const [isAdmin, setIsAdmin] = useState(false)

  useEffect(() => {
    const checkAuth = async () => {
      try {
        // Check if user is authenticated
        if (!apiClientV2.isAuthenticated()) {
          console.warn('User not authenticated, redirecting to login')
          setIsValid(false)
          setIsChecking(false)
          return
        }

        // Verify token with backend
        const user = await apiClientV2.getMe()

        // Check if user has admin privileges (if required)
        if (requireAdmin) {
          const adminEmails = ['ymirliu@panjit.com.tw'] // Admin email list
          const userIsAdmin = adminEmails.includes(user.email)
          setIsAdmin(userIsAdmin)

          if (!userIsAdmin) {
            console.warn('User is not admin, access denied')
            setIsValid(false)
            setIsChecking(false)
            return
          }
        }

        setIsValid(true)
        setIsChecking(false)
      } catch (error) {
        console.error('Authentication check failed:', error)
        apiClientV2.clearAuth()
        setIsValid(false)
        setIsChecking(false)
      }
    }

    checkAuth()
  }, [requireAdmin, location.pathname])

  // Show loading while checking
  if (isChecking) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
          <p className="text-gray-600">驗證中...</p>
        </div>
      </div>
    )
  }

  // Redirect to login if not authenticated
  if (!isValid) {
    if (requireAdmin && apiClientV2.isAuthenticated() && !isAdmin) {
      // User is authenticated but not admin
      return (
        <div className="flex items-center justify-center min-h-screen">
          <div className="text-center">
            <h1 className="text-2xl font-bold text-red-600 mb-4">訪問被拒絕</h1>
            <p className="text-gray-600 mb-4">您沒有權限訪問此頁面</p>
            <a href="/" className="text-blue-600 hover:underline">返回首頁</a>
          </div>
        </div>
      )
    }

    return <Navigate to="/login" state={{ from: location }} replace />
  }

  return <>{children}</>
}
