import { Container, Stack, Title, Text, Button, Loader, Center } from '@pikku/mantine/core'
import { useI18n } from "@/context/i18n-provider"
import { useEffect, useState } from 'react'
import { useLocation, useNavigate, useParams } from '@tanstack/react-router'
import { verifyMagicLink } from '@/lib/auth'
import { asI18n } from '@pikku/react'

const MagicLinkPage: React.FunctionComponent = () => {
  const t = useI18n()
  const searchParams = useLocation({ select: (l) => new URLSearchParams(l.searchStr) })
  const navigate = useNavigate()
  const { lang } = useParams({ strict: false }) as { lang: string }
  const [status, setStatus] = useState<'loading' | 'success' | 'error'>('loading')
  const [errorMessage, setErrorMessage] = useState<string>('')

  useEffect(() => {
    const token = searchParams.get('token')
    const redirect = searchParams.get('redirect') || '/jobs/application'

    if (!token) {
      setStatus('error')
      setErrorMessage(t('magiclink.error.notoken'))
      return
    }

    const completeMagicLinkSignIn = async () => {
      try {
        await verifyMagicLink(token)
        setStatus('success')
        setTimeout(() => {
          navigate({ to: redirect })
        }, 1000)
      } catch (error: any) {
        setStatus('error')
        setErrorMessage(error.message || t('magiclink.error.verificationfailed'))
      }
    }

    completeMagicLinkSignIn()
  }, [searchParams, navigate, t])

  return (
    <Container size="sm" py="xl" my='auto'>
      <Stack gap="xl" align="center">
        {status === 'loading' && (
          <>
            <Center>
              <Loader size="xl" />
            </Center>
            <Title order={1} ta="center">
              {t('magiclink.loading.title')}
            </Title>
          </>
        )}

        {status === 'success' && (
          <>
            <Stack gap="md" align="center">
              <Title order={1} ta="center">
                {t('magiclink.success.title')}
              </Title>
              <Text c="dimmed" ta="center">
                {t('magiclink.success.message')}
              </Text>
            </Stack>
          </>
        )}

        {status === 'error' && (
          <>
            <Stack gap="md" align="center">
              <Title order={1} ta="center">
                {t('magiclink.error.title')}
              </Title>
              <Text c="dimmed" ta="center">
                {t('magiclink.error.message')}
              </Text>
              {errorMessage && (
                <Text size="sm" c="red" ta="center">
                  {asI18n(errorMessage)}
                </Text>
              )}
              <Button
                size="lg"
                mt="md"
                onClick={() => navigate({ to: `/${lang}` })}
              >
                {t('magiclink.error.button')}
              </Button>
            </Stack>
          </>
        )}
      </Stack>
    </Container>
  )
}

export default MagicLinkPage
