"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";

export default function AdminLoginPage() {
  const router = useRouter();
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [submitting, setSubmitting] = useState(false);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setSubmitting(true);
    setError(null);
    const res = await fetch("/api/auth/login", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ email, password }),
    });
    if (!res.ok) {
      const data = await res.json().catch(() => ({}));
      setError(data.error ?? "Login failed");
      setSubmitting(false);
      return;
    }
    router.push("/admin/bookings");
    router.refresh();
  }

  return (
    <div className="flex min-h-screen items-center justify-center bg-blush px-6">
      <div className="w-full max-w-sm rounded-2xl bg-cream p-8 shadow-sm">
        <p className="text-center text-xs uppercase tracking-wide-plus text-rose-dark">
          Hair by Nyasia
        </p>
        <h1 className="mt-2 text-center font-display text-2xl text-rosewood">Admin Login</h1>
        <form onSubmit={handleSubmit} className="mt-8 space-y-4">
          <input
            required
            type="email"
            placeholder="Email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            className="w-full rounded-lg border border-blush-dark/60 px-4 py-2.5 text-sm"
          />
          <input
            required
            type="password"
            placeholder="Password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            className="w-full rounded-lg border border-blush-dark/60 px-4 py-2.5 text-sm"
          />
          {error && <p className="text-sm text-red-600">{error}</p>}
          <button
            type="submit"
            disabled={submitting}
            className="w-full rounded-full bg-rosewood px-6 py-3 text-xs uppercase tracking-wide-plus text-cream transition hover:bg-rose-dark disabled:opacity-50"
          >
            {submitting ? "Signing in…" : "Sign In"}
          </button>
        </form>
      </div>
    </div>
  );
}
