import { useState, useEffect, useCallback } from 'react';
import { supabase } from '../../lib/supabase';

export function useAdminUsers() {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  const fetchUsers = useCallback(async (isMounted) => {
    const { data, error } = await supabase.functions.invoke('list-admin-users');

    if (!isMounted) return;

    if (error) {
      setError(error.message);
    } else {
      setUsers(data ?? []);
    }
    setLoading(false);
  }, []);

  useEffect(() => {
    let isMounted = true;
    fetchUsers(isMounted);
    return () => {
      isMounted = false;
    };
  }, [fetchUsers]);

  const inviteUser = async (email) => {
    const { data, error } = await supabase.functions.invoke('invite-admin-user', {
      body: { email },
    });

    if (error) {
      throw new Error(error.message);
    }

    setUsers((prev) => [...prev, data]);
    return data;
  };

  const deleteUser = async (userId) => {
    const { error } = await supabase.functions.invoke('delete-admin-user', {
      body: { userId },
    });

    if (error) {
      throw new Error(error.message);
    }

    setUsers((prev) => prev.filter((u) => u.id !== userId));
  };

  return { users, loading, error, inviteUser, deleteUser };
}
