import { useState, useEffect } from "react";

const NocodbUser = (userId) => {
  const [identifier, setIdentifier] = useState(null);
  const [registered, setRegistered] = useState(false);
  const [error, setError] = useState(null);
  const [loading, setLoading] = useState(true);
  const [userAccount, setUserAccount] = useState(null);

  useEffect(() => {
    const fetchUserData = async () => {
      try {
        // Placeholder for user data fetching logic
        const mockData = [
          {
            "User ID": "123",
            Email: "user@example.com",
          },
        ];

        const user = mockData.find((item) => item["User ID"] === userId);

        if (user) {
          if (user.Email) {
            setIdentifier(user.Email); // already registered
            setRegistered(true);
            setUserAccount(user);
          } else {
            setIdentifier(user["User ID"]); // ready for registration
            setRegistered(false);
          }
        } else {
          setIdentifier(null); // unauthorized user
          setRegistered(false);
        }
      } catch (err) {
        setError(err.message);
      } finally {
        setLoading(false);
      }
    };

    if (userId) {
      fetchUserData();
    } else {
      setLoading(false);
      setIdentifier(null);
    }
  }, [userId]);

  return { identifier, registered, userAccount, error, loading };
};

export default NocodbUser;
