// components/users.jsx — UsersPanel: git-based user management.
// Depends on: React (useState, useCallback, useEffect), Card, StatusBadge, get, post from api.js

const USER_ROLE_COLORS = {
  admin: "bg-purple-100 text-purple-700",
  developer: "bg-blue-100 text-blue-700",
  viewer: "bg-gray-100 text-gray-600",
};

// ── Hook: useUsers ──────────────────────────────────────────

function useUsers() {
  const [users, setUsers] = useState([]);
  const [defaultUser, setDefaultUserState] = useState(null);
  const [loading, setLoading] = useState(true);
  const [syncing, setSyncing] = useState(false);

  const refreshUsers = useCallback(async () => {
    try {
      const data = await get("/dashboard/users");
      setUsers(data?.users || []);
      setDefaultUserState(data?.default_user || null);
    } catch (e) {
      console.error("Failed to load users:", e);
    } finally {
      setLoading(false);
    }
  }, []);

  const syncGitUsers = useCallback(async () => {
    setSyncing(true);
    try {
      const data = await get("/dashboard/users/sync-git");
      await refreshUsers();
      return data;
    } catch (e) {
      console.error("Git sync failed:", e);
      throw e;
    } finally {
      setSyncing(false);
    }
  }, [refreshUsers]);

  const createUser = useCallback(async (userData) => {
    try {
      const data = await post("/dashboard/users", userData);
      await refreshUsers();
      return data;
    } catch (e) {
      console.error("Failed to create user:", e);
      throw e;
    }
  }, [refreshUsers]);

  const setDefaultUser = useCallback(async (userId) => {
    try {
      await post(`/dashboard/users/${userId}/set-default`, {});
      await refreshUsers();
    } catch (e) {
      console.error("Failed to set default user:", e);
      throw e;
    }
  }, [refreshUsers]);

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

  return {
    users,
    defaultUser,
    loading,
    syncing,
    refreshUsers,
    syncGitUsers,
    createUser,
    setDefaultUser,
  };
}

// ── UserCard ────────────────────────────────────────────────

function UserCard({ user, isDefault, onSetDefault }) {
  const roleClass = USER_ROLE_COLORS[user.role] || USER_ROLE_COLORS.viewer;

  return (
    <div className={`bg-white border rounded-lg p-4 hover:shadow-sm transition-shadow ${isDefault ? 'border-purple-300 bg-purple-50' : 'border-gray-200'}`}>
      <div className="flex items-start justify-between">
        <div className="flex items-center gap-3">
          <div className={`w-10 h-10 rounded-full flex items-center justify-center text-sm font-medium ${isDefault ? 'bg-purple-200 text-purple-700' : 'bg-gray-200 text-gray-600'}`}>
            {(user.name || user.username || "?").charAt(0).toUpperCase()}
          </div>
          <div>
            <div className="flex items-center gap-2">
              <span className="font-semibold text-gray-900">{user.name || user.username || "Unknown"}</span>
              {isDefault && (
                <span className="text-xs px-2 py-0.5 rounded-full bg-purple-100 text-purple-700 font-medium">
                  Default
                </span>
              )}
              {user.git_configured && (
                <span className="text-xs px-2 py-0.5 rounded-full bg-emerald-100 text-emerald-700" title="Auto-discovered from git">
                  git
                </span>
              )}
            </div>
            <div className="text-xs text-gray-500 mt-0.5">{user.email}</div>
          </div>
        </div>
        <div className="flex items-center gap-2">
          <span className={`text-xs px-2 py-0.5 rounded-full ${roleClass}`}>
            {user.role}
          </span>
          {!isDefault && user.is_active && (
            <button
              onClick={() => onSetDefault?.(user.id)}
              className="text-xs px-2 py-1 rounded bg-gray-100 text-gray-600 hover:bg-purple-100 hover:text-purple-700 transition-colors"
              title="Set as default user"
            >
              Set Default
            </button>
          )}
        </div>
      </div>

      <div className="mt-3 pt-3 border-t border-gray-100 grid grid-cols-3 gap-2 text-xs text-gray-500">
        <div>
          <span className="text-gray-400">Username:</span>
          <span className="ml-1 font-mono text-gray-700">{user.username || "—"}</span>
        </div>
        <div>
          <span className="text-gray-400">Projects:</span>
          <span className="ml-1 text-gray-700">{user.projects?.length || 0}</span>
        </div>
        <div>
          <span className="text-gray-400">Tickets:</span>
          <span className="ml-1 text-gray-700">{user.tickets_assigned || 0}</span>
        </div>
      </div>

      {user.last_seen_at > 0 && (
        <div className="mt-2 text-xs text-gray-400">
          Last seen: {new Date(user.last_seen_at * 1000).toLocaleString()}
        </div>
      )}
    </div>
  );
}

