'use client'

import { useEffect, Suspense } from 'react'
import { useRouter, useSearchParams } from 'next/navigation'
import { useLocale } from 'next-intl'
import { Box, CircularProgress, Typography } from '@mui/material'

function LoginRedirectContent() {
  const router = useRouter()
  const locale = useLocale()
  const searchParams = useSearchParams()

  useEffect(() => {
    // Preserve the redirect parameter when redirecting to the actual login page
    const redirect = searchParams.get('redirect')
    const redirectParam = redirect ? `?redirect=${encodeURIComponent(redirect)}` : ''
    router.replace(`/${locale}/auth/login${redirectParam}`)
  }, [router, locale, searchParams])

  return (
    <Box
      display="flex"
      flexDirection="column"
      alignItems="center"
      justifyContent="center"
      minHeight="100vh"
      gap={2}
    >
      <CircularProgress />
      <Typography variant="body2" color="text.secondary">
        Redirecting to login...
      </Typography>
    </Box>
  )
}

export default function LoginRedirectPage() {
  return (
    <Suspense fallback={
      <Box
        display="flex"
        flexDirection="column"
        alignItems="center"
        justifyContent="center"
        minHeight="100vh"
        gap={2}
      >
        <CircularProgress />
        <Typography variant="body2" color="text.secondary">
          Loading...
        </Typography>
      </Box>
    }>
      <LoginRedirectContent />
    </Suspense>
  )
}