// Add-ons management utilities for Black Canyon Tickets
import { supabase } from './supabase';

export interface AddOnType {
  id: string;
  slug: string;
  name: string;
  description: string;
  pricing_type: 'per_event' | 'monthly' | 'annual' | 'per_ticket';
  price_cents: number;
  category: 'feature' | 'service' | 'analytics' | 'marketing' | 'subscription';
  is_active: boolean;
  requires_setup: boolean;
  feature_flags: Record<string, boolean>;
  sort_order: number;
}

export interface EventAddOn {
  id: string;
  event_id: string;
  add_on_type_id: string;
  organization_id: string;
  purchase_price_cents: number;
  status: 'active' | 'cancelled' | 'expired';
  purchased_at: string;
  expires_at?: string;
  metadata?: Record<string, any>;
}

export interface AddOnWithAccess extends AddOnType {
  has_access: boolean;
  purchased_at?: string;
}

// Get all available add-ons for an organization/event
export async function getAvailableAddOns(
  organizationId: string, 
  eventId?: string
): Promise<AddOnWithAccess[]> {
  try {
    const { data, error } = await supabase
      .rpc('get_available_addons', {
        p_organization_id: organizationId,
        p_event_id: eventId || null
      });

    if (error) throw error;

    return data.map((item: any) => ({
      id: item.addon_id,
      slug: item.slug,
      name: item.name,
      description: item.description,
      pricing_type: item.pricing_type,
      price_cents: item.price_cents,
      category: item.category,
      is_active: true,
      requires_setup: false,
      feature_flags: {},
      sort_order: 0,
      has_access: item.has_access,
      purchased_at: item.purchased_at
    }));
  } catch (error) {
    console.error('Error fetching available add-ons:', error);
    return [];
  }
}

// Check if user has access to specific feature
export async function hasFeatureAccess(
  organizationId: string,
  eventId: string | null,
  featureFlag: string
): Promise<boolean> {
  try {
    const { data, error } = await supabase
      .rpc('has_feature_access', {
        p_organization_id: organizationId,
        p_event_id: eventId,
        p_feature_flag: featureFlag
      });

    if (error) throw error;
    return data === true;
  } catch (error) {
    console.error('Error checking feature access:', error);
    return false;
  }
}

// Purchase an add-on for an event
export async function purchaseEventAddOn(
  eventId: string,
  addOnTypeId: string,
  organizationId: string,
  priceCents: number,
  metadata?: Record<string, any>
): Promise<{ success: boolean; addOnId?: string; error?: string }> {
  try {
    const { data, error } = await supabase
      .from('event_add_ons')
      .insert([{
        event_id: eventId,
        add_on_type_id: addOnTypeId,
        organization_id: organizationId,
        purchase_price_cents: priceCents,
        status: 'active',
        metadata: metadata || {}
      }])
      .select()
      .single();

    if (error) throw error;

    return { success: true, addOnId: data.id };
  } catch (error) {
    console.error('Error purchasing add-on:', error);
    return { 
      success: false, 
      error: error instanceof Error ? error.message : 'Unknown error' 
    };
  }
}

// Get event add-ons for a specific event
export async function getEventAddOns(eventId: string): Promise<EventAddOn[]> {
  try {
    const { data, error } = await supabase
      .from('event_add_ons')
      .select(`
        *,
        add_on_types (
          slug,
          name,
          description,
          feature_flags
        )
      `)
      .eq('event_id', eventId)
      .eq('status', 'active');

    if (error) throw error;
    return data || [];
  } catch (error) {
    console.error('Error fetching event add-ons:', error);
    return [];
  }
}

// Format price for display
export function formatAddOnPrice(priceCents: number, pricingType: string): string {
  const price = priceCents / 100;
  const formattedPrice = new Intl.NumberFormat('en-US', {
    style: 'currency',
    currency: 'USD'
  }).format(price);

  switch (pricingType) {
    case 'per_event':
      return `${formattedPrice} per event`;
    case 'monthly':
      return `${formattedPrice}/month`;
    case 'annual':
      return `${formattedPrice}/year`;
    case 'per_ticket':
      return `${formattedPrice} per ticket`;
    default:
      return formattedPrice;
  }
}

