import {
  Activity,
  BarChart3,
  Calendar,
  DollarSign,
  Download,
  Package,
  TrendingUp,
  Users,
} from 'lucide-react';
import { useEffect, useState } from 'react';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Skeleton } from '@/components/ui/skeleton';
import { adminAdvancedApi } from '@/db/api';
import { useToast } from '@/hooks/use-toast';

interface DashboardStats {
  total_users: number;
  total_trips: number;
  total_places: number;
  total_leads: number;
  total_providers: number;
  active_providers: number;
  total_revenue: number;
  recent_activity_count: number;
  pending_leads: number;
  sold_leads: number;
}

export default function AdminAnalytics() {
  const [stats, setStats] = useState<DashboardStats | null>(null);
  const [loading, setLoading] = useState(true);
  const [period, setPeriod] = useState('daily');
  const { toast } = useToast();

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

  const loadStats = async () => {
    try {
      setLoading(true);
      const data = await adminAdvancedApi.getDashboardStats();
      setStats(data);
    } catch (error: any) {
      console.error('Error loading stats:', error);
      toast({
        title: 'Hata',
        description: 'İstatistikler yüklenirken bir hata oluştu',
        variant: 'destructive',
      });
    } finally {
      setLoading(false);
    }
  };

  const handleExport = () => {
    if (!stats) return;

    const csvContent = [
      ['Metrik', 'Değer'],
      ['Toplam Kullanıcı', stats.total_users],
      ['Toplam Gezi', stats.total_trips],
      ['Toplam Mekan', stats.total_places],
      ['Toplam Lead', stats.total_leads],
      ['Toplam Sağlayıcı', stats.total_providers],
      ['Aktif Sağlayıcı', stats.active_providers],
      ['Toplam Gelir', `${stats.total_revenue} TL`],
      ['Son 24 Saat Aktivite', stats.recent_activity_count],
      ['Bekleyen Lead', stats.pending_leads],
      ['Satılan Lead', stats.sold_leads],
    ]
      .map(row => row.join(','))
      .join('\n');

    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = `analytics_${new Date().toISOString().split('T')[0]}.csv`;
    link.click();

    toast({
      title: 'Başarılı',
      description: 'Analitik verileri başarıyla dışa aktarıldı',
    });
  };

  const statCards = [
    {
      title: 'Toplam Kullanıcı',
      value: stats?.total_users || 0,
      icon: Users,
      color: 'text-blue-600',
      bgColor: 'bg-blue-100 dark:bg-blue-950',
    },
    {
      title: 'Toplam Gezi',
      value: stats?.total_trips || 0,
      icon: Package,
      color: 'text-green-600',
      bgColor: 'bg-green-100 dark:bg-green-950',
    },
    {
      title: 'Toplam Mekan',
      value: stats?.total_places || 0,
      icon: Package,
      color: 'text-purple-600',
      bgColor: 'bg-purple-100 dark:bg-purple-950',
    },
    {
      title: 'Toplam Gelir',
      value: `${stats?.total_revenue || 0} TL`,
      icon: DollarSign,
      color: 'text-yellow-600',
      bgColor: 'bg-yellow-100 dark:bg-yellow-950',
    },
    {
      title: 'Aktif Sağlayıcı',
      value: `${stats?.active_providers || 0} / ${stats?.total_providers || 0}`,
      icon: Users,
      color: 'text-indigo-600',
      bgColor: 'bg-indigo-100 dark:bg-indigo-950',
    },
    {
      title: 'Lead Durumu',
      value: `${stats?.sold_leads || 0} / ${stats?.total_leads || 0}`,
      icon: TrendingUp,
      color: 'text-pink-600',
      bgColor: 'bg-pink-100 dark:bg-pink-950',
    },
    {
      title: 'Bekleyen Lead',
      value: stats?.pending_leads || 0,
      icon: Activity,
      color: 'text-orange-600',
      bgColor: 'bg-orange-100 dark:bg-orange-950',
    },
    {
      title: 'Son 24 Saat Aktivite',
      value: stats?.recent_activity_count || 0,
      icon: Activity,
      color: 'text-red-600',
      bgColor: 'bg-red-100 dark:bg-red-950',
    },
  ];

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold">Gelişmiş Analitik</h1>
          <p className="text-muted-foreground mt-2">
            Detaylı istatistikler ve raporlar
          </p>
        </div>
        <div className="flex gap-2">
          <Select value={period} onValueChange={setPeriod}>
            <SelectTrigger className="w-[180px]">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="daily">Günlük</SelectItem>
              <SelectItem value="weekly">Haftalık</SelectItem>
              <SelectItem value="monthly">Aylık</SelectItem>
              <SelectItem value="yearly">Yıllık</SelectItem>
            </SelectContent>
          </Select>
          <Button onClick={handleExport} variant="outline">
            <Download className="mr-2 h-4 w-4" />
            Dışa Aktar
          </Button>
        </div>
      </div>

      {loading ? (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
          {[...Array(8)].map((_, i) => (
            <Card key={i}>
              <CardContent className="p-6">
                <Skeleton className="h-20 w-full" />
              </CardContent>
            </Card>
          ))}
        </div>
      ) : (
        <>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
            {statCards.map((stat, index) => (
              <Card key={index}>
                <CardContent className="p-6">
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="text-sm font-medium text-muted-foreground">
                        {stat.title}
                      </p>
                      <p className="text-2xl font-bold mt-2">{stat.value}</p>
                    </div>
                    <div className={`p-3 rounded-full ${stat.bgColor}`}>
                      <stat.icon className={`h-6 w-6 ${stat.color}`} />
                    </div>
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>

          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <TrendingUp className="h-5 w-5" />
                  Gelir Analizi
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  <div className="flex items-center justify-between">
                    <span className="text-sm text-muted-foreground">Toplam Gelir</span>
                    <span className="font-semibold">{stats?.total_revenue || 0} TL</span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-sm text-muted-foreground">Satılan Lead</span>
                    <span className="font-semibold">{stats?.sold_leads || 0}</span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-sm text-muted-foreground">Ortalama Lead Fiyatı</span>
                    <span className="font-semibold">
                      {stats?.sold_leads && stats.sold_leads > 0
                        ? ((stats.total_revenue || 0) / stats.sold_leads).toFixed(2)
                        : 0}{' '}
                      TL
                    </span>
                  </div>
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Users className="h-5 w-5" />
                  Sağlayıcı Analizi
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  <div className="flex items-center justify-between">
                    <span className="text-sm text-muted-foreground">Toplam Sağlayıcı</span>
                    <span className="font-semibold">{stats?.total_providers || 0}</span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-sm text-muted-foreground">Aktif Sağlayıcı</span>
                    <span className="font-semibold">{stats?.active_providers || 0}</span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-sm text-muted-foreground">Aktivasyon Oranı</span>
                    <span className="font-semibold">
                      {stats?.total_providers && stats.total_providers > 0
                        ? ((stats.active_providers / stats.total_providers) * 100).toFixed(1)
                        : 0}
                      %
                    </span>
                  </div>
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Package className="h-5 w-5" />
                  İçerik Analizi
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  <div className="flex items-center justify-between">
                    <span className="text-sm text-muted-foreground">Toplam Gezi</span>
                    <span className="font-semibold">{stats?.total_trips || 0}</span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-sm text-muted-foreground">Toplam Mekan</span>
                    <span className="font-semibold">{stats?.total_places || 0}</span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-sm text-muted-foreground">Kullanıcı Başına Gezi</span>
                    <span className="font-semibold">
                      {stats?.total_users && stats.total_users > 0
                        ? (stats.total_trips / stats.total_users).toFixed(2)
                        : 0}
                    </span>
                  </div>
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Activity className="h-5 w-5" />
                  Aktivite Analizi
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  <div className="flex items-center justify-between">
                    <span className="text-sm text-muted-foreground">Son 24 Saat</span>
                    <Badge>{stats?.recent_activity_count || 0} aktivite</Badge>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-sm text-muted-foreground">Bekleyen Lead</span>
                    <Badge variant="secondary">{stats?.pending_leads || 0}</Badge>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-sm text-muted-foreground">Lead Dönüşüm Oranı</span>
                    <Badge variant="outline">
                      {stats?.total_leads && stats.total_leads > 0
                        ? ((stats.sold_leads / stats.total_leads) * 100).toFixed(1)
                        : 0}
                      %
                    </Badge>
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>
        </>
      )}
    </div>
  );
}
