import { useEffect, useState } from 'react'
import { createFileRoute, useNavigate } from '@tanstack/react-router'
import { Alert, Button, Center, Paper, Stack, Text, Title } from '@pikku/mantine/core'
import { m } from '@/i18n/messages'
import { useLocale } from '@/i18n/config'
import { asI18n } from '@pikku/react'
import { useQueryClient } from '@tanstack/react-query'

function LogoutPage() {
  useLocale()
  const navigate = useNavigate()
  const queryClient = useQueryClient()
  const [error, setError] = useState<string | null>(null)
  const [done, setDone] = useState(false)

  useEffect(() => {
    let cancelled = false
    const run = async () => {
      try {
        const csrfRes = await fetch('/auth/csrf', { credentials: 'include' })
        const { csrfToken } = (await csrfRes.json()) as { csrfToken: string }
        const body = new URLSearchParams({ csrfToken, callbackUrl: '/login' })
        await fetch('/auth/signout', {
          method: 'POST',
          headers: { 'content-type': 'application/x-www-form-urlencoded' },
          body,
          credentials: 'include',
          redirect: 'manual',
        })
        if (cancelled) return
        queryClient.clear()
        setDone(true)
      } catch (err) {
        if (!cancelled) setError(String((err as Error).message))
      }
    }
    run()
    return () => {
      cancelled = true
    }
  }, [queryClient])

  return (
    <Center mih="100vh" p="md">
      <Paper withBorder radius="md" p="xl" maw={420} w="100%">
        <Stack gap="md">
          <Title order={2}>{m.auth_logout_title({ defaultValue: 'Signed out' })}</Title>
          {error && <Alert color="red">{asI18n(error)}</Alert>}
          {!done && !error && (
            <Text size="sm" c="dimmed">
              {m.auth_logout_signing_out({ defaultValue: 'Signing you out…' })}
            </Text>
          )}
          {done && (
            <>
              <Text size="sm" c="dimmed">
                {m.auth_logout_cleared({ defaultValue: 'Your session has been cleared.' })}
              </Text>
              <Button onClick={() => navigate({ to: '/login' })}>
                {m.auth_logout_sign_in_again({ defaultValue: 'Sign in again' })}
              </Button>
            </>
          )}
        </Stack>
      </Paper>
    </Center>
  )
}

export const Route = createFileRoute('/logout')({
  component: LogoutPage,
})
