"use client";

import { useEffect, useState } from "react";
import { nip19 } from "nostr-tools";
import { api } from "@/lib/api";
import { useAuth } from "@/hooks/useAuth";
import { useNostrProfile } from "@/hooks/useNostrProfile";
import { NostrAvatar } from "@/components/nostr/NostrAvatar";
import { formatDate } from "@/lib/utils";
import { Lock, Plus } from "lucide-react";

const ROLE_RANK: Record<string, number> = {
  superadmin: 4,
  admin: 3,
  moderator: 2,
  writer: 1,
  guest: 0,
};

const ROLE_OPTIONS: { value: string; label: string }[] = [
  { value: "admin", label: "Admin" },
  { value: "moderator", label: "Moderator" },
  { value: "writer", label: "Writer" },
  { value: "guest", label: "Guest (no role)" },
];

function normalizeRole(role: string | null | undefined): string {
  return role && ROLE_RANK[role] !== undefined ? role : "guest";
}

function hexToNpub(pubkey: string): string {
  if (!pubkey) return "";
  // Already an npub (some users are stored in npub form).
  if (pubkey.startsWith("npub1")) return pubkey;
  try {
    return nip19.npubEncode(pubkey);
  } catch {
    return "";
  }
}

function shortenNpub(npub: string): string {
  if (npub.length <= 26) return npub;
  return `${npub.slice(0, 14)}...${npub.slice(-10)}`;
}

interface UserRowProps {
  user: any;
  draft: string;
  onDraftChange: (pubkey: string, value: string) => void;
  savingPubkey: string | null;
  onSaveUsername: (pubkey: string, currentUsername: string | null | undefined) => void;
  onCancelUsername: (pubkey: string, stored: string | null | undefined) => void;
  hostname: string;
  copiedPubkey: string | null;
  onCopyNpub: (pubkey: string) => void;
  callerRank: number;
  isSuperAdmin: boolean;
  savingRole: string | null;
  onRoleChange: (pubkey: string, role: string) => void;
}

