import { t } from '@/lib/i18n'
import { Card, CardHeader, CardTitle, CardContent } from '@/components/common/Card'
import { Bot, Star, Calendar, Puzzle } from 'lucide-react'
import type { BotPerformance } from '@/api/analytics'

interface BotTableProps {
  leadsByBot: Array<{ bot_id: number; bot_name: string; lead_count: number }>
  botsPerformance?: BotPerformance[]
}

export function BotTable({ leadsByBot, botsPerformance }: BotTableProps) {
  // Use comprehensive performance data if available, otherwise fallback
  const bots = botsPerformance || leadsByBot.map(b => ({
    ...b,
    meeting_count: 0,
    avg_rating: 0,
    rating_count: 0,
    widget_usage: [],
  }))

  const totalLeads = bots.reduce((sum, b) => sum + b.lead_count, 0)

  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center gap-2">
          <Bot className="w-5 h-5" />
          {t('Bot Performance')}
        </CardTitle>
      </CardHeader>
      <CardContent>
        {bots.length === 0 ? (
          <p className="text-gray-500 text-sm text-center py-4">
            {t('No data available')}
          </p>
        ) : (
          <div className="space-y-6">
            {bots.map((bot, index) => {
              const maxLeads = Math.max(...bots.map(b => b.lead_count), 1)
              const percentage = (bot.lead_count / maxLeads) * 100
              const sharePercentage = totalLeads > 0 
                ? ((bot.lead_count / totalLeads) * 100).toFixed(1) 
                : '0'

              // Alternating colors
              const colors = ['bg-primary-500', 'bg-accent-500', 'bg-purple-500', 'bg-blue-500', 'bg-teal-500']
              const bgColor = colors[index % colors.length]

              return (
                <div key={bot.bot_id} className="border border-gray-100 rounded-lg p-4">
                  {/* Bot header */}
                  <div className="flex items-center justify-between mb-3">
                    <div className="flex items-center gap-2">
                      <div className={`w-3 h-3 rounded-full ${bgColor}`} />
                      <span className="text-sm font-semibold text-gray-800">
                        {bot.bot_name}
                      </span>
                    </div>
                    {bot.avg_rating > 0 && (
                      <div className="flex items-center gap-1 px-2 py-0.5 bg-orange-50 rounded-full">
                        <Star className="w-3.5 h-3.5 text-orange-500 fill-orange-500" />
                        <span className="text-xs font-medium text-orange-700">
                          {bot.avg_rating}/5
                        </span>
                        <span className="text-xs text-orange-400">
                          ({bot.rating_count})
                        </span>
                      </div>
                    )}
                  </div>

                  {/* Lead bar */}
                  <div className="mb-3">
                    <div className="flex items-center justify-between mb-1">
                      <span className="text-xs text-gray-500">{t('Leads')}</span>
                      <div className="flex items-center gap-2">
                        <span className="text-xs text-gray-400">{sharePercentage}%</span>
                        <span className="text-sm font-semibold text-gray-900">{bot.lead_count}</span>
                      </div>
                    </div>
                    <div className="w-full bg-gray-100 rounded-full h-2 overflow-hidden">
                      <div 
                        className={`h-full ${bgColor} rounded-full transition-all`}
                        style={{ width: `${percentage}%` }}
                      />
                    </div>
                  </div>

                  {/* Metrics row */}
                  <div className="grid grid-cols-3 gap-3">
                    <div className="text-center p-2 bg-gray-50 rounded">
                      <p className="text-lg font-bold text-gray-900">{bot.lead_count}</p>
                      <p className="text-xs text-gray-500">{t('Leads')}</p>
                    </div>
                    <div className="text-center p-2 bg-gray-50 rounded">
                      <div className="flex items-center justify-center gap-1">
                        <Calendar className="w-3 h-3 text-yellow-600" />
                        <p className="text-lg font-bold text-gray-900">{bot.meeting_count}</p>
                      </div>
                      <p className="text-xs text-gray-500">{t('Meetings')}</p>
                    </div>
                    <div className="text-center p-2 bg-gray-50 rounded">
                      <div className="flex items-center justify-center gap-1">
                        <Puzzle className="w-3 h-3 text-purple-600" />
                        <p className="text-lg font-bold text-gray-900">
                          {bot.widget_usage?.reduce((sum, w) => sum + (w.usage_count || 0), 0) || 0}
                        </p>
                      </div>
                      <p className="text-xs text-gray-500">{t('Widget Uses')}</p>
                    </div>
                  </div>

                  {/* Top widget usage */}
                  {bot.widget_usage && bot.widget_usage.length > 0 && (
                    <div className="mt-3 pt-3 border-t border-gray-100">
                      <p className="text-xs text-gray-400 mb-2">{t('Widget Usage')}</p>
                      <div className="flex flex-wrap gap-2">
                        {bot.widget_usage.slice(0, 5).map((w) => (
                          <span 
                            key={w.widget_id} 
                            className="inline-flex items-center gap-1 px-2 py-0.5 bg-gray-100 rounded text-xs text-gray-600"
                          >
                            {w.widget_name || w.widget_type}
                            <span className="font-semibold">{w.usage_count}</span>
                          </span>
                        ))}
                      </div>
                    </div>
                  )}
                </div>
              )
            })}

            {/* Total */}
            <div className="pt-4 border-t border-gray-100 flex items-center justify-between">
              <span className="text-sm text-gray-600">
                {t('Total Leads')}
              </span>
              <span className="text-lg font-bold text-gray-900">
                {totalLeads.toLocaleString()}
              </span>
            </div>
          </div>
        )}
      </CardContent>
    </Card>
  )
}
