"use client";

import { useEffect, useState } from "react";
import { AlertTriangle, RefreshCw, Home } from "lucide-react";
import { Button } from "@/components/ui/button";
import Link from "next/link";
import { useUserStore } from "@/store";

export default function GlobalError({
  error,
  reset,
}: {
  error: Error & { digest?: string };
  reset: () => void;
}) {
  const { role } = useUserStore();
  const [dashboardUrl, setDashboardUrl] = useState("/dashboard");

  useEffect(() => {
    if (role === "admin") {
      setDashboardUrl("/admin");
    } else {
      setDashboardUrl("/dashboard");
    }
  }, [role]);

  useEffect(() => {
    // Log to your error monitoring service (e.g. Sentry) here
    console.error("[GlobalError]", error);
  }, [error]);

  return (
    <html lang="en" suppressHydrationWarning>
      <body className="bg-gray-50 antialiased" suppressHydrationWarning>
        <div className="min-h-screen flex items-center justify-center px-6">
          <div className="max-w-md w-full text-center space-y-6">
            <div className="flex justify-center">
              <div className="flex h-16 w-16 items-center justify-center rounded-full bg-red-100">
                <AlertTriangle className="h-8 w-8 text-red-600" />
              </div>
            </div>
            <div className="space-y-2">
              <h1 className="text-2xl font-bold text-gray-900">Something went wrong</h1>
              <p className="text-gray-500 text-sm leading-relaxed">
                An unexpected error occurred. Our team has been notified.
              </p>
              {error.digest && (
                <p className="text-xs text-gray-400 font-mono bg-gray-100 rounded px-2 py-1 inline-block">
                  Error ID: {error.digest}
                </p>
              )}
            </div>
            <div className="flex items-center justify-center gap-3">
              <Button onClick={reset} variant="outline" className="gap-2">
                <RefreshCw className="h-4 w-4" />
                Try again
              </Button>
              <Button asChild className="gap-2">
                <Link href={dashboardUrl}>
                  <Home className="h-4 w-4" />
                  Go to Dashboard
                </Link>
              </Button>
            </div>
          </div>
        </div>
      </body>
    </html>
  );
}
