import { useState, useEffect, useCallback } from "react";
import { adminApi } from "../api";
import type { AdminUser } from "../types";
import type { UserInfo } from "../types";
import "./AdminPanel.css";
import { FaTrash } from "react-icons/fa6";

interface Props {
  currentUser: UserInfo;
  onClose: () => void;
  /** "modal" (default) renders with a full-screen backdrop overlay.
   *  "page" renders inline for use as a standalone page. */
  mode?: "modal" | "page";
}

export default function AdminPanel({
  currentUser,
  onClose,
  mode = "modal",
}: Props) {
  const [users, setUsers] = useState<AdminUser[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [busy, setBusy] = useState<string | null>(null); // user id being acted on

  const load = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const list = await adminApi.listUsers();
      setUsers(list);
    } catch (err) {
      const msg = err instanceof Error ? err.message : String(err);
      setError(msg.replace(/^\d+:\s*/, "").trim() || "Failed to load users");
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    load();
  }, [load]);

  async function handleBanToggle(user: AdminUser) {
    setBusy(user.id);
    try {
      if (user.status === "banned") {
        await adminApi.unbanUser(user.id);
      } else {
        await adminApi.banUser(user.id);
      }
      setUsers((prev) =>
        prev.map((u) =>
          u.id === user.id
            ? { ...u, status: u.status === "banned" ? "active" : "banned" }
            : u,
        ),
      );
    } catch (err) {
      const msg = err instanceof Error ? err.message : String(err);
      alert(msg.replace(/^\d+:\s*/, "").trim() || "Action failed");
    } finally {
      setBusy(null);
    }
  }

  async function handleRoleToggle(user: AdminUser) {
    const newRole = user.role === "admin" ? "user" : "admin";
    setBusy(user.id);
    try {
      await adminApi.setUserRole(user.id, newRole);
      setUsers((prev) =>
        prev.map((u) => (u.id === user.id ? { ...u, role: newRole } : u)),
      );
    } catch (err) {
      const msg = err instanceof Error ? err.message : String(err);
      alert(msg.replace(/^\d+:\s*/, "").trim() || "Action failed");
    } finally {
      setBusy(null);
    }
  }

  async function handleDelete(user: AdminUser) {
    if (
      !window.confirm(
        `Permanently delete user "${user.username}"? This cannot be undone.`,
      )
    )
      return;
    setBusy(user.id);
    try {
      await adminApi.deleteUser(user.id);
      setUsers((prev) => prev.filter((u) => u.id !== user.id));
    } catch (err) {
      const msg = err instanceof Error ? err.message : String(err);
      alert(msg.replace(/^\d+:\s*/, "").trim() || "Failed to delete user");
    } finally {
      setBusy(null);
    }
  }

  function formatDate(iso: string) {
    return new Date(iso).toLocaleDateString(undefined, {
      year: "numeric",
      month: "short",
      day: "numeric",
    });
  }

  const panelContent = (
    <div
      className={`admin-panel${mode === "page" ? " admin-panel-page" : ""}`}
      onClick={(e) => e.stopPropagation()}
    >
      {/* Header */}
      <div className="admin-header">
        <h2>Site Admin — Users</h2>
        {mode != "page" && (
          <button className="admin-close" onClick={onClose} aria-label="Close">
            ✕
          </button>
        )}
      </div>

      {/* Body */}
      <div className="admin-body">
        {loading ? (
          <p className="admin-loading">Loading…</p>
        ) : error ? (
          <p className="admin-error">{error}</p>
        ) : (
          <table className="admin-table">
            <thead>
              <tr>
                <th>Username</th>
                <th>Email</th>
                <th>Role</th>
                <th>Status</th>
                <th>Joined</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody>
              {users.map((user) => {
                const isSelf = user.id === currentUser.id;
                const isBusy = busy === user.id;

                return (
                  <tr
                    key={user.id}
                    className={`admin-row${isSelf ? " admin-row-self" : ""}${user.status === "banned" ? " admin-row-banned" : ""}`}
                  >
                    <td className="admin-username">
                      {user.username}
                      {isSelf && (
                        <span className="admin-self-badge"> (you)</span>
                      )}
                    </td>
                    <td className="admin-email">
                      {user.email ?? <span className="admin-none">—</span>}
                    </td>
                    <td>
                      <span className={`admin-role-badge role-${user.role}`}>
                        {user.role}
                      </span>
                    </td>
                    <td>
                      <span
                        className={`admin-status-badge status-${user.status}`}
                      >
                        {user.status}
                      </span>
                    </td>
                    <td className="admin-date">
                      {formatDate(user.created_at)}
                    </td>
                    <td className="admin-actions">
                      {/* Role toggle */}
                      <button
                        className={`admin-btn admin-btn-role${user.role === "admin" ? " is-admin" : ""}`}
                        onClick={() => handleRoleToggle(user)}
                        disabled={isSelf || isBusy}
                        title={
                          isSelf
                            ? "Cannot change your own role"
                            : user.role === "admin"
                              ? "Demote to user"
                              : "Promote to admin"
                        }
                      >
                        {user.role === "admin" ? "Demote" : "Make Admin"}
                      </button>

                      {/* Ban / Unban toggle */}
                      <button
                        className={`admin-btn admin-btn-ban${user.status === "banned" ? " is-banned" : ""}`}
                        onClick={() => handleBanToggle(user)}
                        disabled={isSelf || isBusy}
                        title={
                          isSelf
                            ? "Cannot ban yourself"
                            : user.status === "banned"
                              ? "Unban user"
                              : "Ban user"
                        }
                      >
                        {user.status === "banned" ? "Unban" : "Ban"}
                      </button>

                      {/* Delete */}
                      <button
                        className="admin-btn admin-btn-delete"
                        onClick={() => handleDelete(user)}
                        disabled={isSelf || isBusy}
                        title={
                          isSelf
                            ? "Cannot delete yourself"
                            : "Delete user permanently"
                        }
                      >
                        <FaTrash />
                      </button>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );

  if (mode === "page") {
    return panelContent;
  }

  return (
    <div className="admin-backdrop" onClick={onClose}>
      {panelContent}
    </div>
  );
}
