import { useEffect } from 'react'
import { useNavigate } from '@tanstack/react-router'
import { trpc } from '@/trpc/client'
import { useUserStore } from '@/stores/userStore'
import { getCurrentUserId } from '@/services/auth'

interface AuthWrapperProps {
  children: React.ReactNode
}

export function AuthWrapper({ children }: AuthWrapperProps) {
  const navigate = useNavigate()
  const { setUser, setLoading, setError, user, isLoading } = useUserStore()

  const { data: staffData, isLoading: isStaffLoading, error: staffError } = trpc.admin.staffUser.getStaff.useQuery()

  useEffect(() => {
    const initializeAuth = async () => {
      const userId = await getCurrentUserId()

      if (!userId) {
        navigate({ to: '/login' as any })
        return
      }

      if (staffData && !isStaffLoading && !staffError) {
        const currentUser = staffData.staff.find((staff: any) => staff.id === userId)

        if (currentUser) {
          setUser({
            id: currentUser.id,
            name: currentUser.name,
            role: currentUser.role,
            permissions: currentUser.permissions,
          })
        } else {
          setError('User not found in staff list')
          navigate({ to: '/login' as any })
        }
      } else if (staffError) {
        setError('Failed to load user data')
        navigate({ to: '/login' as any })
      }
    }

    initializeAuth()
  }, [staffData, isStaffLoading, staffError, navigate, setUser, setError])

  if (isLoading || isStaffLoading) {
    return (
      <div className="flex items-center justify-center min-h-64">
        <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">Loading user data...</p>
        </div>
      </div>
    )
  }

  if (!user) {
    return null // Will redirect
  }

  return <>{children}</>
}