import { t, isRtl } from '@/lib/i18n'
import { Card, CardHeader, CardTitle, CardContent } from '@/components/common/Card'
import { Calendar, Star } from 'lucide-react'
import type { FunnelStage, FunnelParallelMetric, FunnelSatisfaction } from '@/api/analytics'

function localizedLabel(item: { label?: string; label_he?: string }): string {
  return isRtl() ? (item.label_he || item.label || '') : (item.label || item.label_he || '')
}

interface FunnelChartProps {
  funnel: FunnelStage[]
  period: string
  meetings?: FunnelParallelMetric
  satisfaction?: FunnelSatisfaction
}

export function FunnelChart({ funnel, period, meetings, satisfaction }: FunnelChartProps) {
  if (!funnel || funnel.length === 0) {
    return (
      <Card>
        <CardHeader>
          <CardTitle>{t('Conversion Funnel')}</CardTitle>
        </CardHeader>
        <CardContent>
          <p className="text-gray-500 text-sm text-center py-4">
            {t('No data available')}
          </p>
        </CardContent>
      </Card>
    )
  }

  const maxCount = Math.max(...funnel.map(s => s.count), 1)

  // Calculate conversion rates between stages
  const stagesWithRates = funnel.map((stage, index) => {
    const prevCount = index > 0 ? funnel[index - 1].count : stage.count
    const conversionRate = prevCount > 0 ? ((stage.count / prevCount) * 100).toFixed(1) : '0'
    return { ...stage, conversionRate }
  })

  const periodLabel = period === '7days' ? t('7 days') : period === '30days' ? t('30 days') : t('90 days')

  // 4-stage funnel colors: Conversations → Leads → Qualified → Converted
  const colors = [
    'bg-primary-500',    // conversations
    'bg-primary-400',    // leads
    'bg-accent-500',     // qualified
    'bg-green-500',      // converted
  ]

  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center justify-between">
          <span>{t('Conversion Funnel')}</span>
          <span className="text-sm font-normal text-gray-500">{periodLabel}</span>
        </CardTitle>
      </CardHeader>
      <CardContent>
        <div className="space-y-4">
          {stagesWithRates.map((stage, index) => {
            const widthPercentage = (stage.count / maxCount) * 100
            const isFirst = index === 0
            const bgColor = colors[index] || 'bg-gray-500'

            return (
              <div key={stage.stage}>
                <div className="flex items-center justify-between mb-2">
                  <div className="flex items-center gap-3">
                    <span className="text-sm font-medium text-gray-700">
                      {localizedLabel(stage)}
                    </span>
                    {!isFirst && (
                      <span className="text-xs px-2 py-0.5 bg-gray-100 rounded-full text-gray-500">
                        {stage.conversionRate}%
                      </span>
                    )}
                  </div>
                  <span className="text-lg font-bold text-gray-900">
                    {stage.count.toLocaleString()}
                  </span>
                </div>
                <div className="w-full bg-gray-100 rounded-lg h-8 overflow-hidden">
                  <div 
                    className={`h-full ${bgColor} rounded-lg transition-all flex items-center justify-end px-3`}
                    style={{ width: `${Math.max(widthPercentage, 5)}%` }}
                  >
                    {widthPercentage > 20 && (
                      <span className="text-white text-xs font-medium">
                        {stage.count}
                      </span>
                    )}
                  </div>
                </div>
              </div>
            )
          })}
        </div>

        {/* Overall conversion rate */}
        <div className="mt-6 pt-4 border-t border-gray-100">
          <div className="flex items-center justify-between">
            <span className="text-sm text-gray-600">
              {t('Overall Conversion Rate')}
            </span>
            <span className="text-lg font-bold text-green-600">
              {funnel[0]?.count > 0 
                ? ((funnel[funnel.length - 1]?.count / funnel[0].count) * 100).toFixed(2)
                : 0}%
            </span>
          </div>
          <p className="text-xs text-gray-400 mt-1">
            {t('From conversations to converted')}
          </p>
        </div>

        {/* Parallel metrics: Meetings & Satisfaction */}
        {(meetings || satisfaction) && (
          <div className="mt-4 pt-4 border-t border-gray-100 grid grid-cols-2 gap-4">
            {meetings && (
              <div className="flex items-center gap-3 p-3 bg-yellow-50 rounded-lg">
                <Calendar className="w-5 h-5 text-yellow-600" />
                <div>
                  <p className="text-lg font-bold text-gray-900">{meetings.count.toLocaleString()}</p>
                  <p className="text-xs text-gray-500">{localizedLabel(meetings)}</p>
                </div>
              </div>
            )}
            {satisfaction && satisfaction.count > 0 && (
              <div className="flex items-center gap-3 p-3 bg-orange-50 rounded-lg">
                <Star className="w-5 h-5 text-orange-500" />
                <div>
                  <p className="text-lg font-bold text-gray-900">{satisfaction.average}/5</p>
                  <p className="text-xs text-gray-500">
                    {localizedLabel(satisfaction)} ({satisfaction.count})
                  </p>
                </div>
              </div>
            )}
          </div>
        )}
      </CardContent>
    </Card>
  )
}
