import { useState } from 'react'
import { TrendingUp, Users, MessageSquare, Target, BarChart3, GitBranch, Puzzle, Bot, Filter, ShoppingCart, Tag, Package } from 'lucide-react'
import { ResponsiveContainer, BarChart, Bar, CartesianGrid, Tooltip, XAxis, YAxis } from 'recharts'
import { 
  useDashboard, 
  useTrends, 
  useSourceAnalytics, 
  useWidgetAnalytics, 
  useFunnelAnalytics, 
  useBotAnalytics,
  useCommerceAnalytics,
} from '@/hooks/useAnalytics'
import { PageHeader } from '@/components/layout/PageHeader'
import { Card, CardHeader, CardTitle, CardContent } from '@/components/common/Card'
import { Button } from '@/components/common/Button'
import { PageLoading } from '@/components/common/Spinner'
import { SourcesTable } from '@/components/analytics/SourcesTable'
import { WidgetChart } from '@/components/analytics/WidgetChart'
import { FunnelChart } from '@/components/analytics/FunnelChart'
import { BotTable } from '@/components/analytics/BotTable'
import { formatNumber } from '@/utils/formatters'
import { t, isRtl } from '@/lib/i18n'
import { useLanguage } from '@/contexts/LanguageContext'

type Period = '7days' | '30days' | '90days'
type Tab = 'overview' | 'sources' | 'widgets' | 'funnel' | 'commerce' | 'bots'

function formatCurrencyAmount(amount: number, currencyCode: string) {
  try {
    return new Intl.NumberFormat(isRtl() ? 'he-IL' : 'en-US', {
      style: 'currency',
      currency: currencyCode,
      maximumFractionDigits: currencyCode.toUpperCase() === 'ILS' ? 0 : 2,
    }).format(amount)
  } catch {
    return `${currencyCode} ${amount.toFixed(2)}`
  }
}

function formatRevenueSummary(revenueByCurrency: Array<{ currency_code: string; amount: number }>) {
  if (!revenueByCurrency || revenueByCurrency.length === 0) {
    return '0'
  }

  return revenueByCurrency
    .map((entry) => formatCurrencyAmount(entry.amount, entry.currency_code))
    .join(' • ')
}

