"use client";

import { FormEvent, useState } from "react";
import Image from "next/image";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { TextInput } from "@/components/admin/form-fields";
import { apiFetch } from "@/lib/admin-api";

export default function AdminLoginPage() {
  const router = useRouter();
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);

  async function onSubmit(e: FormEvent) {
    e.preventDefault();
    setError("");
    setLoading(true);
    try {
      const user = await apiFetch<{ role: string }>("/api/auth/login", {
        method: "POST",
        json: { email, password },
      });
      const adminRoles = ["SUPER_ADMIN", "ADMIN", "EDITOR", "STAFF"];
      if (!adminRoles.includes(user.role)) {
        await apiFetch("/api/auth/logout", { method: "POST" }).catch(() => undefined);
        throw new Error("Akun ini tidak memiliki akses admin");
      }
      router.replace("/admin");
    } catch (err) {
      setError(err instanceof Error ? err.message : "Login failed");
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="grid-bg flex min-h-screen items-center justify-center px-4">
      <div className="w-full max-w-md rounded-3xl border border-border bg-surface/90 p-8 shadow-2xl backdrop-blur">
        <div className="mb-8 text-center">
          <div className="relative mx-auto h-16 w-[260px]">
            <Image
              src="/logo-305.png"
              alt="305 GAMING"
              fill
              className="object-contain"
              priority
              unoptimized
            />
          </div>
          <h1 className="mt-4 font-[family-name:var(--font-space)] text-xl font-semibold">
            Admin Login
          </h1>
          <p className="mt-1 text-sm text-muted">Sign in to manage the store</p>
        </div>

        <form onSubmit={onSubmit} className="space-y-4">
          <TextInput
            label="Email"
            name="email"
            type="email"
            autoComplete="username"
            required
            value={email}
            onChange={(e) => setEmail(e.target.value)}
          />
          <TextInput
            label="Password"
            name="password"
            type="password"
            autoComplete="current-password"
            required
            value={password}
            onChange={(e) => setPassword(e.target.value)}
          />
          {error ? (
            <p className="rounded-xl border border-danger/30 bg-danger/10 px-3 py-2 text-sm text-danger">
              {error}
            </p>
          ) : null}
          <Button type="submit" className="w-full" disabled={loading}>
            {loading ? "Signing in…" : "Sign in"}
          </Button>
        </form>
      </div>
    </div>
  );
}
