"use client";
import { useEffect, useState } from "react";

type User = { id: string; name: string; email: string; role: string; tier: string; points: number; permissions: string | null };

// Kept in sync with ALL_SECTIONS in app/admin/layout.tsx.
const SECTIONS = [
  { key: "dashboard", label: "Dashboard" },
  { key: "videos", label: "Videos" },
  { key: "categories", label: "Categories" },
  { key: "plans", label: "Membership Plans" },
  { key: "products", label: "Shop Products" },
  { key: "posts", label: "Community Posts" },
  { key: "deleted-posts", label: "Deleted Posts" },
  { key: "missions", label: "Missions & Targets" },
  { key: "points", label: "Points System" },
  { key: "users", label: "Users & Roles" },
  { key: "funding", label: "Funding Dashboard" },
  { key: "reports", label: "Strong Reports" },
  { key: "recurring", label: "Recurring Revenue" },
  { key: "accounting", label: "Accounting" },
  { key: "supporters", label: "Supporters" },
  { key: "test-billing", label: "Test Recurring Billing" },
  { key: "emails", label: "Email Templates" },
  { key: "email-campaign", label: "Email Campaign" },
  { key: "welcome-animation", label: "Welcome Animation" },
  { key: "analytics", label: "Visitor Analytics" },
  { key: "settings", label: "Site Settings" },
];

