import { useState, useEffect, useCallback } from 'react';
import { supabase } from '@/lib/supabase';
import { useTranslation } from 'react-i18next';
import type {
  SubscriptionPlan,
  SubscriptionPlanTranslation,
  SubscriptionPlanFeature,
  SubscriptionFeatureTranslation,
  AdditionalPackage,
  AdditionalPackageTranslation,
  PlanWithTranslation,
  FeatureWithTranslation,
  PackageWithTranslation
} from '@/types/subscription.types';

interface UsePlansReturn {
  plans: PlanWithTranslation[];
  isLoading: boolean;
  error: string | null;
  refetch: () => Promise<void>;
}

export function usePlans(): UsePlansReturn {
  const { i18n } = useTranslation();
  const [plans, setPlans] = useState<PlanWithTranslation[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const currentLanguage = i18n.language?.split('-')[0] || 'en';

  const fetchPlans = useCallback(async () => {
    try {
      setIsLoading(true);
      setError(null);

      // Fetch all active plans
      const { data: plansData, error: plansError } = await supabase
        .from('subscription_plans')
        .select('*')
        .eq('is_active', true)
        .order('sort_order');

      if (plansError) throw plansError;

      if (!plansData || plansData.length === 0) {
        setPlans([]);
        return;
      }

      // Fetch translations for all plans
      const planIds = plansData.map(p => p.id);
      const { data: translationsData } = await supabase
        .from('subscription_plan_translations')
        .select('*')
        .in('plan_id', planIds)
        .eq('language_code', currentLanguage);

      // Fetch features for all plans
      const { data: featuresData } = await supabase
        .from('subscription_plan_features')
        .select('*')
        .in('plan_id', planIds)
        .order('sort_order');

      // Fetch feature translations
      const featureIds = featuresData?.map(f => f.id) || [];
      const { data: featureTranslationsData } = await supabase
        .from('subscription_feature_translations')
        .select('*')
        .in('feature_id', featureIds)
        .eq('language_code', currentLanguage);

      // Combine data
      const combinedPlans: PlanWithTranslation[] = plansData.map(plan => {
        const translation = translationsData?.find(t => t.plan_id === plan.id);
        const features = featuresData?.filter(f => f.plan_id === plan.id) || [];
        const featuresWithTranslations: FeatureWithTranslation[] = features.map(feature => {
          const featureTranslation = featureTranslationsData?.find(
            ft => ft.feature_id === feature.id
          );
          return {
            ...feature,
            translations: featureTranslation || {
              id: '',
              feature_id: feature.id,
              language_code: currentLanguage,
              label: feature.feature_code,
              created_at: ''
            }
          };
        });

        return {
          ...plan,
          translations: translation || {
            id: '',
            plan_id: plan.id,
            language_code: currentLanguage,
            name: plan.plan_code,
            description: null,
            period_label: null,
            overage_label: null,
            badge_text: null,
            created_at: '',
            updated_at: ''
          },
          features: featuresWithTranslations
        };
      });

      setPlans(combinedPlans);
    } catch (err) {
      console.error('Error fetching plans:', err);
      setError(err instanceof Error ? err.message : 'Failed to fetch plans');
    } finally {
      setIsLoading(false);
    }
  }, [currentLanguage]);

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

  return {
    plans,
    isLoading,
    error,
    refetch: fetchPlans
  };
}

// Hook for fetching additional packages
interface UsePackagesReturn {
  packages: PackageWithTranslation[];
  isLoading: boolean;
  error: string | null;
  purchasePackage: (storeId: string, subscriptionId: string, packageId: string, pkg: AdditionalPackage, currency: string) => Promise<boolean>;
  refetch: () => Promise<void>;
}

export function usePackages(): UsePackagesReturn {
  const { i18n } = useTranslation();
  const [packages, setPackages] = useState<PackageWithTranslation[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const currentLanguage = i18n.language?.split('-')[0] || 'en';

  const fetchPackages = useCallback(async () => {
    try {
      setIsLoading(true);
      setError(null);

      // Fetch all active packages
      const { data: packagesData, error: packagesError } = await supabase
        .from('additional_packages')
        .select('*')
        .eq('is_active', true)
        .order('sort_order');

      if (packagesError) throw packagesError;

      if (!packagesData || packagesData.length === 0) {
        setPackages([]);
        return;
      }

      // Fetch translations
      const packageIds = packagesData.map(p => p.id);
      const { data: translationsData } = await supabase
        .from('additional_package_translations')
        .select('*')
        .in('package_id', packageIds)
        .eq('language_code', currentLanguage);

      // Combine data
      const combinedPackages: PackageWithTranslation[] = packagesData.map(pkg => {
        const translation = translationsData?.find(t => t.package_id === pkg.id);
        return {
          ...pkg,
          translations: translation || {
            id: '',
            package_id: pkg.id,
            language_code: currentLanguage,
            name: `${pkg.minutes} Minutes`,
            description: null,
            created_at: ''
          }
        };
      });

      setPackages(combinedPackages);
    } catch (err) {
      console.error('Error fetching packages:', err);
      setError(err instanceof Error ? err.message : 'Failed to fetch packages');
    } finally {
      setIsLoading(false);
    }
  }, [currentLanguage]);

  const purchasePackage = async (
    storeId: string,
    subscriptionId: string,
    packageId: string,
    pkg: AdditionalPackage,
    currency: string
  ): Promise<boolean> => {
    try {
      // Get subscription end date for package expiry
      const { data: subData } = await supabase
        .from('store_subscriptions')
        .select('period_end')
        .eq('id', subscriptionId)
        .single();

      const price = currency === 'EUR' ? pkg.price_eur :
                    currency === 'USD' ? pkg.price_usd :
                    pkg.price_huf;

      // Insert package purchase
      const { error: purchaseError } = await supabase
        .from('package_purchases')
        .insert({
          store_id: storeId,
          subscription_id: subscriptionId,
          package_id: packageId,
          minutes_purchased: pkg.minutes,
          minutes_remaining: pkg.minutes,
          currency: currency,
          price_paid: price,
          is_auto_purchase: false,
          expires_at: subData?.period_end || new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString(),
          is_active: true
        });

      if (purchaseError) throw purchaseError;

      // Log billing history
      await supabase.from('billing_history').insert({
        store_id: storeId,
        subscription_id: subscriptionId,
        event_type: 'package_purchased',
        currency: currency,
        amount: price,
        package_id: packageId,
        description: `Purchased ${pkg.minutes} minutes package`
      });

      return true;
    } catch (err) {
      console.error('Error purchasing package:', err);
      return false;
    }
  };

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

  return {
    packages,
    isLoading,
    error,
    purchasePackage,
    refetch: fetchPackages
  };
}
