'use client';

import * as Sentry from '@sentry/nextjs';
import { useTranslations } from 'next-intl';
import { useEffect, useState } from 'react';

export default function GlobalError({
  error,
  reset,
}: {
  error: Error & { digest?: string };
  reset: () => void;
}) {
  const [retryCount, setRetryCount] = useState(0);
  const [autoRetrying, setAutoRetrying] = useState(false);
  const t = useTranslations();

  useEffect(() => {
    Sentry.captureException(error);
    if (process.env.NODE_ENV !== 'production') {
      console.error('Unhandled error:', error);
    }
  }, [error]);

  // Auto-retry once after 3 seconds
  useEffect(() => {
    if (retryCount > 0) return;
    setAutoRetrying(true);
    const timer = setTimeout(() => {
      setAutoRetrying(false);
      setRetryCount((c) => c + 1);
      reset();
    }, 3000);
    return () => clearTimeout(timer);
  }, [error, reset, retryCount]);

  const handleRetry = () => {
    setRetryCount((c) => c + 1);
    reset();
  };

  return (
    <div className="flex min-h-screen flex-col items-center justify-center bg-background px-4" role="alert">
      <div className="mx-auto max-w-md text-center">
        <div className="mx-auto flex h-16 w-16 items-center justify-center rounded-full bg-destructive/10">
          <svg
            className="h-8 w-8 text-destructive"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
            aria-hidden="true"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L4.082 16.5c-.77.833.192 2.5 1.732 2.5z"
            />
          </svg>
        </div>
        <h1 className="mt-4 text-2xl font-bold tracking-tight">
          {t('error.title')}
        </h1>
        <p className="mt-2 text-muted-foreground">
          {autoRetrying ? t('error.autoRetrying') : t('error.description')}
        </p>
        {error.digest && (
          <p className="mt-1 text-xs text-muted-foreground">
            {t('common.errorCode', { code: error.digest })}
          </p>
        )}
        {retryCount > 0 && (
          <p className="mt-1 text-xs text-muted-foreground">
            {t('common.retriedCount', { count: retryCount })}
          </p>
        )}
        <div className="mt-8 flex justify-center gap-3">
          <button
            onClick={handleRetry}
            disabled={autoRetrying}
            className="inline-flex h-10 items-center justify-center rounded-md bg-primary px-6 text-sm font-medium text-primary-foreground shadow transition-colors hover:bg-primary/90 disabled:opacity-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
          >
            {autoRetrying ? (
              <>
                <svg className="mr-2 h-4 w-4 animate-spin" viewBox="0 0 24 24" fill="none" aria-hidden="true">
                  <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
                  <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
                </svg>
                {t('common.retrying')}
              </>
            ) : (
              t('common.retry')
            )}
          </button>
          <a
            href="/"
            className="inline-flex h-10 items-center justify-center rounded-md border border-input bg-background px-6 text-sm font-medium shadow-sm transition-colors hover:bg-accent hover:text-accent-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
          >
            {t('common.goHome')}
          </a>
        </div>
      </div>
    </div>
  );
}
