import type { ErrorRouteComponent } from "@tanstack/solid-router";
import { createSignal, Show } from "solid-js";

// Modified from https://github.com/TanStack/router/blob/61d767049e57420a1eb5dcb77994d970aa8f64fa/packages/solid-router/src/CatchBoundary.tsx#L36-L78
export const DefaultErrorComponent: ErrorRouteComponent = ({ error, reset, info }) => {
  const [showError, setShowError] = createSignal(process.env.NODE_ENV !== "production");

  return (
    <div style={{ padding: ".5rem", "max-width": "100%" }}>
      <div style={{ display: "flex", "align-items": "center", gap: ".5rem" }}>
        <strong style={{ "font-size": "1rem" }}>Oh no, something went wrong :(</strong>
        <button
          onClick={() => setShowError((d) => !d)}
          style={{
            appearance: "none",
            "font-size": ".6em",
            border: "1px solid currentColor",
            padding: ".1rem .2rem",
            "font-weight": "bold",
            "border-radius": ".25rem",
          }}
          type="button"
        >
          {showError() ? "Hide Error" : "Show Error"}
        </button>
        <button
          onClick={reset}
          style={{
            appearance: "none",
            "font-size": ".6em",
            border: "1px solid currentColor",
            padding: ".1rem .2rem",
            "font-weight": "bold",
            "border-radius": ".25rem",
          }}
          type="button"
        >
          Try again?
        </button>
      </div>

      <div style={{ height: ".25rem" }} />

      <Show when={showError()}>
        <div>
          <pre
            style={{
              "font-size": ".7em",
              border: "1px solid red",
              "border-radius": ".25rem",
              padding: ".3rem",
              color: "red",
              overflow: "auto",
            }}
          >
            <code style={{ "text-wrap": "wrap" }}>
              {error.message}
              {error.cause ? ` caused by ${error.cause}` : ""}
              {"\n"}
              {error.stack}
            </code>

            {info?.componentStack}
          </pre>
        </div>
      </Show>
    </div>
  );
};
