import {
  Link,
  rootRouteId,
  useMatch,
  useRouter,
  useNavigate,
  redirect,
} from '@tanstack/react-router'
import type { ErrorComponentProps } from '@tanstack/react-router'
import {
  Box,
  Button as MantineButton,
  Text,
  Stack,
  Group,
  Collapse,
  Code,
  Container,
  Center
} from '@mantine/core'
import { useDisclosure } from '@mantine/hooks'
import { useEffect } from 'react'
import toast from '@/lib/sonner'
import { logger } from '@/lib/logger'
import { XCircleIcon, WarningIcon } from '@phosphor-icons/react'
import { Trans, useLingui } from '@lingui/react/macro'
import Button from './button'

export function DefaultCatchBoundary({ error }: ErrorComponentProps) {
  const router = useRouter()
  const navigate = useNavigate()
  const { t } = useLingui()
  const isRoot = useMatch({
    strict: false,
    select: (state) => state.id === rootRouteId,
  })
  const [detailsOpened, { toggle: toggleDetails }] = useDisclosure(false)

  const errorMessage = error?.message || t`Unknown error`
  const errorStack = error?.stack || 'No stack trace available'

  useEffect(() => {
    logger.error('DefaultCatchBoundary | ', error)

    if (errorMessage.toLowerCase().includes('unauthenticated')) {
      toast.error(t`You've been logged out`)
      router.history.push('/login')
      throw redirect({ to: '/login' })
    }
  }, [error, errorMessage, navigate])

  if (errorMessage.toLowerCase().includes('unauthorized')) {
    return (
      <Container size="sm" py="xl">
        <Center>
          <Stack align="center" gap="md">
            <XCircleIcon size={64} color="var(--mantine-color-red-6)" />
            <Text size="xl" fw={600}><Trans>Access Denied</Trans></Text>
            <Text c="dimmed" ta="center">
              <Trans>You don't have permission to access this page.</Trans>
            </Text>
            <Group gap="sm" mt="md">
              <Button
                variant="light"
                onClick={() => window.history.back()}
              >
                <Trans>Go Back</Trans>
              </Button>
              <MantineButton
                component={Link}
                to="/"
                variant="filled"
              >
                <Trans>Home</Trans>
              </MantineButton>
            </Group>
          </Stack>
        </Center>
      </Container>
    )
  }

  return (
    <Container size="sm" py="xl">
      <Center>
        <Stack align="center" gap="md" w="100%">
          <WarningIcon size={64} color="var(--mantine-color-red-6)" />

          <Text size="xl" fw={600}><Trans>Something went wrong</Trans></Text>

          <Text c="dimmed" ta="center">
            <Trans>An error occurred while loading this page.</Trans>
          </Text>

          <Box w="100%" mt="md">
            <Text size="sm" c="dimmed" mb="xs"><Trans>Error: {errorMessage}</Trans></Text>
            <Button
              variant="subtle"
              size="compact-sm"
              onClick={toggleDetails}
              fullWidth
            >
              {detailsOpened ? <Trans>Hide details</Trans> : <Trans>Show details</Trans>}
            </Button>
            <Collapse in={detailsOpened}>
              <Code block mt="sm" p="sm" style={{ fontSize: '11px' }}>
                {errorStack}
              </Code>
            </Collapse>
          </Box>

          <Group gap="sm" mt="lg">
            <Button
              variant="light"
              onClick={() => router.invalidate()}
            >
              <Trans>Retry</Trans>
            </Button>
            {isRoot ? (
              <MantineButton
                component={Link}
                to="/"
                variant="filled"
              >
                <Trans>Home</Trans>
              </MantineButton>
            ) : (
              <Button
                variant="filled"
                onClick={() => window.history.back()}
              >
                <Trans>Go Back</Trans>
              </Button>
            )}
          </Group>
        </Stack>
      </Center>
    </Container>
  )
}