export default function AdminUsersPage() {
  const [users, setUsers] = useState<User[]>([]);
  const [saving, setSaving] = useState<string | null>(null);
  const [expanded, setExpanded] = useState<string | null>(null);

  const [showCreate, setShowCreate] = useState(false);
  const [newStaff, setNewStaff] = useState({ name: "", email: "", password: "" });
  const [newPerms, setNewPerms] = useState<string[]>([]);
  const [creating, setCreating] = useState(false);
  const [createError, setCreateError] = useState("");

  async function load() {
    const res = await fetch("/api/admin/users");
    setUsers(await res.json());
  }
  useEffect(() => { load(); }, []);

  function update(id: string, key: string, value: any) {
    setUsers((us) => us.map((u) => (u.id === id ? { ...u, [key]: value } : u)));
  }

  function togglePermission(u: User, key: string) {
    const current: string[] = u.permissions ? JSON.parse(u.permissions) : [];
    const next = current.includes(key) ? current.filter((k) => k !== key) : [...current, key];
    update(u.id, "permissions", JSON.stringify(next));
  }

  function hasFullAccess(u: User) {
    return !u.permissions;
  }

  async function save(u: User) {
    setSaving(u.id);
    await fetch(`/api/admin/users/${u.id}`, {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        tier: u.tier,
        role: u.role,
        permissions: u.permissions ? JSON.parse(u.permissions) : null,
      }),
    });
    setSaving(null);
  }

  async function deleteUser(id: string, name: string) {
    if (!confirm(`Permanently delete ${name}'s account? This cannot be undone.`)) return;
    const res = await fetch(`/api/admin/users/${id}`, { method: "DELETE" });
    const data = await res.json();
    if (!res.ok) {
      alert(data.error || "Failed to delete user.");
      return;
    }
    load();
  }

  function toggleNewPerm(key: string) {
    setNewPerms((prev) => (prev.includes(key) ? prev.filter((k) => k !== key) : [...prev, key]));
  }

  async function createStaff() {
    setCreateError("");
    setCreating(true);
    const res = await fetch("/api/admin/create-staff", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ ...newStaff, permissions: newPerms }),
    });
    const data = await res.json();
    setCreating(false);
    if (!res.ok) {
      setCreateError(data.error);
      return;
    }
    setShowCreate(false);
    setNewStaff({ name: "", email: "", password: "" });
    setNewPerms([]);
    load();
  }

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

  return (
    <div>
      <div className="flex items-center justify-between mb-1">
        <h2 className="text-lg font-semibold">Users & Roles ({users.length})</h2>
        <button onClick={() => setShowCreate((s) => !s)} className="btn-primary px-4 py-2 text-sm">
          {showCreate ? "Cancel" : "+ Create Staff Account"}
        </button>
      </div>
      <p className="text-xs text-neutral-500 mb-4">
        Admins with no restrictions checked below have full access to everything, including deleting
        content. Check specific sections to limit a staff account — and check "Can Delete" separately if
        they should also be allowed to delete things (not just view/edit) within those sections.
      </p>

      {showCreate && (
        <div className="card p-4 mb-4 border-amber-800/50 bg-amber-950/10">
          <h3 className="font-semibold text-sm mb-3 text-amber-400">New Staff Account</h3>
          <div className="grid sm:grid-cols-3 gap-3 mb-3">
            <input placeholder="Name" value={newStaff.name} onChange={(e) => setNewStaff((s) => ({ ...s, name: e.target.value }))} className={inputCls} />
            <input placeholder="Email" value={newStaff.email} onChange={(e) => setNewStaff((s) => ({ ...s, email: e.target.value }))} className={inputCls} />
            <input placeholder="Password (6+ chars)" type="password" value={newStaff.password} onChange={(e) => setNewStaff((s) => ({ ...s, password: e.target.value }))} className={inputCls} />
          </div>
          <p className="text-xs text-neutral-500 mb-2">
            Permissions (leave all unchecked for full access):
          </p>
          <div className="grid grid-cols-2 sm:grid-cols-3 gap-2 mb-3">
            <label className="flex items-center gap-2 text-xs font-semibold text-red-400">
              <input type="checkbox" checked={newPerms.includes("delete")} onChange={() => toggleNewPerm("delete")} />
              Can Delete
            </label>
            {SECTIONS.map((s) => (
              <label key={s.key} className="flex items-center gap-2 text-xs">
                <input type="checkbox" checked={newPerms.includes(s.key)} onChange={() => toggleNewPerm(s.key)} />
                {s.label}
              </label>
            ))}
          </div>
          {createError && <p className="text-red-500 text-xs mb-2">{createError}</p>}
          <button onClick={createStaff} disabled={creating} className="btn-primary px-4 py-2 text-sm">
            {creating ? "Creating..." : "Create Staff Account"}
          </button>
        </div>
      )}

      <div className="card overflow-hidden">
        <table className="w-full text-sm">
          <thead className="bg-neutral-900 text-neutral-500 text-left">
            <tr>
              <th className="p-3">Name</th>
              <th className="p-3">Email</th>
              <th className="p-3">Role</th>
              <th className="p-3">Tier</th>
              <th className="p-3"></th>
            </tr>
          </thead>
          <tbody>
            {users.map((u) => (
              <>
                <tr key={u.id} className="border-t border-neutral-800">
                  <td className="p-3">{u.name}</td>
                  <td className="p-3 text-neutral-400">{u.email}</td>
                  <td className="p-3">
                    <select value={u.role} onChange={(e) => update(u.id, "role", e.target.value)}
                      className="bg-neutral-900 border border-neutral-800 rounded px-2 py-1 text-xs">
                      <option value="member">Member</option>
                      <option value="admin">Admin</option>
                    </select>
                  </td>
                  <td className="p-3">
                    <select value={u.tier} onChange={(e) => update(u.id, "tier", e.target.value)}
                      className="bg-neutral-900 border border-neutral-800 rounded px-2 py-1 text-xs">
                      <option value="free">Free</option>
                      <option value="starter">Starter</option>
                      <option value="plus">Plus</option>
                      <option value="premium">Premium</option>
                    </select>
                  </td>
                  <td className="p-3 space-x-3 whitespace-nowrap">
                    {u.role === "admin" && (
                      <button onClick={() => setExpanded(expanded === u.id ? null : u.id)} className="text-neutral-400 hover:text-white">
                        {expanded === u.id ? "Hide permissions" : "Permissions"}
                      </button>
                    )}
                    <button onClick={() => save(u)} disabled={saving === u.id} className="text-red-500">
                      {saving === u.id ? "Saving..." : "Save"}
                    </button>
                    <button onClick={() => deleteUser(u.id, u.name)} className="text-neutral-500 hover:text-red-500">
                      Delete
                    </button>
                  </td>
                </tr>
                {expanded === u.id && u.role === "admin" && (
                  <tr className="border-t border-neutral-800 bg-neutral-950">
                    <td colSpan={5} className="p-4">
                      <p className="text-xs text-neutral-500 mb-2">
                        {hasFullAccess(u)
                          ? "Currently: full access (no restrictions), including delete. Check any box to switch to limited access."
                          : "Currently: limited access to checked sections only."}
                      </p>
                      <div className="grid grid-cols-2 sm:grid-cols-3 gap-2">
                        {(() => {
                          const perms: string[] = u.permissions ? JSON.parse(u.permissions) : [];
                          return (
                            <>
                              <label className="flex items-center gap-2 text-xs font-semibold text-red-400">
                                <input type="checkbox" checked={perms.includes("delete")} onChange={() => togglePermission(u, "delete")} />
                                Can Delete
                              </label>
                              {SECTIONS.map((s) => (
                                <label key={s.key} className="flex items-center gap-2 text-xs">
                                  <input type="checkbox" checked={perms.includes(s.key)} onChange={() => togglePermission(u, s.key)} />
                                  {s.label}
                                </label>
                              ))}
                            </>
                          );
                        })()}
                      </div>
                      {!hasFullAccess(u) && (
                        <button
                          onClick={() => update(u.id, "permissions", null)}
                          className="text-xs text-red-500 mt-3"
                        >
                          Clear restrictions (grant full access)
                        </button>
                      )}
                    </td>
                  </tr>
                )}
              </>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}
