import { createFileRoute, Link, useNavigate } from '@tanstack/react-router'
import { useQuery } from '@tanstack/react-query'
import { useTranslation } from 'react-i18next'
import { RegisterForm } from '@/features/auth/RegisterForm'
import { fetchRegistrationStatus } from '@/features/auth/api'
import { useRequireGuest } from '@/features/auth/guards'
import { qk } from '@/shared/api/query-keys'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/shared/ui/card'

export const Route = createFileRoute('/register')({ component: RegisterPage })

function RegisterPage() {
  useRequireGuest()
  const { t } = useTranslation()
  const navigate = useNavigate()

  const { data: registration, isLoading } = useQuery({
    queryKey: qk.auth.registration,
    queryFn: fetchRegistrationStatus,
  })

  const disabled = !isLoading && registration?.enabled === false

  return (
    <div className="mx-auto max-w-sm py-8">
      <Card>
        <CardHeader>
          <CardTitle>{t('auth.registerTitle')}</CardTitle>
          <CardDescription>
            {disabled ? t('auth.registrationClosed') : t('auth.registerSubtitle')}
          </CardDescription>
        </CardHeader>
        <CardContent>
          {disabled ? (
            <p className="text-center text-sm text-muted-foreground">
              {t('auth.registrationClosedHint')}{' '}
              <Link to="/login" className="text-primary hover:underline">
                {t('nav.login')}
              </Link>
            </p>
          ) : (
            <>
              <RegisterForm onSuccess={() => void navigate({ to: '/dashboard' })} />
              <p className="mt-4 text-center text-sm text-muted-foreground">
                {t('auth.haveAccount')}{' '}
                <Link to="/login" className="text-primary hover:underline">
                  {t('nav.login')}
                </Link>
              </p>
            </>
          )}
        </CardContent>
      </Card>
    </div>
  )
}
