import { useState, useEffect } from 'react';
import { getSubscriptions, createSubscription, deleteSubscription, getUsers } from '../services/api';
import { Subscription, User } from '../types';

const useSubscriptions = (userId: number) => {
  const [subscriptions, setSubscriptions] = useState<Subscription[]>([]);
  const [users, setUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const [subscriptionsData, usersData] = await Promise.all([
          getSubscriptions(),
          getUsers(),
        ]);
        setSubscriptions(subscriptionsData.data);
        setUsers(usersData.data);
        setLoading(false);
      } catch (err: any) {
        setError(err.message);
        setLoading(false);
      }
    };
    fetchData();
  }, []);

  const addSubscription = async (subscription: Omit<Subscription, 'id' | 'active' | 'userId'>) => {
    const response = await createSubscription({ ...subscription, userId, active: true });
    setSubscriptions([...subscriptions, response.data]);
  };

  const cancelSubscription = async (id: number) => {
    await deleteSubscription(id);
    setSubscriptions(subscriptions.filter(s => s.id !== id));
  };

  const getUserSubscription = (): Subscription | undefined => {
    return subscriptions.find(s => s.userId === userId);
  };

  return { subscriptions, users, loading, error, addSubscription, cancelSubscription, getUserSubscription };
};

export default useSubscriptions;