import { Show, type JSX } from "solid-js";

import { RouteError } from "~/lib/errors";

import styles from "~/routes/[handle].module.css";

interface ErrorBoundaryProps {
  error: unknown;
  reset: () => void;
}

export default function ErrorBoundary(props: ErrorBoundaryProps): JSX.Element {
  const err = (): Error =>
    props.error instanceof Error ? props.error : new Error(String(props.error));

  const routeError = (): RouteError | null =>
    props.error instanceof RouteError ? props.error : null;

  return (
    <div class={styles.page}>
      <div class={styles.errorContainer}>
        <h1 class={styles.errorTitle}>
          {routeError()?.title ?? "Something went wrong"}
        </h1>
        <p class={styles.errorMessage}>
          {routeError()?.message ??
            "An unexpected error occurred. Please try again."}
        </p>
        <Show when={!routeError()}>
          <details class={styles.errorDetails}>
            <summary>Error details</summary>
            <pre class={styles.errorStack}>{err().stack}</pre>
          </details>
        </Show>
        <div class={styles.errorActions}>
          <button
            classList={{ [styles.button]: true, [styles.buttonSecondary]: true }}
            onClick={() => window.history.back()}
          >
            Go Back
          </button>
          <button class={styles.button} onClick={props.reset}>
            Try Again
          </button>
        </div>
      </div>
    </div>
  );
}
