import { apiClient } from './client'
import type { AnalyticsResponse, TrendsResponse, ExportResponse } from '@/types/api'

// New analytics types
export interface SourceAnalyticsResponse {
  success: boolean
  data: {
    lead_sources: Array<{ page_url: string; lead_count: number }>
    conversation_sources: Array<{ page_url: string; conversation_count: number }>
  }
}

export interface WidgetUsageItem {
  widget_id: number
  widget_name: string
  widget_type: string
  total_uses: number
}

export interface WidgetAnalyticsResponse {
  success: boolean
  data: {
    leads_by_widget: Array<{ widget_id: number; widget_name: string; widget_type: string; lead_count: number }>
    meetings_by_widget: Array<{ widget_id: number; widget_name: string; meeting_count: number }>
    widget_usage: WidgetUsageItem[]
  }
}

export interface FunnelStage {
  stage: string
  label: string
  label_he: string
  count: number
}

export interface FunnelParallelMetric {
  count: number
  label: string
  label_he: string
}

export interface FunnelSatisfaction {
  average: number
  count: number
  label: string
  label_he: string
}

export interface FunnelAnalyticsResponse {
  success: boolean
  data: {
    period: string
    bot_id: number | null
    funnel: FunnelStage[]
    meetings: FunnelParallelMetric
    satisfaction: FunnelSatisfaction
  }
}

export interface BotPerformance {
  bot_id: number
  bot_name: string
  lead_count: number
  meeting_count: number
  avg_rating: number
  rating_count: number
  widget_usage: Array<{ widget_id: number; widget_name: string; widget_type: string; usage_count: number }>
}

export interface BotAnalyticsResponse {
  success: boolean
  data: {
    leads_by_bot: Array<{ bot_id: number; bot_name: string; lead_count: number }>
    bots_performance: BotPerformance[]
  }
}

export interface CommerceRevenueByCurrency {
  currency_code: string
  amount: number
}

export interface CommerceSummary {
  views: number
  add_to_cart: number
  checkout_clicks: number
  coupons_applied: number
  bundles_added: number
  revenue_by_currency: CommerceRevenueByCurrency[]
}

export interface CommerceFunnelStage {
  stage: string
  label: string
  count: number
}

export interface CommerceDailyTrend {
  date: string
  views: number
  add_to_cart: number
  checkout_clicks: number
  coupons_applied: number
  bundles_added: number
}

export interface CommerceLanguageBreakdown {
  language: string
  total_events: number
  views: number
  add_to_cart: number
  checkout_clicks: number
}

export interface CommerceBotBreakdown {
  bot_id: number | null
  bot_name: string
  total_events: number
  views: number
  add_to_cart: number
  checkout_clicks: number
  tracked_value: number
}

export interface CommerceProductBreakdown {
  product_id: number
  product_name: string
  views: number
  add_to_cart: number
  failures: number
}

export interface CommerceCouponBreakdown {
  coupon_code: string
  views: number
  copies: number
  applies: number
  failures: number
}

export interface CommerceAnalyticsResponse {
  success: boolean
  data: {
    period: string
    bot_id: number | null
    language: string | null
    summary: CommerceSummary
    funnel: CommerceFunnelStage[]
    daily_trends: CommerceDailyTrend[]
    by_language: CommerceLanguageBreakdown[]
    by_bot: CommerceBotBreakdown[]
    top_products: CommerceProductBreakdown[]
    top_coupons: CommerceCouponBreakdown[]
  }
}

/**
 * Analytics API
 */
export const analyticsApi = {
  /**
   * Get dashboard stats
   */
  async getDashboard(language?: string): Promise<AnalyticsResponse> {
    const params: Record<string, unknown> = {}
    if (language) params.language = language
    return apiClient.get<AnalyticsResponse>('analytics', params)
  },
  
  /**
   * Get trends data
   */
  async getTrends(period: '7days' | '30days' | '90days' = '7days', language?: string): Promise<TrendsResponse> {
    const params: Record<string, unknown> = { period }
    if (language) params.language = language
    return apiClient.get<TrendsResponse>('analytics/trends', params)
  },

  /**
   * Get source analytics - which pages generate leads/conversations
   */
  async getSources(language?: string): Promise<SourceAnalyticsResponse> {
    const params: Record<string, unknown> = {}
    if (language) params.language = language
    return apiClient.get<SourceAnalyticsResponse>('analytics/sources', params)
  },

  /**
   * Get widget analytics - which widgets generate leads/meetings/usage
   */
  async getWidgets(botId?: number, language?: string): Promise<WidgetAnalyticsResponse> {
    const params: Record<string, unknown> = {}
    if (botId) params.bot_id = botId
    if (language) params.language = language
    return apiClient.get<WidgetAnalyticsResponse>('analytics/widgets', params)
  },

  /**
   * Get funnel analytics - conversion funnel stages
   */
  async getFunnel(period: '7days' | '30days' | '90days' = '30days', botId?: number, language?: string): Promise<FunnelAnalyticsResponse> {
    const params: Record<string, unknown> = { period }
    if (botId) params.bot_id = botId
    if (language) params.language = language
    return apiClient.get<FunnelAnalyticsResponse>('analytics/funnel', params)
  },

  /**
   * Get bot analytics - comprehensive bot performance
   */
  async getBots(language?: string): Promise<BotAnalyticsResponse> {
    const params: Record<string, unknown> = {}
    if (language) params.language = language
    return apiClient.get<BotAnalyticsResponse>('analytics/bots', params)
  },

  async getCommerce(period: '7days' | '30days' | '90days' = '30days', botId?: number, language?: string): Promise<CommerceAnalyticsResponse> {
    const params: Record<string, unknown> = { period }
    if (botId) params.bot_id = botId
    if (language) params.language = language
    return apiClient.get<CommerceAnalyticsResponse>('commerce-analytics', params)
  },
}

/**
 * Export API
 */
export const exportApi = {
  /**
   * Export leads to CSV
   */
  async exportLeads(filters?: Record<string, unknown>): Promise<ExportResponse> {
    return apiClient.get<ExportResponse>('export/leads', {
      format: 'csv',
      ...filters,
    })
  },
  
  /**
   * Export conversations to CSV
   */
  async exportConversations(): Promise<ExportResponse> {
    return apiClient.get<ExportResponse>('export/conversations', {
      format: 'csv',
    })
  },
}
