import { useState, useEffect } from 'react';
import { loadStripe, Stripe } from '@stripe/stripe-js';
import { paymentService, StripeCredentials } from '@/services/paymentService';

export const useStripe = () => {
  const [stripe, setStripe] = useState<Stripe | null>(null);
  const [credentials, setCredentials] = useState<StripeCredentials | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const initStripe = async () => {
      try {
        const creds = await paymentService.getStripeCredentials();
        
        if (!creds || !creds.enabled) {
          setError('Stripe is not configured or enabled');
          setLoading(false);
          return;
        }

        setCredentials(creds);
        
        const stripeInstance = await loadStripe(creds.publishableKey);
        setStripe(stripeInstance);
        setLoading(false);
      } catch (err) {
        setError(err instanceof Error ? err.message : 'Failed to initialize Stripe');
        setLoading(false);
      }
    };

    initStripe();
  }, []);

  return { stripe, credentials, loading, error };
};
