import { Users, MessageSquare, Target, TrendingUp, Calendar, ExternalLink } from 'lucide-react'
import { useDashboard, useSourceAnalytics, useFunnelAnalytics } from '@/hooks/useAnalytics'
import { useLeads } from '@/hooks/useLeads'
import { PageHeader } from '@/components/layout/PageHeader'
import { StatCard } from '@/components/dashboard/StatCard'
import { RecentLeads } from '@/components/dashboard/RecentLeads'
import { PageLoading } from '@/components/common/Spinner'
import { Card, CardHeader, CardTitle, CardContent } from '@/components/common/Card'
import { FunnelChart } from '@/components/analytics/FunnelChart'
import { formatNumber } from '@/utils/formatters'
import { useLanguage } from '@/contexts/LanguageContext'
import { t } from '@/lib/i18n'

export function Dashboard() {
  const { currentLanguage } = useLanguage()

  const { data: stats, isLoading: statsLoading, isError: statsError } = useDashboard(currentLanguage)
  
  const { data: leadsData, isLoading: leadsLoading, isError: leadsError } = useLeads(1, 5, undefined, currentLanguage)
  
  const { data: sourceData } = useSourceAnalytics(currentLanguage)
  
  const { data: funnelData } = useFunnelAnalytics('30days', undefined, currentLanguage)
  
  if (statsLoading || leadsLoading) {
    return <PageLoading />
  }

  if (statsError || leadsError) {
    return (
      <div className="p-6 text-center text-red-500">
        {t('Error loading dashboard data. Please refresh the page.')}
      </div>
    )
  }
  
  const dashboardData = stats?.data
  const recentLeads = leadsData?.data?.leads || []
  const leadSources = sourceData?.data?.lead_sources || []
  const funnelStages = funnelData?.data?.funnel || []
  
  // Calculate conversion rate
  const rawRate = Number(dashboardData?.conversions?.rate)
  const conversionRate = Number.isFinite(rawRate) ? rawRate : 0
  
  return (
    <div className="space-y-6 animate-fade-in">
      <PageHeader 
        title={t('Dashboard')}
        subtitle={t('General overview of bot activity')}
      />
      
      {/* Stats Grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-4">
        <StatCard
          title={t('Leads This Month')}
          value={formatNumber(dashboardData?.leads?.this_month ?? 0)}
          icon={Users}
          color="primary"
        />
        <StatCard
          title={t('Conversations This Month')}
          value={formatNumber(dashboardData?.conversations?.this_month ?? 0)}
          icon={MessageSquare}
          color="accent"
        />
        <StatCard
          title={t('Meetings This Month')}
          value={formatNumber(dashboardData?.meetings?.this_month ?? 0)}
          icon={Calendar}
          color="warning"
        />
        <StatCard
          title={t('Conversion Rate')}
          value={`${conversionRate.toFixed(1)}%`}
          icon={Target}
          color="success"
        />
        <StatCard
          title={t('Avg Messages')}
          value={(dashboardData?.conversations?.avg_messages ?? 0).toFixed(1)}
          icon={TrendingUp}
          color="primary"
        />
      </div>
      
      {/* Funnel and Sources Row */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Conversion Funnel */}
        <FunnelChart 
          funnel={funnelStages} 
          period="30days"
          meetings={funnelData?.data?.meetings}
          satisfaction={funnelData?.data?.satisfaction}
        />
        
        {/* Top Pages */}
        <TopPagesCard leadSources={leadSources} />
      </div>
      
      {/* Main Content */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Lead Status Distribution */}
        <LeadStatusCard statusData={dashboardData?.leads?.by_status} />
        
        {/* Quick Stats */}
        <QuickStats data={dashboardData} />
        
        {/* Recent Leads */}
        <RecentLeads leads={recentLeads} />
      </div>
      
      {/* Usage Stats */}
      <UsageCard usage={dashboardData?.usage} />
    </div>
  )
}

// Top Pages Card Component
function TopPagesCard({ leadSources }: { leadSources: Array<{ page_url: string; lead_count: number }> }) {
  const truncateUrl = (url: string, maxLength = 35): string => {
    if (!url) return '-'
    try {
      const urlObj = new URL(url)
      const path = urlObj.pathname + urlObj.search
      if (path.length <= maxLength) return path
      return path.substring(0, maxLength - 3) + '...'
    } catch {
      return url.length > maxLength ? url.substring(0, maxLength - 3) + '...' : url
    }
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle>{t('Top Converting Pages')}</CardTitle>
      </CardHeader>
      <CardContent>
        {leadSources.length === 0 ? (
          <p className="text-gray-500 text-sm text-center py-4">
            {t('No data available yet')}
          </p>
        ) : (
          <div className="space-y-3">
            {leadSources.slice(0, 5).map((source, index) => (
              <div key={`${index}-${source.page_url || 'unknown'}`} className="flex items-center justify-between">
                <div className="flex items-center gap-2 min-w-0">
                  <span className="text-sm font-medium text-gray-400 w-5">
                    {index + 1}.
                  </span>
                  <a 
                    href={source.page_url} 
                    target="_blank" 
                    rel="noopener noreferrer"
                    className="text-sm text-gray-700 hover:text-primary-600 truncate flex items-center gap-1"
                    title={source.page_url}
                  >
                    {truncateUrl(source.page_url)}
                    <ExternalLink className="w-3 h-3 shrink-0" />
                  </a>
                </div>
                <span className="text-sm font-semibold text-gray-900 shrink-0">
                  {source.lead_count} {t('leads')}
                </span>
              </div>
            ))}
          </div>
        )}
      </CardContent>
    </Card>
  )
}

