'use client';

import { createContext, useContext, useState, useEffect, type ReactNode } from 'react';

type StripeMode = 'test' | 'live' | 'dev' | null;

interface StripeConfigContextValue {
  mode: StripeMode;
  configured: boolean;
  isTest: boolean;
  isLive: boolean;
  priceIds: { pro: string | null; enterprise: string | null };
  webhookConfigured: boolean;
  billingServiceUrl: string;
  loading: boolean;
}

const StripeConfigContext = createContext<StripeConfigContextValue>({
  mode: null,
  configured: false,
  isTest: false,
  isLive: false,
  priceIds: { pro: null, enterprise: null },
  webhookConfigured: false,
  billingServiceUrl: 'http://localhost:4003',
  loading: true,
});

export function useStripeConfig() {
  return useContext(StripeConfigContext);
}

export function StripeConfigProvider({ children }: { children: ReactNode }) {
  const [state, setState] = useState<Omit<StripeConfigContextValue, 'isTest' | 'isLive'>>({
    mode: null,
    configured: false,
    priceIds: { pro: null, enterprise: null },
    webhookConfigured: false,
    billingServiceUrl: 'http://localhost:4003',
    loading: true,
  });

  useEffect(() => {
    fetch('/api/stripe/config')
      .then(res => res.json())
      .then(data => {
        setState({
          mode: data.mode,
          configured: data.configured,
          priceIds: data.priceIds || { pro: null, enterprise: null },
          webhookConfigured: data.webhookConfigured ?? false,
          billingServiceUrl: data.billingServiceUrl || 'http://localhost:4003',
          loading: false,
        });
      })
      .catch(() => {
        setState(prev => ({ ...prev, mode: 'dev', loading: false }));
      });
  }, []);

  return (
    <StripeConfigContext.Provider
      value={{
        ...state,
        isTest: state.mode === 'test' || state.mode === 'dev',
        isLive: state.mode === 'live',
      }}
    >
      {children}
    </StripeConfigContext.Provider>
  );
}