// ── CreateUserForm ───────────────────────────────────────────

function CreateUserForm({ onCreated, onCancel }) {
  const [form, setForm] = useState({
    name: "",
    email: "",
    username: "",
    role: "developer",
    is_default: false,
  });
  const [submitting, setSubmitting] = useState(false);

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!form.name.trim() || !form.email.trim()) return;

    setSubmitting(true);
    try {
      await onCreated?.(form);
      setForm({ name: "", email: "", username: "", role: "developer", is_default: false });
    } finally {
      setSubmitting(false);
    }
  };

  const field = (name, value) => setForm(prev => ({ ...prev, [name]: value }));

  return (
    <form onSubmit={handleSubmit} className="bg-white rounded-lg border border-blue-200 p-4 space-y-3">
      <h4 className="font-medium text-blue-900">New User</h4>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
        <input
          className="w-full px-3 py-2 border rounded text-sm"
          placeholder="Full name *"
          value={form.name}
          onChange={e => field("name", e.target.value)}
          required
        />
        <input
          className="w-full px-3 py-2 border rounded text-sm"
          placeholder="Email *"
          type="email"
          value={form.email}
          onChange={e => field("email", e.target.value)}
          required
        />
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
        <input
          className="w-full px-3 py-2 border rounded text-sm"
          placeholder="Username"
          value={form.username}
          onChange={e => field("username", e.target.value)}
        />
        <select
          className="w-full px-3 py-2 border rounded text-sm"
          value={form.role}
          onChange={e => field("role", e.target.value)}
        >
          <option value="admin">Admin</option>
          <option value="developer">Developer</option>
          <option value="viewer">Viewer</option>
        </select>
      </div>

      <div className="flex items-center gap-2">
        <input
          type="checkbox"
          id="is_default"
          checked={form.is_default}
          onChange={e => field("is_default", e.target.checked)}
          className="rounded border-gray-300"
        />
        <label htmlFor="is_default" className="text-sm text-gray-700">
          Set as default (delegated) user
        </label>
      </div>

      <div className="flex gap-2">
        <button
          type="submit"
          disabled={submitting}
          className="px-4 py-2 bg-blue-600 text-white text-sm rounded hover:bg-blue-700 disabled:opacity-50"
        >
          {submitting ? "Creating..." : "Create User"}
        </button>
        <button
          type="button"
          onClick={onCancel}
          className="px-4 py-2 bg-gray-100 text-gray-700 text-sm rounded hover:bg-gray-200"
        >
          Cancel
        </button>
      </div>
    </form>
  );
}

// ── UsersPanel (main) ────────────────────────────────────────

