"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { Lock, User, PawPrint, Loader2, AlertCircle } from "lucide-react";

export default function AdminLoginPage() {
  const router = useRouter();
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");

  async function handleLogin(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setLoading(true);
    setError("");

    const fd = new FormData(e.currentTarget);
    const username = String(fd.get("username") ?? "").trim();
    const password = String(fd.get("password") ?? "").trim();

    try {
      const res = await fetch("/api/admin/auth", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ username, password }),
      });

      const json = (await res.json()) as { ok: boolean; error?: string };

      if (json.ok) {
        router.push("/admin");
        router.refresh();
      } else {
        setError(json.error ?? "Giriş başarısız.");
        setLoading(false);
      }
    } catch {
      setError("Bağlantı hatası. Tekrar deneyin.");
      setLoading(false);
    }
  }

  return (
    <div className="flex min-h-screen items-center justify-center bg-gradient-to-br from-sand via-cream to-brand-50 px-4">
      <div className="w-full max-w-md animate-pop-in rounded-[2.5rem] bg-white p-10 shadow-2xl ring-1 ring-sand-dark/60">
        <div className="text-center">
          <span className="mx-auto grid size-20 place-items-center rounded-3xl bg-gradient-to-br from-brand-400 to-brand-600 text-white shadow-xl shadow-brand-500/30">
            <PawPrint className="size-10" />
          </span>
          <h1 className="mt-5 font-display text-3xl font-extrabold text-ink">
            Pet<span className="text-brand-600">Marketim</span>
          </h1>
          <p className="mt-1.5 text-sm font-bold text-mocha">Yönetim Paneli Girişi</p>
        </div>

        <form onSubmit={handleLogin} className="mt-8 space-y-5">
          <div>
            <label
              htmlFor="username"
              className="mb-1.5 block text-xs font-extrabold uppercase tracking-wider text-mocha"
            >
              Kullanıcı Adı
            </label>
            <div className="relative">
              <User className="pointer-events-none absolute left-4 top-1/2 size-5 -translate-y-1/2 text-latte" />
              <input
                id="username"
                name="username"
                type="text"
                required
                autoFocus
                autoComplete="username"
                placeholder="admin"
                className="w-full rounded-2xl border-2 border-sand-dark bg-cream/50 py-3.5 pl-12 pr-4 text-sm font-bold text-ink outline-none transition-colors focus:border-brand-400 focus:bg-white"
              />
            </div>
          </div>

          <div>
            <label
              htmlFor="password"
              className="mb-1.5 block text-xs font-extrabold uppercase tracking-wider text-mocha"
            >
              Şifre
            </label>
            <div className="relative">
              <Lock className="pointer-events-none absolute left-4 top-1/2 size-5 -translate-y-1/2 text-latte" />
              <input
                id="password"
                name="password"
                type="password"
                required
                autoComplete="current-password"
                placeholder="••••••••••"
                className="w-full rounded-2xl border-2 border-sand-dark bg-cream/50 py-3.5 pl-12 pr-4 text-sm font-bold text-ink outline-none transition-colors focus:border-brand-400 focus:bg-white"
              />
            </div>
          </div>

          {error && (
            <div className="flex items-center gap-2 rounded-2xl bg-red-50 px-4 py-3 text-sm font-bold text-red-700 ring-1 ring-red-200">
              <AlertCircle className="size-5 shrink-0" />
              {error}
            </div>
          )}

          <button
            type="submit"
            disabled={loading}
            className="flex w-full items-center justify-center gap-2.5 rounded-full bg-gradient-to-r from-brand-500 to-brand-600 py-4 text-base font-extrabold text-white shadow-xl shadow-brand-500/30 transition-all hover:-translate-y-0.5 hover:shadow-brand-500/50 active:scale-95 disabled:cursor-not-allowed disabled:opacity-50"
          >
            {loading ? (
              <>
                <Loader2 className="size-5 animate-spin" />
                Giriş yapılıyor…
              </>
            ) : (
              <>
                <Lock className="size-5" />
                Giriş Yap
              </>
            )}
          </button>
        </form>
      </div>
    </div>
  );
}
