"use client";
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";

export default function SetupAdminForm({ siteName }: { siteName: string }) {
  const [checking, setChecking] = useState(true);
  const [locked, setLocked] = useState(false);
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [confirm, setConfirm] = useState("");
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);
  const [success, setSuccess] = useState(false);
  const router = useRouter();

  useEffect(() => {
    fetch("/api/setup-admin")
      .then((r) => r.json())
      .then((d) => {
        setLocked(d.setupComplete);
        setChecking(false);
      });
  }, []);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError("");
    if (password !== confirm) {
      setError("Passwords do not match.");
      return;
    }
    setLoading(true);
    const res = await fetch("/api/setup-admin", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ name, email, password }),
    });
    const data = await res.json();
    setLoading(false);
    if (!res.ok) {
      setError(data.error || "Something went wrong.");
      return;
    }
    setSuccess(true);
    setTimeout(() => router.push("/admin-login"), 2000);
  }

  const inputCls =
    "w-full bg-neutral-950 border border-neutral-800 rounded-lg px-3 py-2.5 text-sm outline-none focus:border-red-600";

  if (checking) {
    return <div className="max-w-md mx-auto py-20 text-center text-neutral-500">Checking setup status...</div>;
  }

  if (locked) {
    return (
      <div className="max-w-md mx-auto py-20 text-center">
        <div className="card p-6">
          <h1 className="text-xl font-bold mb-2">Setup already completed</h1>
          <p className="text-neutral-400 text-sm mb-5">
            An admin account already exists for {siteName}. This setup page only works once, for security.
          </p>
          <Link href="/admin-login" className="btn-primary inline-block px-6 py-2.5">
            Go to Admin Login →
          </Link>
        </div>
      </div>
    );
  }

  if (success) {
    return (
      <div className="max-w-md mx-auto py-20 text-center">
        <div className="card p-6">
          <h1 className="text-xl font-bold mb-2 text-green-500">✓ Admin account created</h1>
          <p className="text-neutral-400 text-sm">Redirecting you to the admin login...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="max-w-md mx-auto py-12">
      <div className="text-center mb-6">
        <span className="inline-flex items-center gap-2 text-xs font-bold tracking-widest bg-red-950/60 border border-red-800 text-red-400 rounded-full px-4 py-1.5 mb-4">
          ⚙️ FIRST-TIME SETUP
        </span>
        <h1 className="text-2xl font-bold">Create your admin account</h1>
        <p className="text-neutral-400 text-sm mt-2">
          This one-time setup creates the first admin for {siteName}. Once created, this page locks
          itself permanently — use the normal admin login afterward.
        </p>
      </div>

      <form onSubmit={handleSubmit} className="card p-6 space-y-4">
        <div>
          <label className="block text-xs font-semibold mb-1.5">Your name</label>
          <input required value={name} onChange={(e) => setName(e.target.value)} className={inputCls} />
        </div>
        <div>
          <label className="block text-xs font-semibold mb-1.5">Email address</label>
          <input type="email" required value={email} onChange={(e) => setEmail(e.target.value)} className={inputCls} />
        </div>
        <div>
          <label className="block text-xs font-semibold mb-1.5">Password (min. 8 characters)</label>
          <input type="password" required minLength={8} value={password} onChange={(e) => setPassword(e.target.value)} className={inputCls} />
        </div>
        <div>
          <label className="block text-xs font-semibold mb-1.5">Confirm password</label>
          <input type="password" required value={confirm} onChange={(e) => setConfirm(e.target.value)} className={inputCls} />
        </div>

        {error && <p className="text-red-500 text-sm">{error}</p>}

        <button type="submit" disabled={loading} className="btn-primary w-full py-2.5">
          {loading ? "Creating account..." : "Create Admin Account"}
        </button>
      </form>
    </div>
  );
}