// Usage Card Component
function UsageCard({ usage }: { usage?: { messages?: number; conversations?: number } }) {
  return (
    <div className="bg-white rounded-xl shadow-card border border-gray-100 p-6">
      <h3 className="text-lg font-semibold text-gray-900 mb-4">{t('Monthly Usage')}</h3>
      
      <div className="space-y-4">
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div className="p-4 bg-gray-50 rounded-lg">
            <div className="text-sm text-gray-600 mb-1">{t('Messages')}</div>
            <div className="text-2xl font-bold text-gray-900">{formatNumber(usage?.messages ?? 0)}</div>
          </div>
          <div className="p-4 bg-gray-50 rounded-lg">
            <div className="text-sm text-gray-600 mb-1">{t('Conversations')}</div>
            <div className="text-2xl font-bold text-gray-900">{formatNumber(usage?.conversations ?? 0)}</div>
          </div>
        </div>
      </div>
    </div>
  )
}

// Lead Status Card Component
function LeadStatusCard({ statusData }: { statusData?: Record<string, number> }) {
  const statuses = [
    { key: 'new', label: t('New'), color: 'bg-blue-500' },
    { key: 'contacted', label: t('Contacted'), color: 'bg-yellow-500' },
    { key: 'qualified', label: t('Qualified'), color: 'bg-purple-500' },
    { key: 'converted', label: t('Converted'), color: 'bg-green-500' },
    { key: 'lost', label: t('Lost'), color: 'bg-gray-500' },
  ]
  
  const total = Object.values(statusData || {}).reduce((sum, val) => sum + val, 0)
  
  return (
    <div className="bg-white rounded-xl shadow-card border border-gray-100 p-6">
      <h3 className="text-lg font-semibold text-gray-900 mb-4">{t('Lead Distribution')}</h3>
      
      <div className="space-y-3">
        {statuses.map(status => {
          const count = statusData?.[status.key] ?? 0
          const percentage = total > 0 ? (count / total) * 100 : 0
          
          return (
            <div key={status.key}>
              <div className="flex justify-between text-sm mb-1">
                <span className="text-gray-600">{status.label}</span>
                <span className="font-medium">{count}</span>
              </div>
              <div className="w-full bg-gray-100 rounded-full h-2">
                <div 
                  className={`h-2 rounded-full ${status.color}`}
                  style={{ width: `${percentage}%` }}
                />
              </div>
            </div>
          )
        })}
      </div>
    </div>
  )
}

// Quick Stats Component
function QuickStats({ data }: { data?: any }) {
  return (
    <div className="bg-white rounded-xl shadow-card border border-gray-100 p-6">
      <h3 className="text-lg font-semibold text-gray-900 mb-4">{t('Quick Stats')}</h3>
      
      <div className="grid grid-cols-2 gap-4">
        <div className="p-4 bg-gray-50 rounded-lg text-center">
          <p className="text-2xl font-bold text-gray-900">
            {formatNumber(data?.leads?.today ?? 0)}
          </p>
          <p className="text-sm text-gray-500">{t('Leads Today')}</p>
        </div>
        
        <div className="p-4 bg-gray-50 rounded-lg text-center">
          <p className="text-2xl font-bold text-gray-900">
            {formatNumber(data?.conversations?.today ?? 0)}
          </p>
          <p className="text-sm text-gray-500">{t('Conversations Today')}</p>
        </div>
        
        <div className="p-4 bg-gray-50 rounded-lg text-center">
          <p className="text-2xl font-bold text-gray-900">
            {formatNumber(data?.leads?.this_week ?? 0)}
          </p>
          <p className="text-sm text-gray-500">{t('Leads This Week')}</p>
        </div>
        
        <div className="p-4 bg-gray-50 rounded-lg text-center">
          <p className="text-2xl font-bold text-gray-900">
            {formatNumber(data?.meetings?.this_month ?? 0)}
          </p>
          <p className="text-sm text-gray-500">{t('Meetings This Month')}</p>
        </div>
        
        <div className="p-4 bg-gray-50 rounded-lg text-center">
          <p className="text-2xl font-bold text-gray-900">
            {formatNumber(data?.leads?.total ?? 0)}
          </p>
          <p className="text-sm text-gray-500">{t('Total Leads')}</p>
        </div>
        
        <div className="p-4 bg-gray-50 rounded-lg text-center">
          <p className="text-2xl font-bold text-gray-900">
            {(data?.satisfaction?.average ?? 0).toFixed(1)}
          </p>
          <p className="text-sm text-gray-500">{t('Avg Satisfaction')}</p>
        </div>
      </div>
    </div>
  )
}






