import { useState, useEffect } from "react";

const NocodbUserRegister = (userId) => {
  const [user, setUser] = useState(null);
  const [error, setError] = useState(null);
  const [loading, setLoading] = useState(true);
  const [updateSuccess, setUpdateSuccess] = useState(false);

  useEffect(() => {
    const fetchUserData = async () => {
      try {
        // Placeholder for fetching user data
        const mockData = [
          {
            Id: "1",
            "User ID": "123",
            Name: "John Doe",
            Email: "john.doe@example.com",
            "Stripe Client ID": "cus_12345",
          },
        ];

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

        if (user) {
          setUser(user);
        } else {
          setError("User not found");
        }
      } catch (err) {
        setError(err.message);
      } finally {
        setLoading(false);
      }
    };

    if (userId) {
      fetchUserData();
    }
  }, [userId]);

  const updateUser = async (newName, newEmail, newStripeClientID) => {
    if (!user) {
      return { error: "No user data to update" };
    }

    setLoading(true);
    setUpdateSuccess(false);

    try {
      // Simulate updating user data
      const updatedUser = {
        ...user,
        Name: newName,
        Email: newEmail,
        "Stripe Client ID": newStripeClientID,
      };

      setUser(updatedUser);
      setUpdateSuccess(true);
      return { success: true };
    } catch (err) {
      setError(err.message);
      return { error: err.message };
    } finally {
      setLoading(false);
    }
  };

  return { user, updateUser, error, loading, updateSuccess };
};

export default NocodbUserRegister;
