import Link from "next/link";
import { prisma } from "@/lib/prisma";
import { formatDate } from "@/lib/format";
import { createAdminUser, toggleAdminUser, deleteAdminUser } from "@/lib/actions/settings";
import { getCurrentAdminUserId } from "@/lib/auth";
import { ADMIN_ROLES } from "@/lib/permissions";
import SettingsTabs from "@/components/admin/SettingsTabs";

const roleLabel = (value: string) => ADMIN_ROLES.find((r) => r.value === value)?.label ?? value;

export default async function AdminUsersPage({
  searchParams,
}: {
  searchParams: Promise<{ error?: string }>;
}) {
  const { error } = await searchParams;
  const [users, currentUserId] = await Promise.all([
    prisma.adminUser.findMany({ orderBy: { createdAt: "asc" } }),
    getCurrentAdminUserId(),
  ]);

  return (
    <div>
      <h1 className="font-[family-name:var(--font-heading)] text-2xl font-bold text-stone-800">Users &amp; Roles</h1>
      <p className="mt-1 text-sm text-stone-500">
        Real per-person logins alongside the existing shared store password — the store password still works exactly
        as before, this is additive. To log in as a specific user, enter their username on the login screen along with
        their password.
      </p>
      <p className="mt-1 max-w-2xl rounded-md bg-amber-50 p-3 text-xs text-amber-800">
        Roles are now enforced, not just labels: each section below is only visible/usable if the role has
        permission for it. Super Admin always has full access, including if someone logs in with the shared store
        password. See <Link href="/iv-manage-84x2/settings/roles" className="underline">Roles &amp; Permissions</Link> for
        the full matrix.
      </p>

      <SettingsTabs active="/iv-manage-84x2/settings/users" />

      {error && <p className="mb-4 text-sm text-red-700">{decodeURIComponent(error)}</p>}

      <form action={createAdminUser} className="grid max-w-2xl grid-cols-1 gap-3 rounded-lg border border-rose-100 bg-white p-4 sm:grid-cols-4">
        <input name="email" type="text" required placeholder="Username" className="rounded-md border border-stone-300 px-2 py-2 text-sm sm:col-span-2" />
        <input name="password" type="password" required minLength={8} placeholder="Password (8+ chars)" className="rounded-md border border-stone-300 px-2 py-2 text-sm" />
        <select name="role" className="rounded-md border border-stone-300 px-2 py-2 text-sm">
          {ADMIN_ROLES.filter((r) => r.value !== "super_admin").map((r) => (
            <option key={r.value} value={r.value}>
              {r.label}
            </option>
          ))}
        </select>
        <button type="submit" className="col-span-1 rounded-md bg-rose-700 px-4 py-2 text-sm font-semibold text-white hover:bg-rose-800 sm:col-span-4">
          Add user
        </button>
      </form>

      <div className="mt-8 overflow-hidden rounded-lg border border-rose-100 bg-white">
        {users.length === 0 ? (
          <p className="p-4 text-sm text-stone-500">No per-user accounts yet — everyone still logs in with the shared store password.</p>
        ) : (
          <table className="w-full text-sm">
            <thead className="bg-rose-50/60 text-left text-xs uppercase text-stone-500">
              <tr>
                <th className="p-3">Username</th>
                <th className="p-3">Role</th>
                <th className="p-3">Added</th>
                <th className="p-3">Status</th>
                <th className="p-3"></th>
              </tr>
            </thead>
            <tbody className="divide-y divide-rose-100">
              {users.map((u) => (
                <tr key={u.id}>
                  <td className="p-3 font-medium text-stone-800">
                    {u.email}
                    {u.id === currentUserId && <span className="ml-2 rounded-full bg-rose-100 px-2 py-0.5 text-[11px] text-rose-800">You</span>}
                  </td>
                  <td className="p-3 text-stone-600">{roleLabel(u.role)}</td>
                  <td className="p-3 text-stone-500">{formatDate(u.createdAt)}</td>
                  <td className="p-3">
                    <span className={`rounded-full px-2 py-0.5 text-xs font-medium ${u.active ? "bg-emerald-100 text-emerald-800" : "bg-stone-200 text-stone-600"}`}>
                      {u.active ? "Active" : "Inactive"}
                    </span>
                  </td>
                  <td className="p-3 text-right">
                    <div className="flex items-center justify-end gap-3">
                      <form action={toggleAdminUser.bind(null, u.id)}>
                        <button type="submit" className="text-xs text-stone-500 hover:text-rose-700">
                          {u.active ? "Deactivate" : "Activate"}
                        </button>
                      </form>
                      <form action={deleteAdminUser.bind(null, u.id)}>
                        <button type="submit" className="text-xs text-stone-400 hover:text-red-700">
                          Delete
                        </button>
                      </form>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
}
