'use client';

import { useEffect } from 'react';
import { useParams, useRouter } from '@/framework/navigation';
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 router = useRouter();
  const { lang } = useParams<{ lang?: string }>()
  const logout = useMutation({
    mutationFn: async () => {
      await signOut()
    }
  })

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

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

  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>
  );
}
