import { AlertCircle, ArrowLeft, Home } from 'lucide-react';

import { useEffect } from 'react';

import { Head, Link } from '@inertiajs/react';

import { Button } from '@/Components/ui/button';
import { trackEvent } from '@/lib/analytics';
import { ERROR_DISPLAYED, ErrorCategory, ErrorSeverity } from '@/lib/event-catalog';
import { captureMessage } from '@/lib/sentry';

const popularLinks = [
  { href: '/', label: 'Home' },
  { href: '/features', label: 'Features' },
  { href: '/pricing', label: 'Pricing' },
  { href: '/blog', label: 'Blog' },
];

interface ErrorProps {
  status: number;
}

const errorMessages: Record<number, { title: string; description: string }> = {
  403: {
    title: "You Don't Have Access",
    description:
      "Your account doesn't have permission to view this page. Head back or return to your dashboard.",
  },
  404: {
    title: 'Page Not Found',
    description:
      "We couldn't find what you were looking for. It may have moved or the link might be broken.",
  },
  419: {
    title: 'Session Expired',
    description:
      'Your session timed out for security. Refresh the page to pick up where you left off.',
  },
  429: {
    title: 'Slow Down a Bit',
    description:
      "You've sent a lot of requests in a short window. Wait a minute or two, then try again.",
  },
  500: {
    title: 'Something Went Wrong',
    description:
      "We hit an unexpected error. Try refreshing the page — if the problem persists, check our status page or reach out to support.",
  },
  503: {
    title: 'Back in a Moment',
    description:
      'RankWiz is briefly unavailable — likely a deploy or maintenance window. Try again in a minute.',
  },
};

export default function Error({ status }: ErrorProps) {
  const error = errorMessages[status] || {
    title: 'Error',
    description: 'An unexpected error occurred.',
  };

  useEffect(() => {
    if (status >= 500) {
      captureMessage(`Error page displayed: ${status} ${error.title}`);
    }

    trackEvent(ERROR_DISPLAYED, {
      error_code: String(status),
      error_message: error.title,
      error_category: status === 403 ? ErrorCategory.AUTH : ErrorCategory.SERVER,
      error_severity: status >= 500 ? ErrorSeverity.CRITICAL : ErrorSeverity.WARNING,
      referrer_url: typeof document !== 'undefined' ? document.referrer : '',
      context: 'Error',
    });
  }, [status, error.title]);

  return (
    <>
      <Head title={`${status} - ${error.title}`} />

      <div className="min-h-screen flex items-center justify-center bg-linear-to-br from-background via-card to-background px-4">
        <div className="w-full max-w-md text-center">
          {/* Error Icon */}
          <div className="flex justify-center mb-6">
            <div className="p-4 rounded-full bg-destructive/10">
              <AlertCircle className="w-8 h-8 text-destructive" />
            </div>
          </div>

          {/* Status Code */}
          <h1 className="text-6xl font-bold text-foreground mb-2">{status}</h1>

          {/* Title */}
          <h2 className="text-2xl font-semibold text-foreground mb-3">{error.title}</h2>

          {/* Description */}
          <p className="text-muted-foreground mb-8 text-lg">{error.description}</p>

          {/* Action Buttons */}
          <div className="flex flex-col sm:flex-row gap-3 justify-center">
            <Button variant="outline" onClick={() => window.history.back()} className="gap-2">
              <ArrowLeft className="w-4 h-4" />
              Go Back
            </Button>
            <Button asChild className="w-full gap-2">
              <Link href="/">
                <Home className="w-4 h-4" />
                Go Home
              </Link>
            </Button>
          </div>

          {/* Support links — shown for 500/503 errors */}
          {(status === 500 || status === 503) && (
            <div className="mt-10 border-t border-border pt-6">
              <p className="text-sm text-muted-foreground mb-3">Need help?</p>
              <nav className="flex flex-wrap justify-center gap-x-6 gap-y-2">
                <a
                  href="https://status.rankwiz.com"
                  target="_blank"
                  rel="noopener noreferrer"
                  className="text-sm text-primary hover:underline"
                >
                  Check status page
                </a>
                <a
                  href="mailto:support@rankwiz.com"
                  className="text-sm text-primary hover:underline"
                >
                  Contact support
                </a>
              </nav>
            </div>
          )}

          {/* Popular links — shown for 404 only */}
          {status === 404 && (
            <div className="mt-10 border-t border-border pt-6">
              <p className="text-sm text-muted-foreground mb-3">Popular pages</p>
              <nav className="flex flex-wrap justify-center gap-x-6 gap-y-2">
                {popularLinks.map((link) => (
                  <Link
                    key={link.href}
                    href={link.href}
                    className="text-sm text-primary hover:underline"
                  >
                    {link.label}
                  </Link>
                ))}
              </nav>
            </div>
          )}
        </div>
      </div>
    </>
  );
}