// Get add-on category icon
export function getAddOnCategoryIcon(category: string): string {
  const icons = {
    feature: '⚡',
    service: '🎯',
    analytics: '📊',
    marketing: '📢',
    subscription: '⭐'
  };
  return icons[category as keyof typeof icons] || '🔧';
}

// Get add-on category color
export function getAddOnCategoryColor(category: string): string {
  const colors = {
    feature: 'blue',
    service: 'green',
    analytics: 'purple',
    marketing: 'orange',
    subscription: 'indigo'
  };
  return colors[category as keyof typeof colors] || 'gray';
}

// Calculate total add-on revenue for organization
export async function calculateAddOnRevenue(organizationId: string): Promise<{
  totalRevenue: number;
  eventAddOns: number;
  subscriptionRevenue: number;
}> {
  try {
    // Event add-ons revenue
    const { data: eventAddOns, error: eventError } = await supabase
      .from('event_add_ons')
      .select('purchase_price_cents')
      .eq('organization_id', organizationId)
      .eq('status', 'active');

    if (eventError) throw eventError;

    const eventRevenue = (eventAddOns || [])
      .reduce((sum, addon) => sum + addon.purchase_price_cents, 0);

    // Subscription revenue (simplified - would need proper subscription tracking)
    const { data: subscriptions, error: subError } = await supabase
      .from('organization_subscriptions')
      .select(`
        add_on_types (price_cents)
      `)
      .eq('organization_id', organizationId)
      .eq('status', 'active');

    if (subError) throw subError;

    const subscriptionRevenue = (subscriptions || [])
      .reduce((sum, sub: any) => sum + (sub.add_on_types?.price_cents || 0), 0);

    return {
      totalRevenue: eventRevenue + subscriptionRevenue,
      eventAddOns: eventRevenue,
      subscriptionRevenue
    };
  } catch (error) {
    console.error('Error calculating add-on revenue:', error);
    return {
      totalRevenue: 0,
      eventAddOns: 0,
      subscriptionRevenue: 0
    };
  }
}

// Common feature flags
export const FEATURE_FLAGS = {
  SEATING_MAPS: 'seating_maps',
  AI_DESCRIPTION: 'ai_description',
  ADVANCED_ANALYTICS: 'advanced_analytics',
  EMAIL_MARKETING: 'email_marketing',
  PRIORITY_SUPPORT: 'priority_support',
  CUSTOM_BRANDING: 'custom_branding',
  SOCIAL_MEDIA_TOOLS: 'social_media_tools',
  ADVANCED_GUEST_MANAGEMENT: 'advanced_guest_management',
  TICKET_SCANNER: 'ticket_scanner',
  ALL_FEATURES: 'all_features'
} as const;

// Popular add-on bundles for upselling
export const POPULAR_BUNDLES = [
  {
    name: 'Starter Bundle',
    description: 'Perfect for your first premium event',
    addons: ['ai-event-description', 'ticket-scanner'],
    originalPrice: 1000, // $10
    bundlePrice: 800,    // $8 (20% discount)
    savings: 200
  },
  {
    name: 'Professional Bundle',
    description: 'Everything you need for a successful event',
    addons: ['seating-maps', 'premium-analytics', 'ticket-scanner', 'guest-list-pro'],
    originalPrice: 4000, // $40
    bundlePrice: 3000,   // $30 (25% discount)
    savings: 1000
  },
  {
    name: 'Complete Bundle',
    description: 'All automated features for maximum impact',
    addons: ['seating-maps', 'premium-analytics', 'ticket-scanner', 'guest-list-pro', 'ai-event-description', 'custom-event-branding'],
    originalPrice: 6000, // $60
    bundlePrice: 4500,   // $45 (25% discount)
    savings: 1500
  }
] as const;