import { type ErrorComponentProps, Link } from '@tanstack/react-router'

import { Button, Card, CardContent, CardFooter, CardHeader, CardTitle } from '@postxl/ui-components'

const isDev = import.meta.env.DEV

export const DefaultErrorPage = ({ error }: { error: ErrorComponentProps }) => {
  const actualError = error.error
  const errorMessage = actualError instanceof Error ? actualError.message : String(actualError)
  const errorStack = actualError instanceof Error ? actualError.stack : undefined

  return (
    <div className="flex w-full pt-4 px-4 h-(--content-without-header) items-center justify-center">
      <Card className="max-w-3xl w-full">
        <CardHeader>
          <CardTitle className="text-destructive">An unexpected error occurred</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="p-4 bg-destructive/10 border border-destructive/20 rounded-md">
            <p className="font-mono text-sm text-destructive break-words">{errorMessage}</p>
          </div>

          {isDev && errorStack && (
            <details>
              <summary className="cursor-pointer text-sm text-muted-foreground hover:text-foreground">
                Show stack trace
              </summary>
              <pre className="mt-2 p-4 bg-muted rounded-md overflow-auto text-xs font-mono whitespace-pre-wrap break-words max-h-96">
                {errorStack}
              </pre>
            </details>
          )}

          {isDev && (
            <details>
              <summary className="cursor-pointer text-sm text-muted-foreground hover:text-foreground">
                Show raw error data
              </summary>
              <pre className="mt-2 p-4 bg-muted rounded-md overflow-auto text-xs font-mono whitespace-pre-wrap break-words max-h-64">
                {JSON.stringify(error, null, 2)}
              </pre>
            </details>
          )}
        </CardContent>
        <CardFooter>
          <Button asChild>
            <Link to={'/'}>Back to Home</Link>
          </Button>
        </CardFooter>
      </Card>
    </div>
  )
}
