"use client";

import { useState } from "react";

export function AdminAddUser() {
  const [open, setOpen] = useState(false);
  const [error, setError] = useState("");
  const [pending, setPending] = useState(false);

  async function onSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setError("");
    setPending(true);
    const form = e.currentTarget;
    const data = new FormData(form);
    const res = await fetch("/api/admin/users", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        name: data.get("name"),
        email: data.get("email"),
        phone: data.get("phone"),
        password: data.get("password"),
        role: data.get("role"),
        grantAccess: data.get("grantAccess") === "on",
        unlockAll: data.get("unlockAll") === "on",
      }),
    });
    const json = await res.json();
    setPending(false);
    if (!res.ok) {
      setError(json.error || "Could not add user");
      return;
    }
    window.location.href = `/admin/users/${json.user.id}`;
  }

  return (
    <div className="mt-6">
      {!open ? (
        <button
          type="button"
          onClick={() => setOpen(true)}
          className="rounded-full bg-gold px-5 py-2.5 text-sm font-bold text-forest"
        >
          Add user
        </button>
      ) : (
        <form onSubmit={onSubmit} className="rounded-3xl border border-forest/10 bg-cream p-6">
          <div className="flex items-center justify-between">
            <h2 className="font-display text-2xl text-forest">Add user</h2>
            <button type="button" onClick={() => setOpen(false)} className="text-sm text-forest/60">
              Cancel
            </button>
          </div>
          <div className="mt-4 grid gap-4 sm:grid-cols-2">
            <label className="block text-sm">
              Full name
              <input
                required
                name="name"
                className="mt-1 w-full rounded-xl border border-forest/15 bg-white px-3 py-2.5"
              />
            </label>
            <label className="block text-sm">
              Email
              <input
                required
                type="email"
                name="email"
                className="mt-1 w-full rounded-xl border border-forest/15 bg-white px-3 py-2.5"
              />
            </label>
            <label className="block text-sm">
              Phone
              <input name="phone" placeholder="024…" className="mt-1 w-full rounded-xl border border-forest/15 bg-white px-3 py-2.5" />
            </label>
            <label className="block text-sm">
              Password
              <input
                required
                type="password"
                name="password"
                minLength={8}
                className="mt-1 w-full rounded-xl border border-forest/15 bg-white px-3 py-2.5"
              />
            </label>
            <label className="block text-sm">
              Role
              <select name="role" defaultValue="user" className="mt-1 w-full rounded-xl border border-forest/15 bg-white px-3 py-2.5">
                <option value="user">Learner</option>
                <option value="admin">Admin</option>
              </select>
            </label>
            <div className="flex flex-col justify-end gap-2 text-sm">
              <label className="flex items-center gap-2">
                <input type="checkbox" name="grantAccess" defaultChecked />
                Open classroom for 3 days (skip ₵50)
              </label>
              <label className="flex items-center gap-2">
                <input type="checkbox" name="unlockAll" />
                Unlock all courses
              </label>
            </div>
          </div>
          {error ? <p className="mt-3 text-sm text-terra">{error}</p> : null}
          <button
            disabled={pending}
            className="mt-5 rounded-full bg-forest px-5 py-2.5 text-sm font-semibold text-gold-2 disabled:opacity-60"
          >
            {pending ? "Adding…" : "Save user"}
          </button>
        </form>
      )}
    </div>
  );
}
