"use client";

import * as React from "react";
import Link from "next/link";
import { AlertTriangle, RotateCcw } from "lucide-react";
import { Button } from "@/components/ui/button";

interface ErrorStateProps {
  error: Error & { digest?: string };
  reset: () => void;
  /** Compact variant used inside the dashboard shell. */
  compact?: boolean;
}

/**
 * Shared body for Next.js error boundaries.
 *
 * Client component: boundaries must be client-rendered. Logs to the console for
 * local debugging — `digest` is the only detail Next.js forwards from a
 * server-rendered error, so it is surfaced to help correlate with server logs.
 */
export function ErrorState({ error, reset, compact = false }: ErrorStateProps) {
  React.useEffect(() => {
    console.error("Unhandled application error:", error);
  }, [error]);

  return (
    <div
      className={
        compact
          ? "flex flex-col items-center justify-center gap-4 rounded-xl border border-subtle bg-surface px-6 py-12 text-center"
          : "flex min-h-screen flex-col items-center justify-center gap-6 bg-sunken px-6 text-center"
      }
    >
      <div className="flex size-14 items-center justify-center rounded-2xl bg-danger-50 ring-1 ring-danger-100 dark:bg-danger-600/15 dark:ring-danger-600/30">
        <AlertTriangle className="size-7 text-danger-600" />
      </div>
      <div className="space-y-2">
        <h1 className="text-xl font-bold text-primary sm:text-2xl">Terjadi kesalahan</h1>
        <p className="mx-auto max-w-md text-sm text-secondary">
          Kami tidak dapat memuat bagian ini. Silakan coba lagi — bila masalah berlanjut, hubungi
          administrator sistem.
        </p>
        {error.digest ? (
          <p className="font-mono text-xs text-tertiary">Kode kesalahan: {error.digest}</p>
        ) : null}
      </div>
      <div className="flex flex-wrap items-center justify-center gap-3">
        <Button onClick={reset}>
          <RotateCcw className="size-4" />
          Coba lagi
        </Button>
        <Button asChild variant="secondary">
          <Link href="/dashboard">Kembali ke Dasbor</Link>
        </Button>
      </div>
    </div>
  );
}
