"use client";

import Link from "next/link";
import { PRIMARY_COLOR, PRIMARY_COLOR_HOVER } from "@/lib/common";

const ERROR_500_ACCENT = "#FFA626";

export interface ErrorPageProps {
  code: number;
  title: string;
  message: string;
  actionLabel?: string;
  actionLink?: string;
  /** When provided, action renders as a button that calls this instead of linking */
  onActionClick?: () => void;
}

const ERROR_COLORS: Record<number, string> = {
  404: PRIMARY_COLOR,
  500: ERROR_500_ACCENT,
};

const ACTION_BUTTON_CLASS =
  "px-6 py-3 rounded-lg text-white font-semibold shadow-md transition transform hover:scale-105";

export default function ErrorPage({
  code,
  title,
  message,
  actionLabel = "Go Home",
  actionLink = "/",
  onActionClick,
}: ErrorPageProps) {
  const isError500 = code === 500;
  const codeColor = ERROR_COLORS[code] ?? PRIMARY_COLOR;
  const defaultBg = isError500 ? ERROR_500_ACCENT : PRIMARY_COLOR;
  const hoverBg = isError500 ? PRIMARY_COLOR : PRIMARY_COLOR_HOVER;

  const buttonStyle = { backgroundColor: defaultBg };

  const setHover = (e: React.MouseEvent<HTMLAnchorElement | HTMLButtonElement>, bg: string) => {
    e.currentTarget.style.backgroundColor = bg;
  };

  return (
    <div className="flex flex-col items-center justify-center min-h-screen bg-gray-100 p-6">
      <h1
        className="text-[10rem] sm:text-[15rem] font-extrabold mb-4"
        style={{ color: codeColor }}
      >
        {code}
      </h1>

      <p
        className="text-3xl sm:text-4xl font-semibold mb-2 animate-bounce"
        style={{ color: isError500 ? ERROR_500_ACCENT : PRIMARY_COLOR }}
      >
        {title}
      </p>

      <p className="text-lg text-gray-700 mb-6 text-center max-w-md">{message}</p>

      {onActionClick ? (
        <button
          type="button"
          className={ACTION_BUTTON_CLASS}
          style={buttonStyle}
          onMouseEnter={(e) => setHover(e, hoverBg)}
          onMouseLeave={(e) => setHover(e, defaultBg)}
          onClick={onActionClick}
        >
          {actionLabel}
        </button>
      ) : (
        <Link
          href={actionLink}
          className={ACTION_BUTTON_CLASS}
          style={buttonStyle}
          onMouseEnter={(e) => setHover(e, hoverBg)}
          onMouseLeave={(e) => setHover(e, defaultBg)}
        >
          {actionLabel}
        </Link>
      )}
    </div>
  );
}
