'use client'

import { useEffect } from 'react'
import Link from 'next/link'
import { Button } from '@/components/ui/button'
import { AlertTriangle, RefreshCw } from 'lucide-react'
import { isChunkLoadError, attemptChunkErrorRecovery } from '@/lib/chunk-error-recovery'

export default function Error({
  error,
  reset,
}: {
  error: Error & { digest?: string }
  reset: () => void
}) {
  useEffect(() => {
    console.error('Application error:', error)

    if (isChunkLoadError(error)) {
      attemptChunkErrorRecovery('root')
    }
  }, [error])

  const isChunk = isChunkLoadError(error)

  return (
    <div className="flex min-h-screen flex-col items-center justify-center px-4 py-16 text-center">
      <div className="flex h-16 w-16 items-center justify-center rounded-full bg-primary/10">
        <AlertTriangle className="h-8 w-8 text-primary" />
      </div>
      <h1 className="mt-6 text-display font-bold text-brand-blue">
        Something went wrong
      </h1>
      <p className="mt-4 max-w-md text-body text-muted-foreground">
        {isChunk
          ? 'A new version of the platform may have been deployed. Please reload the page.'
          : 'An unexpected error occurred. Please try again or return to the dashboard.'}
      </p>
      {!isChunk && error.digest && (
        <p className="mt-2 text-tiny text-muted-foreground/60">
          Error ID: {error.digest}
        </p>
      )}
      <div className="mt-8 flex gap-4">
        {isChunk ? (
          <Button size="lg" onClick={() => window.location.reload()}>
            <RefreshCw className="mr-2 h-4 w-4" />
            Reload Page
          </Button>
        ) : (
          <>
            <Button size="lg" onClick={() => reset()}>
              Try Again
            </Button>
            <Button variant="outline" size="lg" asChild>
              <Link href="/">Return to Dashboard</Link>
            </Button>
          </>
        )}
      </div>
    </div>
  )
}
