import { trpc } from "@/lib/trpc";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Progress } from "@/components/ui/progress";
import { Calendar, Users, GraduationCap, Clock, MapPin, AlertCircle, TrendingUp } from "lucide-react";
import { format } from "date-fns";
import { fr } from "date-fns/locale";
import { Skeleton } from "@/components/ui/skeleton";
import DashboardLayout from "@/components/DashboardLayout";

export default function FormateurDashboard() {
  const { data: stats, isLoading: statsLoading } = trpc.formateurs.dashboardStats.useQuery();
  const { data: prochainesSequences, isLoading: sequencesLoading } = trpc.formateurs.prochainesSequences.useQuery({ limit: 10 });

  const statsCards = [
    {
      title: "Total séquences",
      value: stats?.totalSequences || 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",
      description: "Toutes vos séquences",
      loading: statsLoading,
    },
    {
      title: "Séquences à venir",
      value: stats?.sequencesAvenir || 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",
      description: "Avec dates futures",
      loading: statsLoading,
    },
    {
      title: "Total apprenants",
      value: stats?.totalInscrits || 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",
      description: "Inscrits confirmés",
      loading: statsLoading,
    },
  ];

  return (
    <DashboardLayout>
      <div className="space-y-8 animate-in fade-in duration-500">
        {/* En-tête */}
        <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 formateur
            </h1>
            <p className="text-muted-foreground mt-2 text-lg">
              Vue d'ensemble de vos formations et prochaines interventions
            </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-3">
          {statsCards.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>{stat.description}</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>

        {/* Liste des prochaines séquences avec design amélioré */}
        <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: "300ms" }}>
          <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">
                <Calendar 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">
                Prochaines séquences
              </span>
            </CardTitle>
            <CardDescription className="text-base mt-2">
              Vos interventions à venir triées par date
            </CardDescription>
          </CardHeader>
          <CardContent className="pt-6">
            {sequencesLoading ? (
              <div className="space-y-4">
                {[1, 2, 3].map((i) => (
                  <Skeleton key={i} className="h-32" />
                ))}
              </div>
            ) : prochainesSequences && prochainesSequences.length > 0 ? (
              <div className="space-y-4">
                {prochainesSequences.map((seq: any, index: number) => {
                  const pourcentageRemplissage = seq.capaciteMax > 0 
                    ? Math.round((seq.nbInscrits / seq.capaciteMax) * 100)
                    : 0;
                  const estComplete = pourcentageRemplissage >= 100;
                  const estPresqueComplete = pourcentageRemplissage >= 80 && pourcentageRemplissage < 100;

                  return (
                    <Card 
                      key={seq.id} 
                      className="overflow-hidden border-2 transition-all duration-300 hover:shadow-lg hover:border-blue-300 hover:scale-[1.02] animate-in slide-in-from-right-4"
                      style={{ animationDelay: `${index * 50}ms` }}
                    >
                      <CardHeader className="pb-3 bg-gradient-to-r from-gray-50 to-blue-50/30">
                        <div className="flex items-start justify-between">
                          <div className="space-y-1">
                            <CardTitle className="text-lg font-bold text-gray-900">{seq.nom}</CardTitle>
                            <CardDescription className="flex items-center gap-2 text-base">
                              <GraduationCap className="h-4 w-4" />
                              {seq.formation?.nom || "Formation inconnue"}
                            </CardDescription>
                          </div>
                          <Badge 
                            variant={seq.statut === 'ouverte' ? 'default' : seq.statut === 'bloquee' ? 'secondary' : 'outline'}
                            className="text-sm px-3 py-1"
                          >
                            {seq.statut === 'ouverte' ? 'Ouverte' : seq.statut === 'bloquee' ? 'Bloquée' : 'Terminée'}
                          </Badge>
                        </div>
                      </CardHeader>
                      <CardContent className="space-y-4 pt-4">
                        {/* Lieu */}
                        <div className="flex items-center gap-2 text-sm text-muted-foreground bg-gray-50 p-3 rounded-lg border border-gray-200">
                          <MapPin className="h-5 w-5 text-blue-500" />
                          <span className="font-medium">{seq.lieu}</span>
                        </div>

                        {/* Dates */}
                        <div className="space-y-2">
                          <div className="flex items-center gap-2 text-sm font-semibold text-gray-700">
                            <Clock className="h-5 w-5 text-purple-500" />
                            <span>Dates de formation</span>
                          </div>
                          <div className="flex flex-wrap gap-2 ml-7">
                            {seq.dates.map((date: any) => {
                              const dateDebut = new Date(date.dateDebut);
                              const dateFin = new Date(date.dateFin);
                              const estFuture = dateDebut >= new Date();
                              
                              return (
                                <Badge 
                                  key={date.id} 
                                  variant={estFuture ? "default" : "outline"}
                                  className="text-sm px-3 py-1 transition-all duration-200 hover:scale-110"
                                >
                                  {format(dateDebut, "dd MMM", { locale: fr })}
                                  {dateDebut.toDateString() !== dateFin.toDateString() && 
                                    ` - ${format(dateFin, "dd MMM", { locale: fr })}`
                                  }
                                </Badge>
                              );
                            })}
                          </div>
                        </div>

                        {/* Capacité */}
                        <div className="space-y-2 bg-gray-50 p-4 rounded-lg border border-gray-200">
                          <div className="flex items-center justify-between text-sm">
                            <div className="flex items-center gap-2 font-semibold text-gray-700">
                              <Users className="h-5 w-5 text-green-500" />
                              <span>Inscriptions</span>
                            </div>
                            <span className="text-lg font-bold text-gray-900">
                              {seq.nbInscrits} / {seq.capaciteMax}
                            </span>
                          </div>
                          <div className="space-y-1">
                            <Progress 
                              value={pourcentageRemplissage} 
                              className="h-3 transition-all duration-500"
                            />
                            {estComplete && (
                              <div className="flex items-center gap-1 text-xs text-orange-600 font-medium bg-orange-50 p-2 rounded border border-orange-200">
                                <AlertCircle className="h-4 w-4" />
                                <span>Capacité maximale atteinte</span>
                              </div>
                            )}
                            {estPresqueComplete && (
                              <div className="flex items-center gap-1 text-xs text-yellow-600 font-medium bg-yellow-50 p-2 rounded border border-yellow-200">
                                <AlertCircle className="h-4 w-4" />
                                <span>Presque complète ({pourcentageRemplissage}%)</span>
                              </div>
                            )}
                          </div>
                        </div>
                      </CardContent>
                    </Card>
                  );
                })}
              </div>
            ) : (
              <div className="text-center py-16 text-muted-foreground">
                <div className="bg-gray-100 rounded-full w-24 h-24 flex items-center justify-center mx-auto mb-4">
                  <Calendar className="h-12 w-12 text-gray-400" />
                </div>
                <p className="text-lg font-medium">Aucune séquence à venir pour le moment</p>
                <p className="text-sm mt-2">Vos prochaines interventions apparaîtront ici</p>
              </div>
            )}
          </CardContent>
        </Card>
      </div>
    </DashboardLayout>
  );
}
