import { useState } from "react";
import DashboardLayout from "@/components/DashboardLayout";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { trpc } from "@/lib/trpc";
import { History, Search, Filter, ChevronLeft, ChevronRight, Trash2 } from "lucide-react";
import { toast } from "sonner";
import { format } from "date-fns";
import { fr } from "date-fns/locale";

export default function AdminRappelsHistorique() {
  const [filtres, setFiltres] = useState({
    dateDebut: "",
    dateFin: "",
    sequenceId: undefined as number | undefined,
    statut: undefined as "succes" | "echec" | undefined,
    email: "",
    limit: 50,
    offset: 0,
  });

  const { data: logs, isLoading } = trpc.rappels.historique.useQuery(filtres);
  const { data: sequences } = trpc.sequences.list.useQuery();
  const utils = trpc.useUtils();
  
  const viderHistorique = trpc.rappels.viderHistoriqueRappels.useMutation({
    onSuccess: (data) => {
      toast.success(data.message);
      utils.rappels.historique.invalidate();
    },
    onError: (error) => {
      toast.error(`Erreur: ${error.message}`);
    },
  });

  const handleFilterChange = (key: string, value: any) => {
    setFiltres(prev => ({
      ...prev,
      [key]: value,
      offset: 0, // Reset pagination
    }));
  };

  const handlePageChange = (direction: "prev" | "next") => {
    setFiltres(prev => ({
      ...prev,
      offset: direction === "next" ? prev.offset + prev.limit : Math.max(0, prev.offset - prev.limit),
    }));
  };

  const resetFilters = () => {
    setFiltres({
      dateDebut: "",
      dateFin: "",
      sequenceId: undefined,
      statut: undefined,
      email: "",
      limit: 50,
      offset: 0,
    });
  };

  return (
    <DashboardLayout>
      <div className="space-y-6">
        <div className="flex items-center justify-between">
          <div>
            <h1 className="page-title">Historique des Rappels</h1>
            <p className="text-muted-foreground mt-1">
              Consultez tous les rappels envoyés avec filtres avancés
            </p>
          </div>
          <div className="flex items-center gap-3">
            <AlertDialog>
              <AlertDialogTrigger asChild>
                <Button variant="destructive" size="sm">
                  <Trash2 className="h-4 w-4 mr-2" />
                  Vider l'historique
                </Button>
              </AlertDialogTrigger>
              <AlertDialogContent>
                <AlertDialogHeader>
                  <AlertDialogTitle>Êtes-vous absolument sûr ?</AlertDialogTitle>
                  <AlertDialogDescription>
                    Cette action est irréversible. Tous les logs d'historique des rappels seront définitivement supprimés de la base de données.
                  </AlertDialogDescription>
                </AlertDialogHeader>
                <AlertDialogFooter>
                  <AlertDialogCancel>Annuler</AlertDialogCancel>
                  <AlertDialogAction
                    onClick={() => viderHistorique.mutate()}
                    className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
                  >
                    Oui, vider l'historique
                  </AlertDialogAction>
                </AlertDialogFooter>
              </AlertDialogContent>
            </AlertDialog>
            <History className="h-8 w-8 text-muted-foreground" />
          </div>
        </div>

        {/* Filtres */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Filter className="h-5 w-5" />
              Filtres
            </CardTitle>
            <CardDescription>Affinez votre recherche dans l'historique</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
              <div className="space-y-2">
                <Label htmlFor="dateDebut">Date début</Label>
                <Input
                  id="dateDebut"
                  type="date"
                  value={filtres.dateDebut}
                  onChange={(e) => handleFilterChange("dateDebut", e.target.value)}
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="dateFin">Date fin</Label>
                <Input
                  id="dateFin"
                  type="date"
                  value={filtres.dateFin}
                  onChange={(e) => handleFilterChange("dateFin", e.target.value)}
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="sequence">Séquence</Label>
                <Select
                  value={filtres.sequenceId?.toString() || "all"}
                  onValueChange={(value) => handleFilterChange("sequenceId", value === "all" ? undefined : parseInt(value))}
                >
                  <SelectTrigger id="sequence">
                    <SelectValue placeholder="Toutes les séquences" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">Toutes les séquences</SelectItem>
                    {sequences?.map((seq) => (
                      <SelectItem key={seq.id} value={seq.id.toString()}>
                        {seq.nom}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              <div className="space-y-2">
                <Label htmlFor="statut">Statut</Label>
                <Select
                  value={filtres.statut || "all"}
                  onValueChange={(value) => handleFilterChange("statut", value === "all" ? undefined : value)}
                >
                  <SelectTrigger id="statut">
                    <SelectValue placeholder="Tous les statuts" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">Tous les statuts</SelectItem>
                    <SelectItem value="succes">Succès</SelectItem>
                    <SelectItem value="echec">Échec</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div className="space-y-2 md:col-span-2">
                <Label htmlFor="email">Rechercher par email</Label>
                <div className="relative">
                  <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                  <Input
                    id="email"
                    type="text"
                    placeholder="email@exemple.com"
                    className="pl-10"
                    value={filtres.email}
                    onChange={(e) => handleFilterChange("email", e.target.value)}
                  />
                </div>
              </div>

              <div className="flex items-end gap-2 md:col-span-2">
                <Button variant="outline" onClick={resetFilters} className="w-full">
                  Réinitialiser
                </Button>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Tableau des logs */}
        <Card>
          <CardHeader>
            <CardTitle>Logs des rappels</CardTitle>
            <CardDescription>
              {logs?.length || 0} résultat(s) trouvé(s)
            </CardDescription>
          </CardHeader>
          <CardContent>
            {isLoading ? (
              <div className="text-center py-8 text-muted-foreground">
                Chargement...
              </div>
            ) : !logs || logs.length === 0 ? (
              <div className="text-center py-8 text-muted-foreground">
                Aucun log trouvé avec ces filtres
              </div>
            ) : (
              <>
                <div className="rounded-md border overflow-x-auto">
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead>Date envoi</TableHead>
                        <TableHead>Email</TableHead>
                        <TableHead>Type</TableHead>
                        <TableHead>Type d'envoi</TableHead>
                        <TableHead>Statut</TableHead>
                        <TableHead>Tentatives</TableHead>
                        <TableHead>Erreur</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {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 className="font-medium">{log.email}</TableCell>
                          <TableCell>
                            <Badge 
                              variant="outline"
                              className="bg-orange-50 text-orange-700 border-orange-200"
                            >
                              {log.type}
                            </Badge>
                          </TableCell>
                          <TableCell>
                            <Badge 
                              variant="outline" 
                              className={log.typeEnvoi === "test" 
                                ? "bg-blue-50 text-blue-700 border-blue-200" 
                                : "bg-green-50 text-green-700 border-green-200"
                              }
                            >
                              {log.typeEnvoi === "test" ? "Test" : "Automatique"}
                            </Badge>
                          </TableCell>
                          <TableCell>
                            <Badge variant={log.statut === "succes" ? "default" : "destructive"}>
                              {log.statut === "succes" ? "Succès" : "Échec"}
                            </Badge>
                          </TableCell>
                          <TableCell>
                            <span className={log.nbTentatives > 1 ? "text-orange-600 font-medium" : ""}>
                              {log.nbTentatives}
                            </span>
                          </TableCell>
                          <TableCell className="max-w-xs truncate text-sm text-muted-foreground">
                            {log.messageErreur || "-"}
                          </TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                </div>

                {/* Pagination */}
                <div className="flex items-center justify-between mt-4">
                  <div className="text-sm text-muted-foreground">
                    Affichage de {filtres.offset + 1} à {Math.min(filtres.offset + filtres.limit, filtres.offset + (logs?.length || 0))}
                  </div>
                  <div className="flex gap-2">
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => handlePageChange("prev")}
                      disabled={filtres.offset === 0}
                    >
                      <ChevronLeft className="h-4 w-4 mr-1" />
                      Précédent
                    </Button>
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => handlePageChange("next")}
                      disabled={!logs || logs.length < filtres.limit}
                    >
                      Suivant
                      <ChevronRight className="h-4 w-4 ml-1" />
                    </Button>
                  </div>
                </div>
              </>
            )}
          </CardContent>
        </Card>
      </div>
    </DashboardLayout>
  );
}
