import { useState } from "react";
import { trpc } from "@/lib/trpc";
import DashboardLayout from "@/components/DashboardLayout";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { format } from "date-fns";
import { fr } from "date-fns/locale";
import {
  Mail,
  CheckCircle2,
  XCircle,
  TrendingUp,
  Send,
  AlertCircle,
  Filter,
  RefreshCw,
  BarChart3,
} from "lucide-react";

const notificationTypeLabels: Record<string, string> = {
  remerciement: "Remerciement post-formation",
  notification_formateur_inscription: "Notification formateur (inscription)",
  notification_formateur_annulation: "Notification formateur (annulation)",
  alerte_capacite: "Alerte capacité atteinte",
  notification_liste_attente: "Notification liste d'attente",
};

const notificationTypeColors: Record<string, string> = {
  remerciement: "bg-blue-100 text-blue-800",
  notification_formateur_inscription: "bg-green-100 text-green-800",
  notification_formateur_annulation: "bg-orange-100 text-orange-800",
  alerte_capacite: "bg-red-100 text-red-800",
  notification_liste_attente: "bg-purple-100 text-purple-800",
};

export default function AdminNotifications() {
  const [filters, setFilters] = useState({
    type: "",
    statut: "",
    email: "",
    dateDebut: "",
    dateFin: "",
  });
  const [page, setPage] = useState(0);
  const limit = 20;

  const { data: historiqueData, isLoading: isLoadingHistorique, refetch, error: historiqueError } = trpc.notifications.historique.useQuery({
    type: filters.type as any || undefined,
    statut: filters.statut as any || undefined,
    email: filters.email || undefined,
    dateDebut: filters.dateDebut || undefined,
    dateFin: filters.dateFin || undefined,
    limit,
    offset: page * limit,
  });

  const { data: statsData, isLoading: isLoadingStats, error: statsError } = trpc.notifications.statistiques.useQuery({
    dateDebut: filters.dateDebut || undefined,
    dateFin: filters.dateFin || undefined,
  });

  const totalPages = Math.ceil((historiqueData?.total || 0) / limit);

  const handleFilterChange = (key: string, value: string) => {
    // Convertir 'all' en chaîne vide pour les filtres
    const actualValue = value === "all" ? "" : value;
    setFilters((prev) => ({ ...prev, [key]: actualValue }));
    setPage(0);
  };

  const resetFilters = () => {
    setFilters({
      type: "",
      statut: "",
      email: "",
      dateDebut: "",
      dateFin: "",
    });
    setPage(0);
  };

  return (
    <DashboardLayout>
      <div className="space-y-6">
        <div className="flex items-center justify-between">
          <div className="mb-8">
        <h1 className="page-title mb-2">Tableau de bord des Notifications</h1>
        <p className="text-muted-foreground">
          Historique et statistiques de tous les emails envoyés
        </p>
      </div>         <Button onClick={() => refetch()} variant="outline">
            <RefreshCw className="h-4 w-4 mr-2" />
            Actualiser
          </Button>
        </div>

        <Tabs defaultValue="historique">
          <TabsList>
            <TabsTrigger value="historique">
              <Mail className="h-4 w-4 mr-2" />
              Historique
            </TabsTrigger>
            <TabsTrigger value="statistiques">
              <BarChart3 className="h-4 w-4 mr-2" />
              Statistiques
            </TabsTrigger>
          </TabsList>

          <TabsContent value="statistiques" className="space-y-6">
            {isLoadingStats ? (
              <div className="text-center py-8 text-muted-foreground">Chargement...</div>
            ) : statsError ? (
              <div className="text-center py-8 text-red-500">
                <AlertCircle className="h-8 w-8 mx-auto mb-2" />
                <p>Erreur lors du chargement des statistiques</p>
                <p className="text-sm text-muted-foreground mt-1">{statsError.message}</p>
              </div>
            ) : statsData ? (
              <>
                {/* Cartes de statistiques globales */}
                <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
                  <Card>
                    <CardHeader className="pb-2">
                      <CardTitle className="text-sm font-medium text-muted-foreground">
                        Total envoyés
                      </CardTitle>
                    </CardHeader>
                    <CardContent>
                      <div className="flex items-center gap-2">
                        <Send className="h-5 w-5 text-blue-500" />
                        <span className="text-2xl font-bold">{statsData.global.total}</span>
                      </div>
                    </CardContent>
                  </Card>
                  <Card>
                    <CardHeader className="pb-2">
                      <CardTitle className="text-sm font-medium text-muted-foreground">
                        Réussis
                      </CardTitle>
                    </CardHeader>
                    <CardContent>
                      <div className="flex items-center gap-2">
                        <CheckCircle2 className="h-5 w-5 text-green-500" />
                        <span className="text-2xl font-bold">{statsData.global.success}</span>
                      </div>
                    </CardContent>
                  </Card>
                  <Card>
                    <CardHeader className="pb-2">
                      <CardTitle className="text-sm font-medium text-muted-foreground">
                        Échoués
                      </CardTitle>
                    </CardHeader>
                    <CardContent>
                      <div className="flex items-center gap-2">
                        <XCircle className="h-5 w-5 text-red-500" />
                        <span className="text-2xl font-bold">{statsData.global.failed}</span>
                      </div>
                    </CardContent>
                  </Card>
                  <Card>
                    <CardHeader className="pb-2">
                      <CardTitle className="text-sm font-medium text-muted-foreground">
                        Taux de succès
                      </CardTitle>
                    </CardHeader>
                    <CardContent>
                      <div className="flex items-center gap-2">
                        <TrendingUp className="h-5 w-5 text-blue-500" />
                        <span className="text-2xl font-bold">{statsData.global.tauxSucces}%</span>
                      </div>
                    </CardContent>
                  </Card>
                </div>

                {/* Statistiques par type */}
                <Card>
                  <CardHeader>
                    <CardTitle>Répartition par type de notification</CardTitle>
                    <CardDescription>
                      Nombre d'emails envoyés par catégorie
                    </CardDescription>
                  </CardHeader>
                  <CardContent>
                    <Table>
                      <TableHeader>
                        <TableRow>
                          <TableHead>Type</TableHead>
                          <TableHead className="text-right">Total</TableHead>
                          <TableHead className="text-right">Réussis</TableHead>
                          <TableHead className="text-right">Échoués</TableHead>
                          <TableHead className="text-right">Taux de succès</TableHead>
                        </TableRow>
                      </TableHeader>
                      <TableBody>
                        {statsData.parType.map((stat) => (
                          <TableRow key={stat.type}>
                            <TableCell>
                              <Badge className={notificationTypeColors[stat.type] || "bg-gray-100"}>
                                {notificationTypeLabels[stat.type] || stat.type}
                              </Badge>
                            </TableCell>
                            <TableCell className="text-right font-medium">{stat.total}</TableCell>
                            <TableCell className="text-right text-green-600">{stat.success}</TableCell>
                            <TableCell className="text-right text-red-600">{stat.failed}</TableCell>
                            <TableCell className="text-right">
                              {stat.total > 0 ? Math.round((stat.success / stat.total) * 100) : 0}%
                            </TableCell>
                          </TableRow>
                        ))}
                        {statsData.parType.length === 0 && (
                          <TableRow>
                            <TableCell colSpan={5} className="text-center text-muted-foreground">
                              Aucune donnée disponible
                            </TableCell>
                          </TableRow>
                        )}
                      </TableBody>
                    </Table>
                  </CardContent>
                </Card>

                {/* Évolution par jour */}
                <Card>
                  <CardHeader>
                    <CardTitle>Évolution des envois</CardTitle>
                    <CardDescription>
                      Nombre d'emails envoyés par jour
                    </CardDescription>
                  </CardHeader>
                  <CardContent>
                    <Table>
                      <TableHeader>
                        <TableRow>
                          <TableHead>Date</TableHead>
                          <TableHead className="text-right">Total</TableHead>
                          <TableHead className="text-right">Réussis</TableHead>
                          <TableHead className="text-right">Échoués</TableHead>
                        </TableRow>
                      </TableHeader>
                      <TableBody>
                        {statsData.evolutionParJour.map((jour) => (
                          <TableRow key={jour.date}>
                            <TableCell>
                              {format(new Date(jour.date), "EEEE d MMMM yyyy", { locale: fr })}
                            </TableCell>
                            <TableCell className="text-right font-medium">{jour.total}</TableCell>
                            <TableCell className="text-right text-green-600">{jour.success}</TableCell>
                            <TableCell className="text-right text-red-600">{jour.failed}</TableCell>
                          </TableRow>
                        ))}
                        {statsData.evolutionParJour.length === 0 && (
                          <TableRow>
                            <TableCell colSpan={4} className="text-center text-muted-foreground">
                              Aucune donnée disponible
                            </TableCell>
                          </TableRow>
                        )}
                      </TableBody>
                    </Table>
                  </CardContent>
                </Card>
              </>
            ) : (
              <div className="text-center py-8 text-muted-foreground">
                Aucune statistique disponible
              </div>
            )}
          </TabsContent>

          <TabsContent value="historique" className="space-y-6">
            {/* Filtres */}
            <Card>
              <CardHeader className="pb-3">
                <CardTitle className="text-base flex items-center gap-2">
                  <Filter className="h-4 w-4" />
                  Filtres
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="grid grid-cols-1 md:grid-cols-5 gap-4">
                  <div className="space-y-2">
                    <Label>Type</Label>
                    <Select
                      value={filters.type || "all"}
                      onValueChange={(value) => handleFilterChange("type", value)}
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="Tous les types" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="all">Tous les types</SelectItem>
                        <SelectItem value="remerciement">Remerciement</SelectItem>
                        <SelectItem value="notification_formateur_inscription">
                          Notif. formateur (inscription)
                        </SelectItem>
                        <SelectItem value="notification_formateur_annulation">
                          Notif. formateur (annulation)
                        </SelectItem>
                        <SelectItem value="alerte_capacite">Alerte capacité</SelectItem>
                        <SelectItem value="notification_liste_attente">
                          Liste d'attente
                        </SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                  <div className="space-y-2">
                    <Label>Statut</Label>
                    <Select
                      value={filters.statut || "all"}
                      onValueChange={(value) => handleFilterChange("statut", value)}
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="Tous les statuts" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="all">Tous les statuts</SelectItem>
                        <SelectItem value="success">Réussi</SelectItem>
                        <SelectItem value="failed">Échoué</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                  <div className="space-y-2">
                    <Label>Email</Label>
                    <Input
                      placeholder="Rechercher par email"
                      value={filters.email}
                      onChange={(e) => handleFilterChange("email", e.target.value)}
                    />
                  </div>
                  <div className="space-y-2">
                    <Label>Date début</Label>
                    <Input
                      type="date"
                      value={filters.dateDebut}
                      onChange={(e) => handleFilterChange("dateDebut", e.target.value)}
                    />
                  </div>
                  <div className="space-y-2">
                    <Label>Date fin</Label>
                    <Input
                      type="date"
                      value={filters.dateFin}
                      onChange={(e) => handleFilterChange("dateFin", e.target.value)}
                    />
                  </div>
                </div>
                <div className="mt-4 flex justify-end">
                  <Button variant="outline" onClick={resetFilters}>
                    Réinitialiser les filtres
                  </Button>
                </div>
              </CardContent>
            </Card>

            {/* Tableau historique */}
            <Card>
              <CardHeader>
                <CardTitle>Historique des envois</CardTitle>
                <CardDescription>
                  {historiqueData?.total || 0} notification(s) trouvée(s)
                </CardDescription>
              </CardHeader>
              <CardContent>
                {isLoadingHistorique ? (
                  <div className="text-center py-8 text-muted-foreground">Chargement...</div>
                ) : historiqueError ? (
                  <div className="text-center py-8 text-red-500">
                    <AlertCircle className="h-8 w-8 mx-auto mb-2" />
                    <p>Erreur lors du chargement de l'historique</p>
                    <p className="text-sm text-muted-foreground mt-1">{historiqueError.message}</p>
                  </div>
                ) : historiqueData?.logs.length === 0 ? (
                  <div className="text-center py-8 text-muted-foreground">
                    Aucune notification trouvée
                  </div>
                ) : (
                  <>
                    <Table>
                      <TableHeader>
                        <TableRow>
                          <TableHead>Date</TableHead>
                          <TableHead>Type</TableHead>
                          <TableHead>Destinataire</TableHead>
                          <TableHead>Sujet</TableHead>
                          <TableHead>Formation / Séquence</TableHead>
                          <TableHead>Statut</TableHead>
                        </TableRow>
                      </TableHeader>
                      <TableBody>
                        {historiqueData?.logs.map((log) => (
                          <TableRow key={log.id}>
                            <TableCell className="whitespace-nowrap">
                              {format(new Date(log.dateEnvoi), "dd/MM/yyyy HH:mm", { locale: fr })}
                            </TableCell>
                            <TableCell>
                              <Badge className={notificationTypeColors[log.type] || "bg-gray-100"}>
                                {notificationTypeLabels[log.type] || log.type}
                              </Badge>
                            </TableCell>
                            <TableCell>
                              <div className="flex flex-col">
                                <span className="font-medium">{log.emailDestinataire}</span>
                                {log.apprenantNom && log.apprenantPrenom && (
                                  <span className="text-sm text-muted-foreground">
                                    {log.apprenantPrenom} {log.apprenantNom}
                                  </span>
                                )}
                                {log.formateurNom && (
                                  <span className="text-sm text-muted-foreground">
                                    Formateur: {log.formateurNom}
                                  </span>
                                )}
                              </div>
                            </TableCell>
                            <TableCell className="max-w-xs truncate" title={log.sujet}>
                              {log.sujet}
                            </TableCell>
                            <TableCell>
                              {log.formationNom && log.sequenceNom ? (
                                <div className="flex flex-col">
                                  <span className="font-medium">{log.formationNom}</span>
                                  <span className="text-sm text-muted-foreground">
                                    {log.sequenceNom}
                                  </span>
                                </div>
                              ) : (
                                <span className="text-muted-foreground">-</span>
                              )}
                            </TableCell>
                            <TableCell>
                              {log.statut === "success" ? (
                                <Badge variant="default" className="bg-green-500">
                                  <CheckCircle2 className="h-3 w-3 mr-1" />
                                  Envoyé
                                </Badge>
                              ) : (
                                <div className="flex flex-col gap-1">
                                  <Badge variant="destructive">
                                    <XCircle className="h-3 w-3 mr-1" />
                                    Échec
                                  </Badge>
                                  {log.messageErreur && (
                                    <span className="text-xs text-red-600" title={log.messageErreur}>
                                      {log.messageErreur.substring(0, 50)}...
                                    </span>
                                  )}
                                </div>
                              )}
                            </TableCell>
                          </TableRow>
                        ))}
                      </TableBody>
                    </Table>

                    {/* Pagination */}
                    {totalPages > 1 && (
                      <div className="flex items-center justify-between mt-4">
                        <p className="text-sm text-muted-foreground">
                          Page {page + 1} sur {totalPages}
                        </p>
                        <div className="flex gap-2">
                          <Button
                            variant="outline"
                            size="sm"
                            onClick={() => setPage((p) => Math.max(0, p - 1))}
                            disabled={page === 0}
                          >
                            Précédent
                          </Button>
                          <Button
                            variant="outline"
                            size="sm"
                            onClick={() => setPage((p) => Math.min(totalPages - 1, p + 1))}
                            disabled={page >= totalPages - 1}
                          >
                            Suivant
                          </Button>
                        </div>
                      </div>
                    )}
                  </>
                )}
              </CardContent>
            </Card>
          </TabsContent>
        </Tabs>
      </div>
    </DashboardLayout>
  );
}
