"use client";

import * as Sentry from "@sentry/nextjs";
import { AlertTriangleIcon } from "lucide-react";
import Link from "next/link";
import { useEffect } from "react";
import { Button } from "@/components/ui/button";

/**
 * Error boundary for the (app) dashboard segment. The sidebar layout stays
 * mounted around this, so we render a sober, centered state inside the content
 * area. Sentry captures the error on mount (same pattern as global-error).
 */
export default function DashboardError({
  error,
  reset,
}: {
  error: Error & { digest?: string };
  reset: () => void;
}) {
  useEffect(() => {
    Sentry.captureException(error);
  }, [error]);

  const isDev = process.env.NODE_ENV === "development";

  return (
    <div className="flex flex-1 items-center justify-center p-8">
      <div className="flex max-w-md flex-col items-center text-center">
        <div className="mb-4 flex size-14 items-center justify-center rounded-full bg-destructive/10 text-destructive">
          <AlertTriangleIcon className="size-7" />
        </div>
        <h2 className="text-lg font-semibold">Une erreur est survenue</h2>
        <p className="mt-2 text-sm text-muted-foreground">
          Un problème inattendu est survenu de notre côté. Vous pouvez réessayer
          ou revenir au tableau de bord.
        </p>

        <div className="mt-6 flex flex-wrap items-center justify-center gap-2">
          <Button onClick={() => reset()}>Réessayer</Button>
          <Button variant="outline" asChild>
            <Link href="/keywords/reservoir">Retour au dashboard</Link>
          </Button>
        </div>

        {isDev ? (
          <pre className="mt-6 max-w-full overflow-x-auto rounded-md bg-muted p-3 text-left text-xs text-muted-foreground">
            {error.message}
            {error.digest ? `\n\nDigest : ${error.digest}` : null}
          </pre>
        ) : error.digest ? (
          <p className="mt-6 text-xs text-muted-foreground">
            Code : {error.digest}
          </p>
        ) : null}
      </div>
    </div>
  );
}