export function Analytics() {
  const [period, setPeriod] = useState<Period>('7days')
  const [activeTab, setActiveTab] = useState<Tab>('overview')
  const [selectedBotId, setSelectedBotId] = useState<number | undefined>(undefined)
  const { currentLanguage } = useLanguage()
  
  const { data: dashboardData, isLoading: dashboardLoading, isError: dashboardError } = useDashboard(currentLanguage)
  const { data: trendsData, isLoading: trendsLoading, isError: trendsError } = useTrends(period, currentLanguage)
  const { data: sourceData, isLoading: sourceLoading, isError: sourceError } = useSourceAnalytics(currentLanguage)
  const { data: widgetData, isLoading: widgetLoading, isError: widgetError } = useWidgetAnalytics(selectedBotId, currentLanguage)
  const { data: funnelData, isLoading: funnelLoading, isError: funnelError } = useFunnelAnalytics(period, selectedBotId, currentLanguage)
  const { data: commerceData, isLoading: commerceLoading, isError: commerceError } = useCommerceAnalytics(period, selectedBotId, currentLanguage)
  const { data: botData, isLoading: botLoading, isError: botError } = useBotAnalytics(currentLanguage)
  
  if (dashboardLoading || trendsLoading) {
    return <PageLoading />
  }

  if (dashboardError || trendsError) {
    return (
      <div className="p-6 text-center text-red-500">
        {t('Error loading analytics data. Please try again.')}
      </div>
    )
  }
  
  const stats = dashboardData?.data
  const trends = trendsData?.data?.trends || []
  const botsPerformance = botData?.data?.bots_performance || []
  
  const tabs: { id: Tab; label: string; icon: React.ComponentType<{ className?: string }> }[] = [
    { id: 'overview', label: t('Overview'), icon: BarChart3 },
    { id: 'sources', label: t('Traffic Sources'), icon: TrendingUp },
    { id: 'widgets', label: t('Widgets'), icon: Puzzle },
    { id: 'funnel', label: t('Funnel'), icon: GitBranch },
    { id: 'commerce', label: t('Commerce Funnel'), icon: ShoppingCart },
    { id: 'bots', label: t('Bots'), icon: Bot },
  ]
  
  return (
    <div className="space-y-6 animate-fade-in">
      <PageHeader title={t('Analytics')} subtitle={t('Statistics and trends')}>
        <div className="flex items-center gap-3">
          {/* Bot filter dropdown */}
          {botsPerformance.length > 0 && (
            <div className="flex items-center gap-2">
              <Filter className="w-4 h-4 text-gray-400" />
              <select
                value={selectedBotId || ''}
                onChange={(e) => setSelectedBotId(e.target.value ? Number(e.target.value) : undefined)}
                className="text-sm border border-gray-200 rounded-lg px-3 py-1.5 text-gray-700 bg-white focus:outline-none focus:ring-2 focus:ring-primary-500"
              >
                <option value="">{t('All Bots')}</option>
                {botsPerformance.map((bot) => (
                  <option key={bot.bot_id} value={bot.bot_id}>
                    {bot.bot_name}
                  </option>
                ))}
              </select>
            </div>
          )}
          {/* Period buttons */}
          <div className="flex gap-2">
            {(['7days', '30days', '90days'] as Period[]).map((p) => (
              <Button
                key={p}
                variant={period === p ? 'primary' : 'outline'}
                size="sm"
                onClick={() => setPeriod(p)}
              >
                {p === '7days' ? t('7 days') : p === '30days' ? t('30 days') : t('90 days')}
              </Button>
            ))}
          </div>
        </div>
      </PageHeader>
      
      {/* Tab Navigation */}
      <div className="border-b border-gray-200">
        <nav className="flex gap-4 -mb-px">
          {tabs.map((tab) => {
            const Icon = tab.icon
            const isActive = activeTab === tab.id
            return (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id)}
                className={`
                  flex items-center gap-2 px-4 py-3 text-sm font-medium border-b-2 transition-colors
                  ${isActive 
                    ? 'border-primary-500 text-primary-600' 
                    : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'}
                `}
              >
                <Icon className="w-4 h-4" />
                {tab.label}
              </button>
            )
          })}
        </nav>
      </div>
      
      {/* Tab Content */}
      {activeTab === 'overview' && (
        <OverviewTab stats={stats} trends={trends} />
      )}
      
      {activeTab === 'sources' && (
        <SourcesTab 
          leadSources={sourceData?.data?.lead_sources || []}
          conversationSources={sourceData?.data?.conversation_sources || []}
          isLoading={sourceLoading}
          isError={sourceError}
        />
      )}
      
      {activeTab === 'widgets' && (
        <WidgetsTab 
          leadsByWidget={widgetData?.data?.leads_by_widget || []}
          meetingsByWidget={widgetData?.data?.meetings_by_widget || []}
          widgetUsage={widgetData?.data?.widget_usage || []}
          isLoading={widgetLoading}
          isError={widgetError}
        />
      )}
      
      {activeTab === 'funnel' && (
        <FunnelTab 
          funnel={funnelData?.data?.funnel || []}
          meetings={funnelData?.data?.meetings}
          satisfaction={funnelData?.data?.satisfaction}
          period={period}
          isLoading={funnelLoading}
          isError={funnelError}
        />
      )}

      {activeTab === 'commerce' && (
        <CommerceTab
          data={commerceData?.data}
          isLoading={commerceLoading}
          isError={commerceError}
        />
      )}
      
      {activeTab === 'bots' && (
        <BotsTab 
          leadsByBot={botData?.data?.leads_by_bot || []}
          botsPerformance={botsPerformance}
          isLoading={botLoading}
          isError={botError}
        />
      )}
    </div>
  )
}

