import { useQuery } from '@tanstack/react-query';
import { supabase } from '@/db/supabase';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { TOURIST_PERSONAS } from '@/types/persona';
import { Skeleton } from '@/components/ui/skeleton';
import type { TouristPersonaType } from '@/types/lead';

interface PersonaStats {
  type: string;
  count: number;
  avg_confidence: number;
  total_spend_potential: number;
  label: string;
  emoji: string;
}

export default function PersonaAnalytics() {
  const { data: stats, isLoading } = useQuery({
    queryKey: ['persona-analytics'],
    queryFn: async () => {
      const { data, error } = await supabase
        .from('leads')
        .select('tourist_persona, persona_confidence')
        .not('tourist_persona', 'is', null);

      if (error) throw error;

      // Aggregate stats by persona type
      const statsMap = new Map<string, PersonaStats>();

      data.forEach((lead: { tourist_persona: any; persona_confidence: number }) => {
        const persona = lead.tourist_persona;
        const type = persona.type;

        if (!statsMap.has(type)) {
          statsMap.set(type, {
            type,
            count: 0,
            avg_confidence: 0,
            total_spend_potential: 0,
            label: '',
            emoji: ''
          });
        }

        const stat = statsMap.get(type)!;
        stat.count++;
        stat.avg_confidence += lead.persona_confidence || 0;

        // Calculate spend potential score
        const spendScore = {
          'low': 1,
          'medium': 2,
          'high': 3,
          'very_high': 4
        }[persona.spend_potential] || 0;
        stat.total_spend_potential += spendScore;
      });

      // Calculate averages and add labels
      statsMap.forEach((stat) => {
        stat.avg_confidence = stat.avg_confidence / stat.count;
        const personaInfo = TOURIST_PERSONAS[stat.type as TouristPersonaType];
        if (personaInfo) {
          stat.label = personaInfo.label;
          stat.emoji = personaInfo.emoji;
        }
      });

      return Array.from(statsMap.values()).sort((a, b) => b.count - a.count);
    }
  });

  if (isLoading) {
    return (
      <div className="container mx-auto p-6 space-y-6">
        <div>
          <h1 className="text-3xl font-bold">Persona Analytics</h1>
          <p className="text-muted-foreground mt-2">
            Lead persona dağılımı ve analitik verileri
          </p>
        </div>
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {[1, 2, 3, 4, 5, 6].map((i) => (
            <Card key={i}>
              <CardHeader>
                <Skeleton className="h-6 w-32" />
              </CardHeader>
              <CardContent>
                <Skeleton className="h-20 w-full" />
              </CardContent>
            </Card>
          ))}
        </div>
      </div>
    );
  }

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

  return (
    <div className="container mx-auto p-6 space-y-6">
      <div>
        <h1 className="text-3xl font-bold">Persona Analytics</h1>
        <p className="text-muted-foreground mt-2">
          Lead persona dağılımı ve analitik verileri
        </p>
      </div>

      {/* Özet Kartlar */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <Card>
          <CardHeader className="pb-3">
            <CardDescription>Toplam Lead</CardDescription>
            <CardTitle className="text-3xl">{totalLeads}</CardTitle>
          </CardHeader>
        </Card>
        <Card>
          <CardHeader className="pb-3">
            <CardDescription>Persona Tipi</CardDescription>
            <CardTitle className="text-3xl">{stats?.length || 0}</CardTitle>
          </CardHeader>
        </Card>
        <Card>
          <CardHeader className="pb-3">
            <CardDescription>Ortalama Güven</CardDescription>
            <CardTitle className="text-3xl">
              {stats && stats.length > 0
                ? Math.round(
                    (stats.reduce((sum, s) => sum + s.avg_confidence, 0) / stats.length) * 100
                  )
                : 0}%
            </CardTitle>
          </CardHeader>
        </Card>
        <Card>
          <CardHeader className="pb-3">
            <CardDescription>Yüksek Değerli Lead</CardDescription>
            <CardTitle className="text-3xl">
              {stats?.filter(s => 
                TOURIST_PERSONAS[s.type as TouristPersonaType]?.spend_potential === 'high' ||
                TOURIST_PERSONAS[s.type as TouristPersonaType]?.spend_potential === 'very_high'
              ).reduce((sum, s) => sum + s.count, 0) || 0}
            </CardTitle>
          </CardHeader>
        </Card>
      </div>

      {/* Persona Dağılımı */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        {stats?.map((stat) => {
          const personaInfo = TOURIST_PERSONAS[stat.type as TouristPersonaType];
          const percentage = totalLeads > 0 ? (stat.count / totalLeads) * 100 : 0;
          
          return (
            <Card key={stat.type}>
              <CardHeader>
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-2">
                    <span className="text-3xl">{stat.emoji}</span>
                    <div>
                      <CardTitle className="text-lg">{stat.label}</CardTitle>
                      <CardDescription className="text-xs">
                        {personaInfo?.description}
                      </CardDescription>
                    </div>
                  </div>
                </div>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="space-y-2">
                  <div className="flex justify-between text-sm">
                    <span className="text-muted-foreground">Lead Sayısı</span>
                    <span className="font-medium">{stat.count}</span>
                  </div>
                  <div className="flex justify-between text-sm">
                    <span className="text-muted-foreground">Oran</span>
                    <span className="font-medium">{percentage.toFixed(1)}%</span>
                  </div>
                  <div className="flex justify-between text-sm">
                    <span className="text-muted-foreground">Ortalama Güven</span>
                    <span className="font-medium">
                      {Math.round(stat.avg_confidence * 100)}%
                    </span>
                  </div>
                  <div className="flex justify-between text-sm">
                    <span className="text-muted-foreground">Harcama Potansiyeli</span>
                    <span className="font-medium capitalize">
                      {personaInfo?.spend_potential === 'very_high' && '⭐⭐⭐⭐'}
                      {personaInfo?.spend_potential === 'high' && '⭐⭐⭐'}
                      {personaInfo?.spend_potential === 'medium' && '⭐⭐'}
                      {personaInfo?.spend_potential === 'low' && '⭐'}
                    </span>
                  </div>
                </div>

                {/* Progress Bar */}
                <div className="w-full bg-muted rounded-full h-2">
                  <div
                    className="bg-primary h-2 rounded-full transition-all"
                    style={{ width: `${percentage}%` }}
                  />
                </div>

                {/* Önerilen Hizmetler */}
                {personaInfo && (
                  <div>
                    <p className="text-xs font-medium mb-2">Önerilen Hizmetler:</p>
                    <div className="flex flex-wrap gap-1">
                      {personaInfo.recommended_services.slice(0, 2).map((service, idx) => (
                        <span
                          key={idx}
                          className="text-xs bg-muted px-2 py-1 rounded"
                        >
                          {service}
                        </span>
                      ))}
                      {personaInfo.recommended_services.length > 2 && (
                        <span className="text-xs text-muted-foreground px-2 py-1">
                          +{personaInfo.recommended_services.length - 2} daha
                        </span>
                      )}
                    </div>
                  </div>
                )}
              </CardContent>
            </Card>
          );
        })}
      </div>

      {/* Boş Durum */}
      {(!stats || stats.length === 0) && (
        <Card>
          <CardContent className="flex flex-col items-center justify-center py-12">
            <p className="text-muted-foreground text-center">
              Henüz persona verisi bulunmuyor.
              <br />
              Lead'ler oluşturuldukça persona analizleri burada görünecektir.
            </p>
          </CardContent>
        </Card>
      )}
    </div>
  );
}
