import { Activity, CheckCircle2, DollarSign, FileText, Image as ImageIcon, MapPin, Package, Plane, Sparkles, TrendingUp, Users, Wallet } from 'lucide-react';
import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { PersonaStatistics } from '@/components/admin/PersonaStatistics';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { adminAdvancedApi, adminAnalyticsApi } from '@/db/api';
import { supabase } from '@/db/supabase';

interface Stats {
  totalUsers: number;
  totalTrips: number;
  totalPlaces: number;
  publicTrips: number;
}

interface LeadAnalytics {
  total_leads: number;
  total_leads_sold: number;
  total_revenue: number;
  total_providers: number;
  active_providers: number;
  top_destinations: Array<{
    destination: string;
    country: string;
    lead_count: number;
    total_revenue: number;
  }>;
  top_providers: Array<{
    id: string;
    company_name: string;
    email: string;
    purchased_leads: number;
    total_spend: number;
  }>;
}

export default function AdminDashboard() {
  const [stats, setStats] = useState<Stats>({
    totalUsers: 0,
    totalTrips: 0,
    totalPlaces: 0,
    publicTrips: 0,
  });
  const [leadAnalytics, setLeadAnalytics] = useState<LeadAnalytics | null>(null);
  const [advancedStats, setAdvancedStats] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [analyticsLoading, setAnalyticsLoading] = useState(true);

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

  const loadStats = async () => {
    try {
      const [usersResult, tripsResult, placesResult, publicTripsResult] = await Promise.all([
        supabase.from('profiles').select('id', { count: 'exact', head: true }),
        supabase.from('trips').select('id', { count: 'exact', head: true }),
        supabase.from('places').select('id', { count: 'exact', head: true }),
        supabase.from('trips').select('id', { count: 'exact', head: true }).eq('is_public', true),
      ]);

      setStats({
        totalUsers: usersResult.count || 0,
        totalTrips: tripsResult.count || 0,
        totalPlaces: placesResult.count || 0,
        publicTrips: publicTripsResult.count || 0,
      });
    } catch (error) {
      console.error('Error loading stats:', error);
    } finally {
      setLoading(false);
    }
  };

  const loadLeadAnalytics = async () => {
    try {
      setAnalyticsLoading(true);
      const data = await adminAnalyticsApi.getOverview();
      setLeadAnalytics(data);
    } catch (error) {
      console.error('Error loading lead analytics:', error);
    } finally {
      setAnalyticsLoading(false);
    }
  };

  const loadAdvancedStats = async () => {
    try {
      const data = await adminAdvancedApi.getDashboardStats();
      setAdvancedStats(data);
    } catch (error) {
      console.error('Error loading advanced stats:', error);
    }
  };

  const statCards = [
    {
      title: 'Total Users',
      value: stats.totalUsers,
      icon: Users,
      color: 'text-blue-600',
      bgColor: 'bg-blue-50',
    },
    {
      title: 'Total Trips',
      value: stats.totalTrips,
      icon: Plane,
      color: 'text-green-600',
      bgColor: 'bg-green-50',
    },
    {
      title: 'Total Places',
      value: stats.totalPlaces,
      icon: MapPin,
      color: 'text-orange-600',
      bgColor: 'bg-orange-50',
    },
    {
      title: 'Public Trips',
      value: stats.publicTrips,
      icon: TrendingUp,
      color: 'text-purple-600',
      bgColor: 'bg-purple-50',
    },
  ];

  const leadStatCards = leadAnalytics ? [
    {
      title: 'Total Leads',
      value: leadAnalytics.total_leads,
      icon: Package,
      color: 'text-indigo-600',
      bgColor: 'bg-indigo-50',
    },
    {
      title: 'Leads Sold',
      value: leadAnalytics.total_leads_sold,
      icon: CheckCircle2,
      color: 'text-green-600',
      bgColor: 'bg-green-50',
      subtitle: leadAnalytics.total_leads > 0 
        ? `${((leadAnalytics.total_leads_sold / leadAnalytics.total_leads) * 100).toFixed(1)}% conversion`
        : '0% conversion',
    },
    {
      title: 'Total Revenue',
      value: `${leadAnalytics.total_revenue} Credits`,
      icon: DollarSign,
      color: 'text-emerald-600',
      bgColor: 'bg-emerald-50',
    },
    {
      title: 'Active Providers',
      value: `${leadAnalytics.active_providers}/${leadAnalytics.total_providers}`,
      icon: Wallet,
      color: 'text-amber-600',
      bgColor: 'bg-amber-50',
    },
  ] : [];

  const quickActions = [
    {
      title: 'AI Arama',
      description: 'Akıllı arama ile bilgi edinin',
      icon: Sparkles,
      link: '/admin/ai-search',
      color: 'text-purple-600',
      bgColor: 'bg-purple-100 dark:bg-purple-950',
    },
    {
      title: 'Görsel Yönetimi',
      description: 'Görselleri yönetin veya oluşturun',
      icon: ImageIcon,
      link: '/admin/images',
      color: 'text-blue-600',
      bgColor: 'bg-blue-100 dark:bg-blue-950',
    },
    {
      title: 'Gelişmiş Analitik',
      description: 'Detaylı raporlar ve istatistikler',
      icon: TrendingUp,
      link: '/admin/analytics',
      color: 'text-green-600',
      bgColor: 'bg-green-100 dark:bg-green-950',
    },
    {
      title: 'Sistem Logları',
      description: 'Aktiviteleri ve olayları görüntüleyin',
      icon: FileText,
      link: '/admin/logs',
      color: 'text-orange-600',
      bgColor: 'bg-orange-100 dark:bg-orange-950',
    },
  ];

  return (
    <div className="space-y-8">
      <div>
        <h1 className="text-3xl font-bold">Admin Dashboard</h1>
        <p className="text-muted-foreground mt-1">
          Overview of platform statistics and analytics
        </p>
      </div>

      {/* Quick Actions */}
      <div>
        <h2 className="text-xl font-semibold mb-4">Hızlı Erişim</h2>
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
          {quickActions.map((action, index) => (
            <Link key={index} to={action.link}>
              <Card className="hover:shadow-lg transition-shadow cursor-pointer">
                <CardContent className="p-6">
                  <div className="flex items-start gap-4">
                    <div className={`p-3 rounded-lg ${action.bgColor}`}>
                      <action.icon className={`h-6 w-6 ${action.color}`} />
                    </div>
                    <div>
                      <h3 className="font-semibold">{action.title}</h3>
                      <p className="text-sm text-muted-foreground mt-1">
                        {action.description}
                      </p>
                    </div>
                  </div>
                </CardContent>
              </Card>
            </Link>
          ))}
        </div>
      </div>

      {/* Advanced Stats */}
      {advancedStats && (
        <div>
          <h2 className="text-xl font-semibold mb-4">Sistem Durumu</h2>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
            <Card>
              <CardContent className="p-6">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm text-muted-foreground">Son 24 Saat Aktivite</p>
                    <p className="text-2xl font-bold mt-2">{advancedStats.recent_activity_count}</p>
                  </div>
                  <div className="p-3 rounded-lg bg-red-100 dark:bg-red-950">
                    <Activity className="h-6 w-6 text-red-600" />
                  </div>
                </div>
              </CardContent>
            </Card>
            <Card>
              <CardContent className="p-6">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm text-muted-foreground">Bekleyen Lead</p>
                    <p className="text-2xl font-bold mt-2">{advancedStats.pending_leads}</p>
                  </div>
                  <div className="p-3 rounded-lg bg-yellow-100 dark:bg-yellow-950">
                    <Package className="h-6 w-6 text-yellow-600" />
                  </div>
                </div>
              </CardContent>
            </Card>
            <Card>
              <CardContent className="p-6">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm text-muted-foreground">Satılan Lead</p>
                    <p className="text-2xl font-bold mt-2">{advancedStats.sold_leads}</p>
                  </div>
                  <div className="p-3 rounded-lg bg-green-100 dark:bg-green-950">
                    <CheckCircle2 className="h-6 w-6 text-green-600" />
                  </div>
                </div>
              </CardContent>
            </Card>
            <Card>
              <CardContent className="p-6">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm text-muted-foreground">Toplam Gelir</p>
                    <p className="text-2xl font-bold mt-2">{advancedStats.total_revenue} TL</p>
                  </div>
                  <div className="p-3 rounded-lg bg-emerald-100 dark:bg-emerald-950">
                    <DollarSign className="h-6 w-6 text-emerald-600" />
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>
        </div>
      )}

      {/* Platform Stats */}
      <div>
        <h2 className="text-xl font-semibold mb-4">Platform Statistics</h2>
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
          {loading ? (
            Array.from({ length: 4 }).map((_, i) => (
              <Card key={i}>
                <CardHeader className="flex flex-row items-center justify-between pb-2">
                  <Skeleton className="h-4 w-24 bg-muted" />
                  <Skeleton className="h-4 w-4 rounded bg-muted" />
                </CardHeader>
                <CardContent>
                  <Skeleton className="h-8 w-16 bg-muted" />
                </CardContent>
              </Card>
            ))
          ) : (
            statCards.map((card, index) => (
              <Card key={index}>
                <CardHeader className="flex flex-row items-center justify-between pb-2">
                  <CardTitle className="text-sm font-medium">{card.title}</CardTitle>
                  <div className={`p-2 rounded-lg ${card.bgColor}`}>
                    <card.icon className={`h-4 w-4 ${card.color}`} />
                  </div>
                </CardHeader>
                <CardContent>
                  <div className="text-2xl font-bold">{card.value}</div>
                </CardContent>
              </Card>
            ))
          )}
        </div>
      </div>

      {/* Lead Analytics */}
      <div>
        <h2 className="text-xl font-semibold mb-4">Lead & Provider Analytics</h2>
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
          {analyticsLoading ? (
            Array.from({ length: 4 }).map((_, i) => (
              <Card key={i}>
                <CardHeader className="flex flex-row items-center justify-between pb-2">
                  <Skeleton className="h-4 w-24 bg-muted" />
                  <Skeleton className="h-4 w-4 rounded bg-muted" />
                </CardHeader>
                <CardContent>
                  <Skeleton className="h-8 w-16 bg-muted" />
                </CardContent>
              </Card>
            ))
          ) : (
            leadStatCards.map((card, index) => (
              <Card key={index}>
                <CardHeader className="flex flex-row items-center justify-between pb-2">
                  <CardTitle className="text-sm font-medium">{card.title}</CardTitle>
                  <div className={`p-2 rounded-lg ${card.bgColor}`}>
                    <card.icon className={`h-4 w-4 ${card.color}`} />
                  </div>
                </CardHeader>
                <CardContent>
                  <div className="text-2xl font-bold">{card.value}</div>
                  {card.subtitle && (
                    <p className="text-xs text-muted-foreground mt-1">{card.subtitle}</p>
                  )}
                </CardContent>
              </Card>
            ))
          )}
        </div>
      </div>

      {/* Top Destinations */}
      {leadAnalytics && leadAnalytics.top_destinations && leadAnalytics.top_destinations.length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle>Top Destinations by Lead Count</CardTitle>
          </CardHeader>
          <CardContent>
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Rank</TableHead>
                  <TableHead>Destination</TableHead>
                  <TableHead>Country</TableHead>
                  <TableHead>Lead Count</TableHead>
                  <TableHead>Total Revenue</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {leadAnalytics.top_destinations.map((dest, index) => (
                  <TableRow key={index}>
                    <TableCell>
                      <Badge variant="outline" className="font-semibold">
                        #{index + 1}
                      </Badge>
                    </TableCell>
                    <TableCell className="font-medium">{dest.destination}</TableCell>
                    <TableCell>{dest.country}</TableCell>
                    <TableCell>
                      <div className="flex items-center gap-2">
                        <Package className="h-4 w-4 text-muted-foreground" />
                        <span className="font-semibold">{dest.lead_count}</span>
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="flex items-center gap-2">
                        <DollarSign className="h-4 w-4 text-muted-foreground" />
                        <span className="font-semibold">{dest.total_revenue} Credits</span>
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </CardContent>
        </Card>
      )}

      {/* Top Providers */}
      {leadAnalytics && leadAnalytics.top_providers && leadAnalytics.top_providers.length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle>Top Providers by Spend</CardTitle>
          </CardHeader>
          <CardContent>
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Rank</TableHead>
                  <TableHead>Provider</TableHead>
                  <TableHead>Company</TableHead>
                  <TableHead>Purchased Leads</TableHead>
                  <TableHead>Total Spend</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {leadAnalytics.top_providers.map((provider, index) => (
                  <TableRow key={provider.id}>
                    <TableCell>
                      <Badge variant="outline" className="font-semibold">
                        #{index + 1}
                      </Badge>
                    </TableCell>
                    <TableCell className="font-medium">{provider.email}</TableCell>
                    <TableCell>{provider.company_name || 'N/A'}</TableCell>
                    <TableCell>
                      <div className="flex items-center gap-2">
                        <Package className="h-4 w-4 text-muted-foreground" />
                        <span className="font-semibold">{provider.purchased_leads}</span>
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="flex items-center gap-2">
                        <DollarSign className="h-4 w-4 text-muted-foreground" />
                        <span className="font-semibold">{provider.total_spend} Credits</span>
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </CardContent>
        </Card>
      )}

      {/* Persona Statistics */}
      <PersonaStatistics />
    </div>
  );
}
