import DashboardLayout from "@/components/DashboardLayout";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { trpc } from "@/lib/trpc";
import { GraduationCap, Calendar, Users, CheckCircle, PieChart as PieChartIcon, Building2, TrendingUp } from "lucide-react";
import { Skeleton } from "@/components/ui/skeleton";
import { PieChart, Pie, Cell, ResponsiveContainer, Legend, Tooltip } from "recharts";
import { useMemo } from "react";

export default function Admin() {
  const { data: formations, isLoading: loadingFormations } = trpc.formations.list.useQuery();
  const { data: sequences, isLoading: loadingSessions } = trpc.sequences.list.useQuery();
  const { data: apprenants, isLoading: loadingApprenants } = trpc.apprenants.list.useQuery();

  // Statistiques par fonction
  const statsFonction = useMemo(() => {
    if (!apprenants) return [];
    
    const directeurs = apprenants.filter(a => a.fonction === "directeur").length;
    const chefsService = apprenants.filter(a => a.fonction === "chef_service").length;
    const autres = apprenants.filter(a => a.fonction === "autre").length;

    return [
      { name: "Directeurs", value: directeurs, color: "#93c5fd" },
      { name: "Chefs de service", value: chefsService, color: "#6ee7b7" },
      { name: "Autres", value: autres, color: "#fcd34d" },
    ].filter(item => item.value > 0);
  }, [apprenants]);

  // Statistiques par établissement
  const statsEtablissement = useMemo(() => {
    if (!apprenants) return [];
    
    const etablissementCounts: Record<string, number> = {};
    apprenants.forEach(a => {
      const code = a.codeEtablissement || "Non renseigné";
      etablissementCounts[code] = (etablissementCounts[code] || 0) + 1;
    });

    const colors = ["#93c5fd", "#6ee7b7", "#fcd34d", "#fca5a5", "#c4b5fd", "#f9a8d4", "#67e8f9", "#bef264", "#fdba74", "#a5b4fc"];
    
    return Object.entries(etablissementCounts)
      .map(([name, value], index) => ({
        name,
        value,
        color: colors[index % colors.length],
      }))
      .sort((a, b) => b.value - a.value)
      .slice(0, 10); // Top 10 établissements
  }, [apprenants]);

  const stats = [
    {
      title: "Formations actives",
      value: formations?.filter(f => f.actif).length || 0,
      icon: GraduationCap,
      gradient: "from-blue-300 to-blue-400",
      borderColor: "border-l-blue-400",
      bgColor: "bg-blue-50/80",
      iconBg: "bg-gradient-to-br from-blue-300 to-blue-400",
      loading: loadingFormations,
    },
    {
      title: "Séquences ouvertes",
      value: sequences?.filter(s => s.statut === "ouverte").length || 0,
      icon: Calendar,
      gradient: "from-green-300 to-emerald-400",
      borderColor: "border-l-green-400",
      bgColor: "bg-green-50/80",
      iconBg: "bg-gradient-to-br from-green-300 to-emerald-400",
      loading: loadingSessions,
    },
    {
      title: "Apprenants inscrits",
      value: apprenants?.length || 0,
      icon: Users,
      gradient: "from-purple-300 to-purple-400",
      borderColor: "border-l-purple-400",
      bgColor: "bg-purple-50/80",
      iconBg: "bg-gradient-to-br from-purple-300 to-purple-400",
      loading: loadingApprenants,
    },
    {
      title: "Séquences terminées",
      value: sequences?.filter(s => s.statut === "terminee").length || 0,
      icon: CheckCircle,
      gradient: "from-orange-300 to-orange-400",
      borderColor: "border-l-orange-400",
      bgColor: "bg-orange-50/80",
      iconBg: "bg-gradient-to-br from-orange-300 to-orange-400",
      loading: loadingSessions,
    },
  ];

  return (
    <DashboardLayout>
      <div className="space-y-8 animate-in fade-in duration-500">
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-4xl font-bold tracking-tight bg-gradient-to-r from-blue-400 to-purple-400 bg-clip-text text-transparent">
              Tableau de bord
            </h1>
            <p className="text-muted-foreground mt-2 text-lg">
              Gestion des formations Manager Itinova
            </p>
          </div>
          <div className="flex items-center gap-2 text-sm text-muted-foreground">
            <TrendingUp className="w-4 h-4 text-green-500" />
            <span>Données en temps réel</span>
          </div>
        </div>

        {/* Cartes de statistiques avec animations */}
        <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-4">
          {stats.map((stat, index) => {
            const Icon = stat.icon;
            return (
              <Card 
                key={index}
                className={`
                  relative overflow-hidden border-l-4 ${stat.borderColor} ${stat.bgColor}
                  transition-all duration-300 hover:shadow-xl hover:scale-105 hover:-translate-y-1
                  animate-in slide-in-from-bottom-4
                `}
                style={{ animationDelay: `${index * 100}ms` }}
              >
                <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-3">
                  <CardTitle className="text-sm font-semibold text-gray-700">
                    {stat.title}
                  </CardTitle>
                  <div className={`p-3 rounded-xl ${stat.iconBg} shadow-lg transition-transform duration-300 hover:rotate-12`}>
                    <Icon className="w-6 h-6 text-white" />
                  </div>
                </CardHeader>
                <CardContent>
                  {stat.loading ? (
                    <Skeleton className="h-10 w-20" />
                  ) : (
                    <div className="space-y-1">
                      <div className={`text-3xl font-bold bg-gradient-to-r ${stat.gradient} bg-clip-text text-transparent`}>
                        {stat.value}
                      </div>
                      <div className="flex items-center gap-1 text-xs text-green-600 font-medium">
                        <TrendingUp className="w-3 h-3" />
                        <span>Actif</span>
                      </div>
                    </div>
                  )}
                </CardContent>
                {/* Effet de brillance au survol */}
                <div className="absolute inset-0 bg-gradient-to-r from-transparent via-white/10 to-transparent -translate-x-full group-hover:translate-x-full transition-transform duration-1000" />
              </Card>
            );
          })}
        </div>

        {/* Graphiques de répartition avec animations */}
        <div className="grid gap-6 md:grid-cols-2">
          {/* Graphique de répartition par fonction */}
          {statsFonction.length > 0 && (
            <Card className="border-2 border-blue-100 transition-all duration-300 hover:shadow-xl hover:border-blue-300 animate-in slide-in-from-left-4" style={{ animationDelay: "400ms" }}>
              <CardHeader className="bg-gradient-to-r from-blue-50 to-purple-50 border-b-2 border-blue-100">
                <CardTitle className="flex items-center gap-3 text-xl">
                  <div className="p-2 rounded-lg bg-gradient-to-br from-blue-500 to-purple-600 shadow-md">
                    <PieChartIcon className="w-6 h-6 text-white" />
                  </div>
                  <span className="bg-gradient-to-r from-blue-600 to-purple-600 bg-clip-text text-transparent font-bold">
                    Répartition des apprenants par fonction
                  </span>
                </CardTitle>
                <CardDescription className="text-base mt-2">
                  Distribution des {apprenants?.length || 0} apprenants selon leur fonction
                </CardDescription>
              </CardHeader>
              <CardContent className="pt-6">
                {loadingApprenants ? (
                  <div className="h-80 flex items-center justify-center">
                    <Skeleton className="h-64 w-64 rounded-full" />
                  </div>
                ) : (
                  <div className="h-80 transition-all duration-500 hover:scale-105">
                    <ResponsiveContainer width="100%" height="100%">
                      <PieChart>
                        <Pie
                          data={statsFonction}
                          cx="50%"
                          cy="50%"
                          labelLine={false}
                          label={({ name, percent }) => `${name}: ${(percent * 100).toFixed(0)}%`}
                          outerRadius={100}
                          fill="#8884d8"
                          dataKey="value"
                          animationBegin={0}
                          animationDuration={800}
                        >
                          {statsFonction.map((entry, index) => (
                            <Cell key={`cell-${index}`} fill={entry.color} />
                          ))}
                        </Pie>
                        <Tooltip />
                        <Legend />
                      </PieChart>
                    </ResponsiveContainer>
                  </div>
                )}
              </CardContent>
            </Card>
          )}

          {/* Graphique de répartition par établissement */}
          {statsEtablissement.length > 0 && (
            <Card className="border-2 border-green-100 transition-all duration-300 hover:shadow-xl hover:border-green-300 animate-in slide-in-from-right-4" style={{ animationDelay: "400ms" }}>
              <CardHeader className="bg-gradient-to-r from-green-50 to-emerald-50 border-b-2 border-green-100">
                <CardTitle className="flex items-center gap-3 text-xl">
                  <div className="p-2 rounded-lg bg-gradient-to-br from-green-500 to-emerald-600 shadow-md">
                    <Building2 className="w-6 h-6 text-white" />
                  </div>
                  <span className="bg-gradient-to-r from-green-600 to-emerald-600 bg-clip-text text-transparent font-bold">
                    Répartition des apprenants par établissement
                  </span>
                </CardTitle>
                <CardDescription className="text-base mt-2">
                  Top 10 des établissements avec le plus d'apprenants
                </CardDescription>
              </CardHeader>
              <CardContent className="pt-6">
                {loadingApprenants ? (
                  <div className="h-80 flex items-center justify-center">
                    <Skeleton className="h-64 w-64 rounded-full" />
                  </div>
                ) : (
                  <div className="h-80 transition-all duration-500 hover:scale-105">
                    <ResponsiveContainer width="100%" height="100%">
                      <PieChart>
                        <Pie
                          data={statsEtablissement}
                          cx="50%"
                          cy="50%"
                          labelLine={false}
                          label={({ name, percent }) => `${name}: ${(percent * 100).toFixed(0)}%`}
                          outerRadius={100}
                          fill="#8884d8"
                          dataKey="value"
                          animationBegin={0}
                          animationDuration={800}
                        >
                          {statsEtablissement.map((entry, index) => (
                            <Cell key={`cell-${index}`} fill={entry.color} />
                          ))}
                        </Pie>
                        <Tooltip />
                        <Legend />
                      </PieChart>
                    </ResponsiveContainer>
                  </div>
                )}
              </CardContent>
            </Card>
          )}
        </div>
      </div>
    </DashboardLayout>
  );
}
