'use client'

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

const MagicLinkPage: React.FunctionComponent = () => {
  const t = useI18n()
  const searchParams = useSearchParams()
  const router = useRouter()
  const { lang } = useParams<{ 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(() => {
          router.push(redirect)
        }, 1000)
      } catch (error: any) {
        setStatus('error')
        setErrorMessage(error.message || t('magiclink.error.verificationfailed'))
      }
    }

    completeMagicLinkSignIn()
  }, [searchParams, router, 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={() => router.push(`/${lang}`)}
              >
                {t('magiclink.error.button')}
              </Button>
            </Stack>
          </>
        )}
      </Stack>
    </Container>
  )
}

export default MagicLinkPage
