import { useState, useEffect, useCallback } from 'react';
import { loadStripe } from '@stripe/stripe-js';
import api from '../utils/api';

// Cache the stripe promise to avoid multiple loads
let stripePromiseCache = null;
let cachedPublishableKey = null;

/**
 * Hook to get Stripe configuration from the backend.
 *
 * Returns the Stripe publishable key and a pre-initialized Stripe promise.
 * The publishable key is fetched from the backend API, allowing admins
 * to configure it through the admin panel instead of environment variables.
 */
const useStripeConfig = () => {
  const [publishableKey, setPublishableKey] = useState(cachedPublishableKey);
  const [stripePromise, setStripePromise] = useState(stripePromiseCache);
  const [loading, setLoading] = useState(!cachedPublishableKey);
  const [error, setError] = useState(null);
  const [environment, setEnvironment] = useState(null);

  const fetchConfig = useCallback(async () => {
    // If we already have a cached key, use it
    if (cachedPublishableKey && stripePromiseCache) {
      setPublishableKey(cachedPublishableKey);
      setStripePromise(stripePromiseCache);
      setLoading(false);
      return;
    }

    try {
      setLoading(true);
      setError(null);

      const response = await api.get('/config/stripe');
      const { publishable_key, environment: env } = response.data;

      // Cache the key and stripe promise
      cachedPublishableKey = publishable_key;
      stripePromiseCache = loadStripe(publishable_key);

      setPublishableKey(publishable_key);
      setStripePromise(stripePromiseCache);
      setEnvironment(env);
    } catch (err) {
      console.error('[useStripeConfig] Failed to fetch Stripe config:', err);
      setError(err.response?.data?.detail || 'Failed to load Stripe configuration');

      // Fallback to environment variable if available
      const envKey = process.env.REACT_APP_STRIPE_PUBLISHABLE_KEY;
      if (envKey) {
        console.warn('[useStripeConfig] Falling back to environment variable');
        cachedPublishableKey = envKey;
        stripePromiseCache = loadStripe(envKey);
        setPublishableKey(envKey);
        setStripePromise(stripePromiseCache);
        setEnvironment(envKey.startsWith('pk_live_') ? 'live' : 'test');
        setError(null);
      }
    } finally {
      setLoading(false);
    }
  }, []);

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

  // Function to clear cache (useful after admin updates settings)
  const clearCache = useCallback(() => {
    cachedPublishableKey = null;
    stripePromiseCache = null;
    setPublishableKey(null);
    setStripePromise(null);
    fetchConfig();
  }, [fetchConfig]);

  return {
    publishableKey,
    stripePromise,
    loading,
    error,
    environment,
    refetch: fetchConfig,
    clearCache,
    isConfigured: !!publishableKey,
  };
};

export default useStripeConfig;
