"use client";

import { useEffect, useState } from "react";
import { useAuth } from "@/context/AuthContext"; // adjust path if needed
import { Loader2 } from "lucide-react";

import type { AdminUser, UserRole } from "@/types/user";

const API_BASE_URL =
  process.env.NEXT_PUBLIC_API_BASE_URL ?? "";

export default function AdminUsersPage() {
  const { getAuthHeaders } = useAuth();
  const [users, setUsers] = useState<AdminUser[]>([]);
  const [loading, setLoading] = useState(true);
  const [savingId, setSavingId] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);

  async function fetchUsers() {
    try {
      setLoading(true);
      setError(null);

      const res = await fetch(`${API_BASE_URL}/admin/users`, {
        headers: {
          ...getAuthHeaders(),
        },
      });

      if (!res.ok) {
        throw new Error(`Failed to load users (${res.status})`);
      }

      const data: AdminUser[] = await res.json();
      setUsers(data);
    } catch (err: any) {
      console.error(err);
      setError(err.message ?? "Failed to load users");
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    fetchUsers();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  async function handleRoleChange(userId: string, newRole: UserRole) {
    setSavingId(userId);
    setError(null);

    const prev = users;
    setUsers((cur) =>
      cur.map((u) => (u.id === userId ? { ...u, role: newRole } : u))
    );

    try {
      const res = await fetch(`${API_BASE_URL}/admin/users/${userId}/role`, {
        method: "PATCH",
        headers: {
          "Content-Type": "application/json",
          ...getAuthHeaders(),
        },
        body: JSON.stringify({ role: newRole }),
      });

      if (!res.ok) {
        throw new Error(`Failed to update role (${res.status})`);
      }
    } catch (err: any) {
      console.error(err);
      setError(err.message ?? "Failed to update role");
      // rollback
      setUsers(prev);
    } finally {
      setSavingId(null);
    }
  }

  function handleRoleSelectChange(user: AdminUser, newRole: UserRole) {
    if (newRole === user.role) {
      return;
    }

    // Confirm promotions to ADMIN
    if (
      newRole === "ADMIN" &&
      !window.confirm(
        `Promote ${user.email} to ADMIN? This will give them access to the admin console.`
      )
    ) {
      return;
    }

    // Confirm demotions from ADMIN
    if (
      user.role === "ADMIN" &&
      newRole === "USER" &&
      !window.confirm(
        `Remove ADMIN access from ${user.email}? They will lose access to the admin console.`
      )
    ) {
      return;
    }

    void handleRoleChange(user.id, newRole);
  }

  return (
    <div className="flex flex-1 flex-col gap-4">
      <div className="flex items-center justify-between gap-3">
        <div>
          <h1 className="text-base font-semibold text-zinc-100">
            Users & Roles
          </h1>
          <p className="mt-1 text-xs text-zinc-500">
            Promote trusted accounts to admins. All new signups start as{" "}
            <span className="font-medium text-zinc-300">USER</span>.
          </p>
        </div>
        <button
          type="button"
          onClick={fetchUsers}
          className="inline-flex items-center gap-1 rounded-md border border-zinc-800 bg-zinc-950 px-3 py-1.5 text-xs text-zinc-300 transition hover:border-amber-400/60 hover:text-amber-300"
          disabled={loading}
        >
          {loading && (
            <Loader2 className="h-3 w-3 animate-spin text-zinc-500" />
          )}
          <span>Refresh</span>
        </button>
      </div>

      {error && (
        <div className="rounded-md border border-red-900/60 bg-red-950/40 px-3 py-2 text-xs text-red-200">
          {error}
        </div>
      )}

      {loading ? (
        <div className="flex flex-1 items-center justify-center text-xs text-zinc-500">
          <Loader2 className="mr-2 h-4 w-4 animate-spin text-zinc-500" />
          Loading users…
        </div>
      ) : users.length === 0 ? (
        <div className="rounded-md border border-zinc-900 bg-zinc-950 px-4 py-6 text-sm text-zinc-400">
          No users found yet. Once people start signing up, they&apos;ll show up
          here.
        </div>
      ) : (
        <div className="overflow-hidden rounded-md border border-zinc-900 bg-zinc-950">
          <table className="min-w-full border-separate border-spacing-0 text-xs">
            <thead className="bg-zinc-950/80">
              <tr className="text-left text-[11px] uppercase tracking-[0.16em] text-zinc-500">
                <th className="border-b border-zinc-900 px-3 py-2">Email</th>
                <th className="border-b border-zinc-900 px-3 py-2">
                  Display Name
                </th>
                <th className="border-b border-zinc-900 px-3 py-2">Role</th>
                <th className="border-b border-zinc-900 px-3 py-2">Created</th>
                <th className="border-b border-zinc-900 px-3 py-2">
                  Last Login
                </th>
              </tr>
            </thead>
            <tbody>
              {users.map((u, idx) => (
                <tr
                  key={u.id}
                  className={idx % 2 === 0 ? "bg-zinc-950" : "bg-zinc-950/60"}
                >
                  <td className="border-b border-zinc-900 px-3 py-2 align-middle text-zinc-100">
                    {u.email}
                  </td>
                  <td className="border-b border-zinc-900 px-3 py-2 align-middle text-zinc-300">
                    {u.displayName || "—"}
                  </td>
                  <td className="border-b border-zinc-900 px-3 py-2 align-middle">
                    <div className="inline-flex items-center gap-2">
                      <span
                        className={`inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-medium ${
                          u.role === "ADMIN"
                            ? "border border-amber-500/60 bg-amber-500/10 text-amber-200"
                            : "border border-zinc-700 bg-zinc-900 text-zinc-300"
                        }`}
                      >
                        {u.role}
                      </span>
                      <select
                        value={u.role}
                        onChange={(e) =>
                          handleRoleSelectChange(u, e.target.value as UserRole)
                        }
                        disabled={savingId === u.id}
                        className="rounded-md border border-zinc-800 bg-zinc-950 px-2 py-1 text-[11px] text-zinc-200 outline-none transition hover:border-amber-400/60 focus:border-amber-400/80"
                      >
                        <option value="USER">USER</option>
                        <option value="ADMIN">ADMIN</option>
                      </select>
                    </div>
                  </td>
                  <td className="border-b border-zinc-900 px-3 py-2 align-middle text-zinc-400">
                    {u.createdAt
                      ? new Date(u.createdAt).toLocaleDateString()
                      : "—"}
                  </td>
                  <td className="border-b border-zinc-900 px-3 py-2 align-middle text-zinc-400">
                    {u.lastLoginAt
                      ? new Date(u.lastLoginAt).toLocaleDateString()
                      : "—"}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      <p className="mt-2 text-[10px] text-zinc-600">
        Note: Role changes take effect on the user&apos;s next request. All new
        accounts are created as <span className="text-zinc-300">USER</span> by
        default.
      </p>
    </div>
  );
}
