"use client";

import { AlertTriangle, RotateCcw } from "lucide-react";
import Link from "next/link";
import { useEffect } from "react";
import { Button, LINK_BUTTON_CLASS } from "@/components/ui/Button";

// Without this file a failed render drops the user on Next.js's own error
// screen — no navigation, no way back, and in production just "a client-side
// exception occurred". `reset()` re-renders the segment, which is enough for
// the common case of a transient Supabase timeout.
export default function AppError({ error, reset }: { error: Error & { digest?: string }; reset: () => void }) {
  useEffect(() => {
    console.error("Route error:", error);
  }, [error]);

  return (
    <div className="mx-auto flex max-w-lg flex-col items-start gap-4 rounded border border-border bg-white p-6">
      <span className="flex h-10 w-10 items-center justify-center rounded-full bg-danger-bg text-danger-text">
        <AlertTriangle className="h-5 w-5" />
      </span>
      <div>
        <h1 className="text-lg font-bold text-ink">Diese Ansicht konnte nicht geladen werden</h1>
        <p className="mt-1 text-sm text-ink-body">
          Die Daten wurden nicht verändert. Meist hilft ein erneuter Versuch; bleibt der Fehler, wenden Sie sich bitte an die
          IT-Betreuung.
        </p>
      </div>
      {/* The digest is the only handle on the server-side stack trace, which
          is deliberately not sent to the browser in production. */}
      {error.digest && (
        <p className="rounded bg-surface px-3 py-2 font-mono text-xs text-ink-muted">
          Fehlerkennung: {error.digest}
        </p>
      )}
      <div className="flex flex-wrap gap-2">
        <Button onClick={reset}>
          <RotateCcw className="h-4 w-4" />
          Erneut versuchen
        </Button>
        <Link href="/" className={LINK_BUTTON_CLASS}>
          Zur Übersicht
        </Link>
      </div>
    </div>
  );
}