function UserRow({
  user,
  draft,
  onDraftChange,
  savingPubkey,
  onSaveUsername,
  onCancelUsername,
  hostname,
  copiedPubkey,
  onCopyNpub,
  callerRank,
  isSuperAdmin,
  savingRole,
  onRoleChange,
}: UserRowProps) {
  const { profile, loading: profileLoading } = useNostrProfile(user.pubkey);
  const stored = user.username ?? "";
  const usernameDirty = draft.trim().toLowerCase() !== stored.toLowerCase();
  const fullNpub = hexToNpub(user.pubkey);
  const nostrDisplay = profile?.name || profile?.displayName;

  return (
    <div className="bg-surface-container-low rounded-xl p-6 flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
      <div className="flex-1 min-w-0 flex gap-4 items-start">
        <NostrAvatar pubkey={user.pubkey} size={56} fallbackText={fullNpub} />
        <div className="flex-1 min-w-0 space-y-3">
          <div>
            <p className="text-on-surface font-semibold text-base truncate">
              {profileLoading ? (
                <span className="text-on-surface/40 font-normal">…</span>
              ) : nostrDisplay ? (
                nostrDisplay
              ) : (
                <span className="text-on-surface/50 font-normal">No Nostr name</span>
              )}
            </p>
            <button
              type="button"
              onClick={() => onCopyNpub(user.pubkey)}
              className="mt-1 text-left font-mono text-sm text-on-surface/80 hover:text-primary transition-colors cursor-pointer break-all w-full"
              title={fullNpub || "Copy npub"}
            >
              {copiedPubkey === user.pubkey
                ? "Copied!"
                : fullNpub
                  ? shortenNpub(fullNpub)
                  : `${user.pubkey?.slice(0, 12)}...${user.pubkey?.slice(-8)}`}
            </button>
          </div>
          <div>
            <p className="text-xs font-semibold text-on-surface/50 mb-1 uppercase tracking-wide">
              NIP-05 username
            </p>
            <p className="text-on-surface-variant text-xs mb-2">
              Reserved names from the site blocklist can be assigned here (users cannot claim them on the dashboard).
            </p>
            <div className="flex flex-wrap items-center gap-2">
              <input
                value={draft}
                onChange={(e) => onDraftChange(user.pubkey, e.target.value)}
                disabled={savingPubkey === user.pubkey}
                placeholder="local-part"
                className="bg-surface-container-highest text-on-surface rounded-lg px-3 py-2 text-sm font-mono min-w-[8rem] max-w-full flex-1 focus:outline-none focus:ring-1 focus:ring-primary/40 disabled:opacity-50"
              />
              <span className="text-on-surface/50 text-sm font-mono shrink-0">
                @{hostname || "…"}
              </span>
              <button
                type="button"
                onClick={() => onSaveUsername(user.pubkey, user.username)}
                disabled={savingPubkey === user.pubkey || !draft.trim() || !usernameDirty}
                className="px-3 py-2 rounded-lg bg-gradient-to-r from-primary to-primary-container text-on-primary font-semibold text-sm hover:opacity-90 transition-opacity disabled:opacity-50 whitespace-nowrap"
              >
                {savingPubkey === user.pubkey ? "Saving…" : "Save"}
              </button>
              <button
                type="button"
                onClick={() => onCancelUsername(user.pubkey, user.username)}
                disabled={savingPubkey === user.pubkey || !usernameDirty}
                className="px-3 py-2 rounded-lg bg-surface-container-highest text-on-surface/70 text-sm hover:text-on-surface transition-colors disabled:opacity-50 whitespace-nowrap"
              >
                Cancel
              </button>
            </div>
            {draft.trim() && (
              <p className="text-on-surface-variant text-xs font-mono mt-2">
                {draft.trim().toLowerCase()}@{hostname || "…"}
              </p>
            )}
          </div>
          <div className="flex items-center gap-3 flex-wrap">
            {user.isSuperAdmin ? (
              <span className="inline-flex items-center gap-1.5 rounded-full px-3 py-1 text-xs font-bold bg-primary-container/20 text-primary">
                <Lock size={12} />
                SuperAdmin
              </span>
            ) : (
              (() => {
                const targetRole = normalizeRole(user.role);
                const targetRank = ROLE_RANK[targetRole];
                const canModify = callerRank > targetRank;
                return (
                  <label className="flex items-center gap-2">
                    <span className="text-xs font-semibold text-on-surface/50 uppercase tracking-wide">
                      Role
                    </span>
                    <select
                      value={targetRole}
                      disabled={!canModify || savingRole === user.pubkey}
                      onChange={(e) => onRoleChange(user.pubkey, e.target.value)}
                      className="bg-surface-container-highest text-on-surface rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-primary/40 disabled:opacity-50"
                    >
                      {ROLE_OPTIONS.map((opt) => (
                        <option
                          key={opt.value}
                          value={opt.value}
                          disabled={!isSuperAdmin && ROLE_RANK[opt.value] >= callerRank}
                        >
                          {opt.label}
                        </option>
                      ))}
                    </select>
                  </label>
                );
              })()
            )}
            {user.createdAt && (
              <span className="text-on-surface/40 text-xs">
                Joined {formatDate(user.createdAt)}
              </span>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

export default function UsersPage() {
  const { user: currentUser, isSuperAdmin } = useAuth();
  const [users, setUsers] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const [savingRole, setSavingRole] = useState<string | null>(null);
  const [hostname, setHostname] = useState("");
  const [usernameDrafts, setUsernameDrafts] = useState<Record<string, string>>({});
  const [savingPubkey, setSavingPubkey] = useState<string | null>(null);
  const [copiedPubkey, setCopiedPubkey] = useState<string | null>(null);
  const [newUserPubkey, setNewUserPubkey] = useState("");
  const [addingUser, setAddingUser] = useState(false);
  const [addUserSuccess, setAddUserSuccess] = useState("");

  const loadUsers = async () => {
    try {
      const data = await api.getUsers();
      setUsers(data);
      setUsernameDrafts(
        Object.fromEntries(
          data.map((u: { pubkey: string; username?: string | null }) => [u.pubkey, u.username ?? ""])
        )
      );
    } catch (err: any) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

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

  useEffect(() => {
    setHostname(typeof window !== "undefined" ? window.location.hostname : "");
  }, []);

  const handleCopyNpub = async (pubkey: string) => {
    const full = hexToNpub(pubkey);
    if (!full) return;
    try {
      await navigator.clipboard.writeText(full);
      setCopiedPubkey(pubkey);
      window.setTimeout(() => setCopiedPubkey((p) => (p === pubkey ? null : p)), 2000);
    } catch {
      // ignore
    }
  };

  const callerRank = isSuperAdmin
    ? ROLE_RANK.superadmin
    : ROLE_RANK[normalizeRole(currentUser?.role)];

  const handleRoleChange = async (pubkey: string, role: string) => {
    setSavingRole(pubkey);
    setError("");
    try {
      await api.setUserRole(pubkey, role === "guest" ? null : role);
      await loadUsers();
    } catch (err: any) {
      setError(err.message);
    } finally {
      setSavingRole(null);
    }
  };

  const handleSaveUsername = async (pubkey: string, currentUsername: string | null | undefined) => {
    const trimmed = (usernameDrafts[pubkey] ?? "").trim().toLowerCase();
    if (!trimmed) return;
    setSavingPubkey(pubkey);
    setError("");
    try {
      await api.updateUserUsername(pubkey, trimmed);
      await loadUsers();
    } catch (err: any) {
      setError(err.message);
      setUsernameDrafts((prev) => ({ ...prev, [pubkey]: currentUsername ?? "" }));
    } finally {
      setSavingPubkey(null);
    }
  };

  const handleCancelUsername = (pubkey: string, stored: string | null | undefined) => {
    setUsernameDrafts((prev) => ({ ...prev, [pubkey]: stored ?? "" }));
  };

  const handleDraftChange = (pubkey: string, value: string) => {
    setUsernameDrafts((prev) => ({ ...prev, [pubkey]: value }));
  };

  const handleAddUser = async () => {
    const value = newUserPubkey.trim();
    if (!value) return;
    setAddingUser(true);
    setError("");
    setAddUserSuccess("");
    try {
      await api.createUser(value);
      setNewUserPubkey("");
      setAddUserSuccess("User added.");
      await loadUsers();
    } catch (err: any) {
      setError(err.message);
    } finally {
      setAddingUser(false);
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-[60vh]">
        <div className="text-on-surface/50">Loading users...</div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <h1 className="text-2xl font-bold text-on-surface">User Management</h1>

      {error && <p className="text-error text-sm">{error}</p>}

      <div className="bg-surface-container-low rounded-xl p-6">
        <h2 className="text-sm font-semibold text-on-surface/70 mb-3">Add User</h2>
        <p className="text-on-surface-variant text-xs mb-3">
          Pre-register a user by their npub or hex pubkey so you can assign a role before they log in.
        </p>
        <div className="flex flex-col sm:flex-row gap-3">
          <input
            placeholder="npub1... or hex pubkey"
            value={newUserPubkey}
            onChange={(e) => setNewUserPubkey(e.target.value)}
            onKeyDown={(e) => {
              if (e.key === "Enter") handleAddUser();
            }}
            disabled={addingUser}
            className="bg-surface-container-highest text-on-surface rounded-lg px-4 py-3 w-full font-mono text-sm focus:outline-none focus:ring-1 focus:ring-primary/40 flex-1 disabled:opacity-50"
          />
          <button
            onClick={handleAddUser}
            disabled={!newUserPubkey.trim() || addingUser}
            className="flex items-center justify-center gap-2 px-4 py-2 rounded-lg bg-gradient-to-r from-primary to-primary-container text-on-primary font-semibold text-sm hover:opacity-90 transition-opacity disabled:opacity-50 whitespace-nowrap"
          >
            <Plus size={16} />
            {addingUser ? "Adding…" : "Add User"}
          </button>
        </div>
        {addUserSuccess && (
          <p className="text-green-400 text-sm mt-3">{addUserSuccess}</p>
        )}
      </div>

      <div className="space-y-3">
        {users.length === 0 ? (
          <p className="text-on-surface/50 text-sm">No users found.</p>
        ) : (
          users.map((user) => (
            <UserRow
              key={user.pubkey || user.id}
              user={user}
              draft={usernameDrafts[user.pubkey] ?? ""}
              onDraftChange={handleDraftChange}
              savingPubkey={savingPubkey}
              onSaveUsername={handleSaveUsername}
              onCancelUsername={handleCancelUsername}
              hostname={hostname}
              copiedPubkey={copiedPubkey}
              onCopyNpub={handleCopyNpub}
              callerRank={callerRank}
              isSuperAdmin={isSuperAdmin}
              savingRole={savingRole}
              onRoleChange={handleRoleChange}
            />
          ))
        )}
      </div>
    </div>
  );
}