function UsersPanel() {
  const {
    users,
    defaultUser,
    loading,
    syncing,
    refreshUsers,
    syncGitUsers,
    createUser,
    setDefaultUser,
  } = useUsers();
  const [showCreate, setShowCreate] = useState(false);

  const handleSetDefault = async (userId) => {
    try {
      await setDefaultUser(userId);
    } catch (e) {
      alert("Failed to set default user: " + (e?.message || "Unknown error"));
    }
  };

  const handleCreate = async (formData) => {
    try {
      await createUser(formData);
      setShowCreate(false);
    } catch (e) {
      alert("Failed to create user: " + (e?.message || "Unknown error"));
    }
  };

  const handleSyncGit = async () => {
    try {
      const result = await syncGitUsers();
      alert(`Git sync complete! Discovered ${result?.discovered || 0} new users.`);
    } catch (e) {
      alert("Git sync failed: " + (e?.message || "Unknown error"));
    }
  };

  if (loading) {
    return (
      <Card title="Users">
        <p className="text-gray-500 text-sm">Loading users...</p>
      </Card>
    );
  }

  const activeUsers = users.filter(u => u.is_active);
  const defaultUserId = defaultUser?.id;

  return (
    <div className="space-y-6">
      {/* Stats */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-3">
        <div className="bg-white rounded-lg border p-3 text-center">
          <div className="text-2xl font-bold text-gray-900">{users.length}</div>
          <div className="text-xs text-gray-500">Total Users</div>
        </div>
        <div className="bg-white rounded-lg border p-3 text-center">
          <div className="text-2xl font-bold text-emerald-600">{activeUsers.length}</div>
          <div className="text-xs text-gray-500">Active</div>
        </div>
        <div className="bg-white rounded-lg border p-3 text-center">
          <div className="text-2xl font-bold text-purple-600">{users.filter(u => u.git_configured).length}</div>
          <div className="text-xs text-gray-500">From Git</div>
        </div>
        <div className="bg-white rounded-lg border p-3 text-center">
          <div className="text-2xl font-bold text-blue-600">{defaultUser ? 1 : 0}</div>
          <div className="text-xs text-gray-500">Default User</div>
        </div>
      </div>

      {/* Default User Info */}
      {defaultUser && (
        <div className="bg-purple-50 rounded-lg border border-purple-200 p-4">
          <div className="flex items-center gap-2 mb-2">
            <span className="text-purple-700 font-medium">Default (Delegated) User</span>
            <span className="text-xs px-2 py-0.5 rounded-full bg-purple-100 text-purple-700">
              Auto-assignment target
            </span>
          </div>
          <div className="text-sm text-gray-700">
            {defaultUser.name} ({defaultUser.email})
          </div>
          <div className="text-xs text-gray-500 mt-1">
            This user is automatically assigned to tickets that require human action.
          </div>
        </div>
      )}

      {/* Toolbar */}
      <div className="flex items-center justify-between flex-wrap gap-2">
        <div className="flex items-center gap-2">
          <button
            onClick={handleSyncGit}
            disabled={syncing}
            className="px-3 py-1.5 bg-emerald-600 text-white text-sm rounded hover:bg-emerald-700 disabled:opacity-50 flex items-center gap-1"
          >
            {syncing ? "↻ Syncing..." : "↻ Sync from Git"}
          </button>
          <button
            onClick={refreshUsers}
            className="px-3 py-1.5 bg-gray-100 text-gray-700 text-sm rounded hover:bg-gray-200"
          >
            ↻ Refresh
          </button>
        </div>
        <button
          onClick={() => setShowCreate(!showCreate)}
          className="px-3 py-1.5 bg-blue-600 text-white text-sm rounded hover:bg-blue-700"
        >
          {showCreate ? "Cancel" : "+ New User"}
        </button>
      </div>

      {/* Create Form */}
      {showCreate && (
        <CreateUserForm
          onCreated={handleCreate}
          onCancel={() => setShowCreate(false)}
        />
      )}

      {/* Users Grid */}
      <Card title={`Users (${activeUsers.length} active)`}>
        {activeUsers.length === 0 ? (
          <div className="text-center py-8">
            <p className="text-gray-500 text-sm mb-4">No users found.</p>
            <button
              onClick={handleSyncGit}
              disabled={syncing}
              className="px-4 py-2 bg-emerald-600 text-white text-sm rounded hover:bg-emerald-700 disabled:opacity-50"
            >
              {syncing ? "Syncing..." : "Sync from Git History"}
            </button>
          </div>
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {activeUsers.map(user => (
              <UserCard
                key={user.id}
                user={user}
                isDefault={user.id === defaultUserId}
                onSetDefault={handleSetDefault}
              />
            ))}
          </div>
        )}
      </Card>

      {/* Info Box */}
      <div className="bg-blue-50 rounded-lg border border-blue-200 p-4 text-sm">
        <div className="font-medium text-blue-900 mb-1">About Git-based Users</div>
        <p className="text-blue-800">
          Users are automatically discovered from git commit history (author name and email).
          The default user is automatically assigned to tickets that require human intervention
          (e.g., manual tool setup, configuration changes).
        </p>
      </div>
    </div>
  );
}
