import React, { useEffect, useCallback } from "react";
import { useState } from "react";
import { User, Flight, SubscriptionsCreate } from "../Types";
import { fetchSubscriptions } from "../Api";

export const useFetchSubscriptions  = (user: User | undefined, token: string | undefined) => {
    const [error, setError] = useState<string | null>(null);
    const [subscriptions, setSubscriptions] = useState<SubscriptionsCreate[]>([]);
    const [loading, setLoading] = useState<boolean>(true);

    const fetchData = useCallback(async () => {
        setError(null);

        if (!user || !token || !loading) {
            return;
        }

        fetchSubscriptions(user.id, token)
            .then((data) => {
                setSubscriptions(data);
                setLoading(false)
            })
            .catch((error) => { });
    }, [user, token]);

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

    return { subscriptions, error, loading, fetchData };
};
