import clsx from "clsx";
import Head from "next/head";
import Link from "next/link";
import { useMemo } from "react";
import { ErrorProps } from "next/error";
import randomRange from "libs/randomRange";

import styles from "styles/error.module.scss";

const statusCodes = {
  400: "Bad Request",
  404: "This page could not be found",
  405: "Method Not Allowed",
  500: "Internal Server Error",
};

const MyError = (props: ErrorProps) => {
  const { statusCode } = props;
  const title =
    props.title ||
    statusCodes[`${statusCode}` as unknown as keyof typeof statusCodes] ||
    "An unexpected error has occurred";
  const bgNumber = useMemo(() => randomRange(1, 5), []);

  return (
    <div className={clsx(styles["page"], styles[`bg-${bgNumber}`])}>
      <Head>
        <title>
          {statusCode
            ? `${statusCode}: ${title}`
            : "Application error: a client-side exception has occurred"}
        </title>
      </Head>
      <div className={clsx(styles["main"])}>
        {statusCode ? <h1 className="next-error-h1">{statusCode}</h1> : null}
        <h2>
          {props.title || statusCode
            ? title
            : "Application error: a client-side exception has occurred (see the browser console for more information)"}
          .
        </h2>
        <Link className="btn btn-primary" href="/">
          Back to Home
        </Link>
      </div>
    </div>
  );
};

export default MyError;
