import type { Metadata } from "next";
import Link from "next/link";
import Image from "next/image";
import { LogIn, UserPlus, CheckCircle2, AlertCircle } from "lucide-react";
import { Container } from "@/components/Container";
import { loadEnv } from "@/lib/env";
import { LoginForm } from "./LoginForm";

export const metadata: Metadata = {
  title: "Sign in",
  description: "Sign in to your OrthoGlobe member account.",
};

const ERROR_MESSAGES: Record<string, string> = {
  not_registered:
    "No OrthoGlobe account matches that Google email. Apply for membership first, then try signing in again.",
  pending_approval:
    "Your membership application is still under review. You'll receive an email once it's approved.",
  not_active:
    "This account isn't active. Contact the administrators if you believe this is a mistake.",
  no_email:
    "Google didn't share an email address with us, so we can't match you to an account.",
  OAuthAccountNotLinked:
    "That email is already registered with a password. Sign in with your password first — Google will link automatically after that.",
  OAuthSignin: "Google sign-in failed. Please try again.",
  OAuthCallback: "Google sign-in was interrupted. Please try again.",
  default: "Sign-in failed. Please try again.",
};

export default async function LoginPage({
  searchParams,
}: {
  searchParams: Promise<{ reset?: string; error?: string }>;
}) {
  const params = await searchParams;
  const resetSuccess = params.reset === "1";
  const devicesRevoked = params.reset === "devices";
  const errorKey = params.error ?? "";
  const errorMessage = errorKey
    ? (ERROR_MESSAGES[errorKey] ?? ERROR_MESSAGES.default)
    : "";
  const googleEnabled = loadEnv().googleAuthEnabled;
  return (
    <section className="bg-white pt-10 pb-16 md:pt-14 md:pb-24">
      <Container>
        <div className="mx-auto w-full max-w-md">
          <div className="flex flex-col items-center text-center">
            <Link href="/" aria-label="OrthoGlobe home" className="inline-flex">
              <Image
                src="/brand/orthoglobe-logo-512.webp"
                alt="OrthoGlobe"
                width={512}
                height={512}
                priority
                className="h-24 w-auto md:h-28"
              />
            </Link>
            <div className="mt-6 inline-flex items-center gap-2 rounded-full border border-[var(--color-line)] bg-[var(--color-mist)] px-3 py-1 text-[11px] font-bold uppercase tracking-wider text-[var(--color-blue)]">
              <LogIn className="h-3 w-3" aria-hidden="true" />
              Members
            </div>
            <h1 className="mt-4 font-display text-[32px] md:text-[40px] font-extrabold leading-[1.1] tracking-[-0.02em] text-[var(--color-ink)]">
              Sign in to OrthoGlobe
            </h1>
            <p className="mt-3 text-[15px] leading-relaxed text-[var(--color-slate)]">
              Welcome back. Enter your credentials to continue.
            </p>
          </div>

          {resetSuccess && (
            <div
              role="status"
              className="mt-6 flex items-start gap-2 rounded-md border border-emerald-200 bg-emerald-50 p-3 text-sm text-emerald-900"
            >
              <CheckCircle2 className="mt-0.5 h-4 w-4 shrink-0" aria-hidden />
              <span>Your password has been updated. Sign in with your new password.</span>
            </div>
          )}
          {devicesRevoked && (
            <div
              role="status"
              className="mt-6 flex items-start gap-2 rounded-md border border-emerald-200 bg-emerald-50 p-3 text-sm text-emerald-900"
            >
              <CheckCircle2 className="mt-0.5 h-4 w-4 shrink-0" aria-hidden />
              <span>All devices have been signed out. Sign in to continue.</span>
            </div>
          )}
          {errorMessage && (
            <div
              role="alert"
              className="mt-6 flex items-start gap-2 rounded-md border border-red-200 bg-red-50 p-3 text-sm text-red-800"
            >
              <AlertCircle className="mt-0.5 h-4 w-4 shrink-0" aria-hidden />
              <span>
                {errorMessage}
                {errorKey === "not_registered" && (
                  <>
                    {" "}
                    <Link href="/join" className="font-semibold underline">
                      Apply now.
                    </Link>
                  </>
                )}
              </span>
            </div>
          )}

          <div className="mt-8 rounded-2xl border border-[var(--color-line)] bg-white p-6 shadow-sm md:p-8">
            <LoginForm googleEnabled={googleEnabled} />
            <p className="mt-4 text-right text-[13px]">
              <Link
                href="/forgot-password"
                className="font-semibold text-[var(--color-blue)] hover:underline"
              >
                Forgot your password?
              </Link>
            </p>
          </div>

          <p className="mt-6 flex items-center justify-center gap-2 text-center text-sm text-[var(--color-slate)]">
            <UserPlus className="h-4 w-4 text-[var(--color-blue)]" aria-hidden="true" />
            No account yet?{" "}
            <Link
              href="/join"
              className="font-semibold text-[var(--color-blue)] hover:underline"
            >
              Apply for membership.
            </Link>
          </p>
        </div>
      </Container>
    </section>
  );
}
