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

import { InfoCard } 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 (
    <InfoCard variant="error" title="An unexpected error occurred" message={errorMessage} showHomeButton>
      {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>
      )}
    </InfoCard>
  )
}
