"use client";

import {
  useState,
  type FormEvent,
} from "react";

import Link from "next/link";
import {
  Eye,
  EyeOff,
  LockKeyhole,
  Mail,
  ShieldCheck,
} from "lucide-react";

type LoginResponse = {
  authenticated?: boolean;
  mustChangePassword?: boolean;
  error?: string;
};

export default function AdminLoginPage() {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [showPassword, setShowPassword] =
    useState(false);
  const [loading, setLoading] = useState(false);
  const [message, setMessage] = useState("");

  async function handleLogin(
    event: FormEvent<HTMLFormElement>,
  ) {
    event.preventDefault();

    if (loading) return;

    setLoading(true);
    setMessage("");

    try {
      const response = await fetch(
        "/api/auth/login",
        {
          method: "POST",
          credentials: "same-origin",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            email: email.trim(),
            password,
          }),
          cache: "no-store",
        },
      );

      const result: LoginResponse =
        await response.json();

      if (!response.ok || !result.authenticated) {
        if (response.status === 429) {
          setMessage(
            "Too many login attempts. Please wait and try again.",
          );
        } else if (
          response.status === 401 ||
          response.status === 403
        ) {
          setMessage(
            "Invalid credentials or account access is unavailable.",
          );
        } else {
          setMessage(
            "Login is temporarily unavailable. Please try again.",
          );
        }

        return;
      }

      setPassword("");

      if (result.mustChangePassword) {
        setMessage(
          "Login successful. Password change is required before accessing the dashboard.",
        );
        return;
      }

      setMessage(
        "Login successful. Admin dashboard is not available yet.",
      );
    } catch {
      setMessage(
        "Unable to connect. Please check your connection and try again.",
      );
    } finally {
      setLoading(false);
    }
  }

  return (
    <main
      className="min-h-[75vh] bg-[var(--soft)] px-5 py-16"
    >
      <div className="mx-auto max-w-md">
        <div className="mb-7 text-center">
          <div
            className="mx-auto mb-4 flex h-14 w-14 items-center justify-center rounded-2xl bg-[var(--navy)] text-white"
          >
            <ShieldCheck size={28} />
          </div>

          <p className="mb-2 text-xs font-bold uppercase tracking-[0.2em] text-[var(--blue)]">
            Teja Technology
          </p>

          <h1 className="text-3xl font-bold text-[var(--navy)]">
            Admin Login
          </h1>

          <p className="mt-3 text-sm text-[var(--muted)]">
            Sign in to your authorized administrator account.
          </p>
        </div>

        <form
          onSubmit={handleLogin}
          className="rounded-2xl border border-[var(--line)] bg-white p-7 shadow-[0_18px_55px_rgba(7,23,47,0.08)]"
        >
          <label
            htmlFor="admin-email"
            className="mb-2 block text-sm font-semibold text-[var(--ink)]"
          >
            Email address
          </label>

          <div className="mb-5 flex items-center gap-3 rounded-xl border border-[var(--line)] px-4 focus-within:border-[var(--blue)]">
            <Mail
              size={18}
              className="shrink-0 text-[var(--muted)]"
            />

            <input
              id="admin-email"
              type="email"
              name="email"
              autoComplete="username"
              required
              maxLength={254}
              value={email}
              onChange={(event) =>
                setEmail(event.target.value)
              }
              disabled={loading}
              placeholder="admin@example.com"
              className="min-h-12 w-full min-w-0 bg-transparent text-sm outline-none"
            />
          </div>

          <label
            htmlFor="admin-password"
            className="mb-2 block text-sm font-semibold text-[var(--ink)]"
          >
            Password
          </label>

          <div className="mb-5 flex items-center gap-3 rounded-xl border border-[var(--line)] px-4 focus-within:border-[var(--blue)]">
            <LockKeyhole
              size={18}
              className="shrink-0 text-[var(--muted)]"
            />

            <input
              id="admin-password"
              type={showPassword ? "text" : "password"}
              name="password"
              autoComplete="current-password"
              required
              value={password}
              onChange={(event) =>
                setPassword(event.target.value)
              }
              disabled={loading}
              placeholder="Enter your password"
              className="min-h-12 w-full min-w-0 bg-transparent text-sm outline-none"
            />

            <button
              type="button"
              onClick={() =>
                setShowPassword((value) => !value)
              }
              disabled={loading}
              aria-label={
                showPassword
                  ? "Hide password"
                  : "Show password"
              }
              className="shrink-0 text-[var(--muted)] hover:text-[var(--blue)]"
            >
              {showPassword ? (
                <EyeOff size={18} />
              ) : (
                <Eye size={18} />
              )}
            </button>
          </div>

          {message && (
            <p
              role="status"
              aria-live="polite"
              className="mb-5 rounded-lg bg-[var(--soft)] px-4 py-3 text-sm text-[var(--ink)]"
            >
              {message}
            </p>
          )}

          <button
            type="submit"
            disabled={loading}
            className="button w-full disabled:cursor-not-allowed disabled:opacity-60"
          >
            {loading ? "Signing in..." : "Sign in"}
          </button>

          <p className="mt-5 text-center text-xs text-[var(--muted)]">
            Authorized administrators only.
          </p>
        </form>

        <p className="mt-6 text-center text-sm">
          <Link
            href="/"
            className="font-semibold text-[var(--blue)] hover:underline"
          >
            Return to website
          </Link>
        </p>
      </div>
    </main>
  );
}
