import { AlertTriangle } from 'lucide-react';

type PanelErrorFallbackProps = {
  error: Error;
  reset: () => void;
  /** Null when the panel is not interactive — then there is nothing to clear it back to. */
  onClearApp: (() => void) | null;
};

/**
 * One panel's app threw. The workspace around it keeps running — the other panels are still live, and
 * that is the whole point: a dashboard left running overnight should not be taken to a white screen by
 * whichever app happened to receive a malformed value.
 *
 * Compact on purpose. A panel can be 200px tall, so the stack lives behind a `<details>` and the two
 * recoveries are the only things guaranteed to be visible.
 */
export const PanelErrorFallback = ({ error, reset, onClearApp }: PanelErrorFallbackProps) => (
  <div className="flex h-full w-full flex-col items-center justify-center gap-2 overflow-auto p-3 text-center">
    <AlertTriangle className="size-5 shrink-0 text-amber-500" />
    <p className="text-sm font-medium">This panel failed to render</p>
    <p className="text-muted-foreground max-w-full truncate text-xs" title={error.message}>
      {error.message || 'Unknown error'}
    </p>
    <div className="flex flex-wrap items-center justify-center gap-2 pt-1">
      <button
        type="button"
        onClick={reset}
        className="cursor-pointer rounded border px-2 py-1 text-xs transition-colors hover:bg-black/5"
      >
        Try again
      </button>
      {onClearApp && (
        <button
          type="button"
          onClick={onClearApp}
          className="cursor-pointer rounded border px-2 py-1 text-xs transition-colors hover:bg-black/5"
        >
          Clear this panel
        </button>
      )}
    </div>
    {error.stack && (
      <details className="w-full text-left">
        <summary className="text-muted-foreground cursor-pointer select-none text-[11px]">Details</summary>
        <pre className="mt-1 max-h-40 overflow-auto whitespace-pre-wrap text-[10px] opacity-70">{error.stack}</pre>
      </details>
    )}
  </div>
);
