'use client';

import React, { createContext, useContext, useState, useEffect } from 'react';
import { useAuth } from './auth-context';
import {
  getSubscriptionOverview,
  type SubscriptionOverviewResponse,
  type SubscriptionPlan,
  type PlanFeature,
} from '../api/subscriptions';

interface SubscriptionContextType {
  subscription: SubscriptionOverviewResponse | null;
  loading: boolean;
  plan: SubscriptionPlan | null;
  planFeatures: PlanFeature[];
  hasFeature: (feature: PlanFeature) => boolean;
  refresh: () => Promise<void>;
}

const SubscriptionContext = createContext<SubscriptionContextType | undefined>(undefined);

export function SubscriptionProvider({ children }: { children: React.ReactNode }) {
  const { user, isAuthenticated } = useAuth();
  const [subscription, setSubscription] = useState<SubscriptionOverviewResponse | null>(null);
  const [loading, setLoading] = useState(true);

  const fetchSubscription = async () => {
    if (!isAuthenticated) {
      setSubscription(null);
      setLoading(false);
      return;
    }
    try {
      const data = await getSubscriptionOverview();
      setSubscription(data);
    } catch (error) {
      console.error('Failed to fetch subscription:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchSubscription();
  }, [isAuthenticated, user?.organizationId]);

  const plan = subscription?.plan ?? null;
  const planFeatures = subscription?.planDetails?.planFeatures ?? [];

  const hasFeature = (feature: PlanFeature): boolean => {
    return planFeatures.includes(feature);
  };

  return (
    <SubscriptionContext.Provider
      value={{
        subscription,
        loading,
        plan,
        planFeatures,
        hasFeature,
        refresh: fetchSubscription,
      }}
    >
      {children}
    </SubscriptionContext.Provider>
  );
}

export function useSubscription() {
  const context = useContext(SubscriptionContext);
  if (context === undefined) {
    throw new Error('useSubscription must be used within a SubscriptionProvider');
  }
  return context;
}
