import { useEffect } from 'react';
import { useNavigate, useParams } from '@tanstack/react-router';
import { Paper, Text, Title, Stack, Loader, Flex } from '@pikku/mantine/core';
import { useI18n } from '@/context/i18n-provider';
import { useMutation } from '@tanstack/react-query';
import { signOut } from '@/lib/auth';
import { asI18n } from '@pikku/react';

export default function LogoutPage() {
  const t = useI18n();
  const navigate = useNavigate();
  const { lang } = useParams({ strict: false }) as { lang?: string }
  const logout = useMutation({
    mutationFn: async () => {
      await signOut()
    }
  })

  useEffect(() => {
    const performLogout = async () => {
      await new Promise((resolve) => setTimeout(resolve, 3000))
      await logout.mutateAsync()
      navigate({ to: lang ? `/${lang}` : '/', replace: true })
    }

    void performLogout()
  }, [lang, navigate])

  return (
    <Flex
      align="center"
      justify="center"
      mih="100vh"
      p="md"
    >
      <Paper p="xl" radius="md" shadow="sm" w="100%" maw="400">
        <Stack align="center" gap="lg">
          <Title order={2} ta="center">
            {t('logout.title')}
          </Title>

          {logout.isPending ? (
            <>
              <Loader size="md" />
              <Text ta="center" c="dimmed">
                {t('logout.loggingout')}
              </Text>
            </>
          ) : logout.isError ? (
            <Text ta="center" c="red">
              {asI18n(`${t('logout.error')}: ${logout.error?.message || 'Unknown error'}`)}
            </Text>
          ) : logout.isSuccess ? (
            <Text ta="center" c="green">
              {t('logout.success')}
            </Text>
          ) : null}
        </Stack>
      </Paper>
    </Flex>
  );
}
