import { useEffect, useState } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
import { supabase } from '@/db/supabase';
import { 
  getPersonaEmoji, 
  getPersonaLabel, 
  getSpendPotentialColor,
  getSpendPotentialLabel 
} from '@/utils/persona-engine';
import type { TouristPersonaType } from '@/types/lead';

interface PersonaStatistic {
  persona_type: TouristPersonaType;
  count: number;
  avg_confidence: number;
  avg_travelers: number;
}

export function PersonaStatistics() {
  const [stats, setStats] = useState<PersonaStatistic[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    loadStats();
  }, []);

  const loadStats = async () => {
    try {
      setLoading(true);
      const { data, error } = await supabase.rpc('get_persona_statistics');
      
      if (error) throw error;
      setStats(data || []);
    } catch (error) {
      console.error('Error loading persona statistics:', error);
    } finally {
      setLoading(false);
    }
  };

  if (loading) {
    return (
      <Card>
        <CardHeader>
          <CardTitle>Persona İstatistikleri</CardTitle>
          <CardDescription>Tespit edilen turist persona dağılımı</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="space-y-3">
            {[1, 2, 3].map((i) => (
              <Skeleton key={i} className="h-16 w-full bg-muted" />
            ))}
          </div>
        </CardContent>
      </Card>
    );
  }

  if (stats.length === 0) {
    return (
      <Card>
        <CardHeader>
          <CardTitle>Persona İstatistikleri</CardTitle>
          <CardDescription>Tespit edilen turist persona dağılımı</CardDescription>
        </CardHeader>
        <CardContent>
          <p className="text-sm text-muted-foreground text-center py-8">
            Henüz persona verisi bulunmuyor
          </p>
        </CardContent>
      </Card>
    );
  }

  const totalLeads = stats.reduce((sum, stat) => sum + stat.count, 0);

  return (
    <Card>
      <CardHeader>
        <CardTitle>Persona İstatistikleri</CardTitle>
        <CardDescription>
          Toplam {totalLeads} lead için tespit edilen persona dağılımı
        </CardDescription>
      </CardHeader>
      <CardContent>
        <div className="space-y-4">
          {stats.map((stat) => {
            const percentage = ((stat.count / totalLeads) * 100).toFixed(1);
            const emoji = getPersonaEmoji(stat.persona_type);
            const label = getPersonaLabel(stat.persona_type, 'tr');
            
            return (
              <div key={stat.persona_type} className="space-y-2">
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-2">
                    <span className="text-xl">{emoji}</span>
                    <span className="font-medium">{label}</span>
                  </div>
                  <div className="flex items-center gap-3 text-sm">
                    <span className="text-muted-foreground">
                      {stat.count} lead ({percentage}%)
                    </span>
                    <span className="text-muted-foreground">
                      {Math.round(stat.avg_confidence * 100)}% güven
                    </span>
                    <span className="text-muted-foreground">
                      {stat.avg_travelers} kişi
                    </span>
                  </div>
                </div>
                <div className="w-full bg-muted rounded-full h-2">
                  <div
                    className="bg-primary rounded-full h-2 transition-all"
                    style={{ width: `${percentage}%` }}
                  />
                </div>
              </div>
            );
          })}
        </div>
      </CardContent>
    </Card>
  );
}
