import Link from "next/link";
import { notFound } from "next/navigation";

const isDevLoginEnabled =
  process.env.NODE_ENV !== "production" ||
  process.env.ALLOW_TEST_LOGIN === "true" ||
  process.env.PLAYWRIGHT_TEST === "true";

const testAuthSecret = process.env.TEST_AUTH_SECRET ?? "";

const roleLinks = [
  {
    role: "ADMIN",
    label: "Continue as Admin",
    description: "Full access for account setup, publishing, and settings validation.",
  },
  {
    role: "EDITOR",
    label: "Continue as Editor",
    description: "Content creation and workflow validation without admin-only controls.",
  },
  {
    role: "VIEWER",
    label: "Continue as Viewer",
    description: "Read-only validation for dashboards, analytics, and navigation.",
  },
] as const;

function buildLoginHref(role: string) {
  const params = new URLSearchParams({ role });
  if (testAuthSecret) {
    params.set("secret", testAuthSecret);
  }
  return `/api/auth/test-login?${params.toString()}`;
}

export default function DevLoginPage() {
  if (!isDevLoginEnabled) {
    notFound();
  }

  return (
    <div className="mx-auto mt-16 w-full max-w-2xl rounded-2xl border border-gray-200 bg-white p-8 shadow-sm">
      <div className="mb-8">
        <p className="text-sm font-medium text-blue-600">Development Only</p>
        <h1 className="mt-2 text-2xl font-semibold text-gray-900">Quick Login</h1>
        <p className="mt-2 text-sm text-gray-600">
          Use a seeded local role to enter the app quickly while developing or validating internal flows.
        </p>
      </div>

      <div className="space-y-4">
        {roleLinks.map((item) => (
          <a
            key={item.role}
            href={buildLoginHref(item.role)}
            className="block rounded-xl border border-gray-200 px-5 py-4 transition-colors hover:border-blue-300 hover:bg-blue-50"
          >
            <div className="flex items-center justify-between gap-4">
              <div>
                <h2 className="text-sm font-semibold text-gray-900">{item.label}</h2>
                <p className="mt-1 text-sm text-gray-600">{item.description}</p>
              </div>
              <span className="rounded-full bg-gray-100 px-3 py-1 text-xs font-medium text-gray-700">
                {item.role}
              </span>
            </div>
          </a>
        ))}
      </div>

      {!testAuthSecret ? (
        <div className="mt-6 rounded-lg border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-800">
          `TEST_AUTH_SECRET` is not set. The page still works if the backend does not require it, but setting one is recommended.
        </div>
      ) : null}

      <div className="mt-8 flex items-center justify-between text-sm">
        <Link href="/login" className="text-gray-500 hover:text-gray-900">
          Back to standard login
        </Link>
        <span className="text-gray-400">Path: `/dev/login`</span>
      </div>
    </div>
  );
}