// Overview Tab
function OverviewTab({ 
  stats, 
  trends
}: { 
  stats: any
  trends: any[]
}) {
  return (
    <div className="space-y-6">
      {/* Overview Stats */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        <OverviewCard
          title={t('Total Leads')}
          value={formatNumber(stats?.leads?.total ?? 0)}
          icon={Users}
          color="primary"
        />
        <OverviewCard
          title={t('Total Conversations')}
          value={formatNumber(stats?.conversations?.total ?? 0)}
          icon={MessageSquare}
          color="accent"
        />
        <OverviewCard
          title={t('Conversion Rate')}
          value={`${(stats?.conversions?.rate ?? 0).toFixed(1)}%`}
          icon={Target}
          color="success"
        />
        <OverviewCard
          title={t('Avg Messages/Conversation')}
          value={(stats?.conversations?.avg_messages ?? 0).toFixed(1)}
          icon={TrendingUp}
          color="warning"
        />
      </div>
      
      {/* Trends */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Lead Trend */}
        <Card>
          <CardHeader>
            <CardTitle>{t('Lead Trend')}</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-2 max-h-96 overflow-y-auto">
              {trends.map((day: { date: string; leads: number }) => (
                <div key={day.date} className="flex items-center gap-4">
                  <span className="text-sm text-gray-500 w-24 shrink-0">
                    {new Date(day.date).toLocaleDateString(isRtl() ? 'he-IL' : 'en-US', { 
                      weekday: 'short', 
                      day: 'numeric', 
                      month: 'short' 
                    })}
                  </span>
                  <div className="flex-1 h-5 bg-gray-100 rounded-full overflow-hidden">
                    <div 
                      className="h-full bg-primary-500 rounded-full transition-all"
                      style={{ 
                        width: `${Math.min((day.leads / Math.max(...trends.map((t: { leads: number }) => t.leads), 1)) * 100, 100)}%` 
                      }}
                    />
                  </div>
                  <span className="text-sm font-medium w-8 text-end">{day.leads}</span>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
        
        {/* Conversation Trend */}
        <Card>
          <CardHeader>
            <CardTitle>{t('Conversation Trend')}</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-2 max-h-96 overflow-y-auto">
              {trends.map((day: { date: string; conversations: number }) => (
                <div key={day.date} className="flex items-center gap-4">
                  <span className="text-sm text-gray-500 w-24 shrink-0">
                    {new Date(day.date).toLocaleDateString(isRtl() ? 'he-IL' : 'en-US', { 
                      weekday: 'short', 
                      day: 'numeric', 
                      month: 'short' 
                    })}
                  </span>
                  <div className="flex-1 h-5 bg-gray-100 rounded-full overflow-hidden">
                    <div 
                      className="h-full bg-accent-500 rounded-full transition-all"
                      style={{ 
                        width: `${Math.min((day.conversations / Math.max(...trends.map((t: { conversations: number }) => t.conversations), 1)) * 100, 100)}%` 
                      }}
                    />
                  </div>
                  <span className="text-sm font-medium w-8 text-end">{day.conversations}</span>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      </div>
      
      {/* Messages Trend Heatmap */}
      <Card>
        <CardHeader>
          <CardTitle>{t('Messages Trend')}</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-7 md:grid-cols-14 lg:grid-cols-30 gap-1">
            {trends.map((day: { date: string; messages: number }) => {
              const maxMessages = Math.max(...trends.map((t: { messages: number }) => t.messages), 1)
              const intensity = Math.min(day.messages / maxMessages, 1)
              return (
                <div 
                  key={day.date}
                  className="aspect-square rounded"
                  style={{ 
                    backgroundColor: `rgba(59, 130, 246, ${0.1 + intensity * 0.9})` 
                  }}
                  title={`${day.date}: ${day.messages} ${t('messages')}`}
                />
              )
            })}
          </div>
          <div className="flex justify-between mt-2 text-xs text-gray-500">
            <span>{trends[0]?.date}</span>
            <span>{trends[trends.length - 1]?.date}</span>
          </div>
        </CardContent>
      </Card>
      
      {/* Summary Stats */}
      <Card>
        <CardHeader>
          <CardTitle>{t('Quick Stats')}</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-2 md:grid-cols-5 gap-6">
            <div className="text-center">
              <p className="text-3xl font-bold text-gray-900">
                {formatNumber(stats?.leads?.this_month ?? 0)}
              </p>
              <p className="text-sm text-gray-500">{t('Leads This Month')}</p>
            </div>
            <div className="text-center">
              <p className="text-3xl font-bold text-gray-900">
                {formatNumber(stats?.leads?.this_week ?? 0)}
              </p>
              <p className="text-sm text-gray-500">{t('Leads This Week')}</p>
            </div>
            <div className="text-center">
              <p className="text-3xl font-bold text-gray-900">
                {formatNumber(stats?.conversations?.this_month ?? 0)}
              </p>
              <p className="text-sm text-gray-500">{t('Conversations This Month')}</p>
            </div>
            <div className="text-center">
              <p className="text-3xl font-bold text-gray-900">
                {formatNumber(stats?.meetings?.this_month ?? 0)}
              </p>
              <p className="text-sm text-gray-500">{t('Meetings This Month')}</p>
            </div>
            <div className="text-center">
              <p className="text-3xl font-bold text-gray-900">
                {formatNumber(stats?.conversions?.total ?? 0)}
              </p>
              <p className="text-sm text-gray-500">{t('Conversions')}</p>
            </div>
          </div>
        </CardContent>
      </Card>
    </div>
  )
}

// Sources Tab
function SourcesTab({ 
  leadSources, 
  conversationSources, 
  isLoading,
  isError,
}: { 
  leadSources: any[]
  conversationSources: any[]
  isLoading: boolean
  isError: boolean
}) {
  if (isLoading) {
    return <PageLoading />
  }
  if (isError) {
    return <div className="p-6 text-center text-red-500">{t('Error loading analytics data. Please try again.')}</div>
  }
  
  return (
    <div className="space-y-6">
      <div className="bg-blue-50 border border-blue-100 rounded-lg p-4">
        <p className="text-sm text-blue-700">
          {t('See which pages on your site generate the most leads and conversations.')}
        </p>
      </div>
      <SourcesTable 
        leadSources={leadSources} 
        conversationSources={conversationSources} 
      />
    </div>
  )
}

// Widgets Tab
function WidgetsTab({ 
  leadsByWidget, 
  meetingsByWidget, 
  widgetUsage,
  isLoading,
  isError,
}: { 
  leadsByWidget: any[]
  meetingsByWidget: any[]
  widgetUsage: any[]
  isLoading: boolean
  isError: boolean
}) {
  if (isLoading) {
    return <PageLoading />
  }
  if (isError) {
    return <div className="p-6 text-center text-red-500">{t('Error loading analytics data. Please try again.')}</div>
  }
  
  return (
    <div className="space-y-6">
      <div className="bg-purple-50 border border-purple-100 rounded-lg p-4">
        <p className="text-sm text-purple-700">
          {t('See which widgets generate the most leads and meetings.')}
        </p>
      </div>
      <WidgetChart 
        leadsByWidget={leadsByWidget} 
        meetingsByWidget={meetingsByWidget} 
      />
      {/* General widget usage */}
      {widgetUsage.length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Puzzle className="w-5 h-5" />
              {t('Widget Usage')}
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-3">
              {widgetUsage.map((widget: any) => {
                const maxUses = Math.max(...widgetUsage.map((w: any) => Number(w.total_uses) || 0), 1)
                const percentage = ((Number(widget.total_uses) || 0) / maxUses) * 100
                return (
                  <div key={widget.widget_id}>
                    <div className="flex justify-between text-sm mb-1">
                      <span className="text-gray-700 font-medium truncate">
                        {widget.widget_name || widget.widget_type}
                      </span>
                      <div className="flex items-center gap-2 shrink-0">
                        <span className="text-xs text-gray-400">{widget.widget_type}</span>
                        <span className="text-gray-900 font-semibold">{widget.total_uses}</span>
                      </div>
                    </div>
                    <div className="w-full bg-gray-100 rounded-full h-2 overflow-hidden">
                      <div 
                        className="h-full bg-purple-500 rounded-full transition-all"
                        style={{ width: `${percentage}%` }}
                      />
                    </div>
                  </div>
                )
              })}
            </div>
          </CardContent>
        </Card>
      )}
    </div>
  )
}

// Funnel Tab
function FunnelTab({ 
  funnel, 
  meetings,
  satisfaction,
  period, 
  isLoading,
  isError,
}: { 
  funnel: any[]
  meetings?: any
  satisfaction?: any
  period: string
  isLoading: boolean
  isError: boolean
}) {
  if (isLoading) {
    return <PageLoading />
  }
  if (isError) {
    return <div className="p-6 text-center text-red-500">{t('Error loading analytics data. Please try again.')}</div>
  }
  
  return (
    <div className="space-y-6">
      <div className="bg-green-50 border border-green-100 rounded-lg p-4">
        <p className="text-sm text-green-700">
          {t('Track your conversion funnel from conversations to converted leads.')}
        </p>
      </div>
      <FunnelChart 
        funnel={funnel} 
        period={period} 
        meetings={meetings}
        satisfaction={satisfaction}
      />
    </div>
  )
}

// Bots Tab
function BotsTab({ 
  leadsByBot, 
  botsPerformance,
  isLoading,
  isError,
}: { 
  leadsByBot: any[]
  botsPerformance?: any[]
  isLoading: boolean
  isError: boolean
}) {
  if (isLoading) {
    return <PageLoading />
  }
  if (isError) {
    return <div className="p-6 text-center text-red-500">{t('Error loading analytics data. Please try again.')}</div>
  }
  
  return (
    <div className="space-y-6">
      <div className="bg-orange-50 border border-orange-100 rounded-lg p-4">
        <p className="text-sm text-orange-700">
          {t('Compare performance across your different bots.')}
        </p>
      </div>
      <BotTable leadsByBot={leadsByBot} botsPerformance={botsPerformance} />
    </div>
  )
}

function CommerceTab({
  data,
  isLoading,
  isError,
}: {
  data?: any
  isLoading: boolean
  isError: boolean
}) {
  if (isLoading) {
    return <PageLoading />
  }
  if (isError) {
    return <div className="p-6 text-center text-red-500">{t('Error loading analytics data. Please try again.')}</div>
  }

  const summary = data?.summary
  const dailyTrends = data?.daily_trends || []
  const funnel = data?.funnel || []
  const byLanguage = data?.by_language || []
  const byBot = data?.by_bot || []
  const topProducts = data?.top_products || []
  const topCoupons = data?.top_coupons || []

  return (
    <div className="space-y-6">
      <div className="bg-emerald-50 border border-emerald-100 rounded-lg p-4">
        <p className="text-sm text-emerald-700">
          {t('Track product views, cart intent, coupon usage, and checkout clicks across your commerce chat funnel.')}
        </p>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-6">
        <OverviewCard title={t('Product Views')} value={formatNumber(summary?.views ?? 0)} icon={BarChart3} color="primary" />
        <OverviewCard title={t('Add to Cart')} value={formatNumber(summary?.add_to_cart ?? 0)} icon={ShoppingCart} color="accent" />
        <OverviewCard title={t('Checkout Clicks')} value={formatNumber(summary?.checkout_clicks ?? 0)} icon={Target} color="success" />
        <OverviewCard title={t('Coupons Applied')} value={formatNumber(summary?.coupons_applied ?? 0)} icon={Tag} color="warning" />
        <OverviewCard title={t('Bundles Added')} value={formatNumber(summary?.bundles_added ?? 0)} icon={Package} color="accent" />
        <OverviewCard title={t('Tracked Revenue')} value={formatRevenueSummary(summary?.revenue_by_currency || [])} icon={TrendingUp} color="success" />
      </div>

      <div className="grid grid-cols-1 xl:grid-cols-2 gap-6">
        <Card>
          <CardHeader>
            <CardTitle>{t('Daily Commerce Trend')}</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="h-80">
              <ResponsiveContainer width="100%" height="100%">
                <BarChart data={dailyTrends}>
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="date" />
                  <YAxis />
                  <Tooltip />
                  <Bar dataKey="views" fill="#3BC2D0" radius={[4, 4, 0, 0]} />
                  <Bar dataKey="add_to_cart" fill="#E32774" radius={[4, 4, 0, 0]} />
                  <Bar dataKey="checkout_clicks" fill="#16A34A" radius={[4, 4, 0, 0]} />
                </BarChart>
              </ResponsiveContainer>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>{t('Commerce Funnel')}</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-4">
              {funnel.map((stage: { stage: string; label: string; count: number }, index: number) => {
                const maxCount = Math.max(...funnel.map((item: { count: number }) => item.count), 1)
                const width = Math.max((stage.count / maxCount) * 100, stage.count > 0 ? 12 : 0)
                return (
                  <div key={stage.stage}>
                    <div className="flex items-center justify-between text-sm mb-1">
                      <span className="font-medium text-gray-700">{t(stage.label)}</span>
                      <span className="text-gray-900 font-semibold">{formatNumber(stage.count)}</span>
                    </div>
                    <div className="w-full h-3 bg-gray-100 rounded-full overflow-hidden">
                      <div
                        className="h-full rounded-full transition-all"
                        style={{
                          width: `${width}%`,
                          background: index === 0 ? '#3BC2D0' : index === 1 ? '#E32774' : '#16A34A',
                        }}
                      />
                    </div>
                  </div>
                )
              })}
            </div>
          </CardContent>
        </Card>
      </div>

      <div className="grid grid-cols-1 xl:grid-cols-2 gap-6">
        <Card>
          <CardHeader>
            <CardTitle>{t('By Language')}</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-3">
              {byLanguage.length === 0 && <p className="text-sm text-gray-500">{t('No data available yet')}</p>}
              {byLanguage.map((row: any) => (
                <div key={row.language} className="rounded-xl border border-gray-100 px-4 py-3">
                  <div className="flex items-center justify-between">
                    <span className="font-medium text-gray-900">{String(row.language || '').toUpperCase() || '—'}</span>
                    <span className="text-sm text-gray-500">{formatNumber(Number(row.total_events) || 0)} {t('events')}</span>
                  </div>
                  <div className="mt-2 grid grid-cols-3 gap-3 text-xs text-gray-500">
                    <span>{t('Views')}: {formatNumber(Number(row.views) || 0)}</span>
                    <span>{t('Add to cart')}: {formatNumber(Number(row.add_to_cart) || 0)}</span>
                    <span>{t('Checkout clicks')}: {formatNumber(Number(row.checkout_clicks) || 0)}</span>
                  </div>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>{t('By Bot')}</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-3">
              {byBot.length === 0 && <p className="text-sm text-gray-500">{t('No data available yet')}</p>}
              {byBot.map((row: any) => (
                <div key={`${row.bot_id ?? 'none'}-${row.bot_name}`} className="rounded-xl border border-gray-100 px-4 py-3">
                  <div className="flex items-center justify-between gap-3">
                    <span className="font-medium text-gray-900 truncate">{row.bot_name}</span>
                    <span className="text-sm text-gray-500">{formatNumber(Number(row.total_events) || 0)} {t('events')}</span>
                  </div>
                  <div className="mt-2 grid grid-cols-2 gap-3 text-xs text-gray-500">
                    <span>{t('Views')}: {formatNumber(Number(row.views) || 0)}</span>
                    <span>{t('Add to cart')}: {formatNumber(Number(row.add_to_cart) || 0)}</span>
                    <span>{t('Checkout clicks')}: {formatNumber(Number(row.checkout_clicks) || 0)}</span>
                    <span>{t('Tracked value')}: {Number(row.tracked_value || 0).toFixed(2)}</span>
                  </div>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      </div>

      <div className="grid grid-cols-1 xl:grid-cols-2 gap-6">
        <Card>
          <CardHeader>
            <CardTitle>{t('Top Products')}</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-3">
              {topProducts.length === 0 && <p className="text-sm text-gray-500">{t('No data available yet')}</p>}
              {topProducts.map((product: any) => (
                <div key={product.product_id} className="flex items-center justify-between gap-3 rounded-xl border border-gray-100 px-4 py-3">
                  <div className="min-w-0">
                    <p className="font-medium text-gray-900 truncate">{product.product_name || `${t('Product')} #${product.product_id}`}</p>
                    <p className="text-xs text-gray-500">{t('Views')}: {formatNumber(Number(product.views) || 0)} · {t('Add to cart')}: {formatNumber(Number(product.add_to_cart) || 0)}</p>
                  </div>
                  <span className="text-xs text-red-500">{t('Failures')}: {formatNumber(Number(product.failures) || 0)}</span>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>{t('Top Coupons')}</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-3">
              {topCoupons.length === 0 && <p className="text-sm text-gray-500">{t('No data available yet')}</p>}
              {topCoupons.map((coupon: any) => (
                <div key={coupon.coupon_code} className="flex items-center justify-between gap-3 rounded-xl border border-gray-100 px-4 py-3">
                  <div>
                    <p className="font-medium text-gray-900">{coupon.coupon_code}</p>
                    <p className="text-xs text-gray-500">{t('Views')}: {formatNumber(Number(coupon.views) || 0)} · {t('Copies')}: {formatNumber(Number(coupon.copies) || 0)}</p>
                  </div>
                  <div className="text-xs text-gray-500 text-end">
                    <p>{t('Applies')}: {formatNumber(Number(coupon.applies) || 0)}</p>
                    <p>{t('Failures')}: {formatNumber(Number(coupon.failures) || 0)}</p>
                  </div>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  )
}

// Overview Card Component
function OverviewCard({ 
  title, 
  value, 
  icon: Icon, 
  color 
}: { 
  title: string
  value: string
  icon: React.ComponentType<{ className?: string }>
  color: 'primary' | 'accent' | 'success' | 'warning'
}) {
  const colorClasses = {
    primary: 'bg-primary-50 text-primary-600',
    accent: 'bg-accent-50 text-accent-600',
    success: 'bg-green-50 text-green-600',
    warning: 'bg-yellow-50 text-yellow-600',
  }
  
  return (
    <Card>
      <CardContent className="flex items-center gap-4">
        <div className={`p-3 rounded-lg ${colorClasses[color]}`}>
          <Icon className="w-6 h-6" />
        </div>
        <div>
          <p className="text-2xl font-bold text-gray-900">{value}</p>
          <p className="text-sm text-gray-500">{title}</p>
        </div>
      </CardContent>
    </Card>
  )
}
