import { useAuth } from "@/_core/hooks/useAuth";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { trpc } from "@/lib/trpc";
import { CheckCircle2, Circle, Loader2, QrCode, RefreshCw } from "lucide-react";
import { useState, useEffect } from "react";
import { toast } from "sonner";
import { Badge } from "@/components/ui/badge";
import DashboardLayout from "@/components/DashboardLayout";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";

export default function FormateurEmargement() {
  const { user } = useAuth();
  const [selectedSequenceId, setSelectedSequenceId] = useState<number | null>(null);
  const [showQRDialog, setShowQRDialog] = useState(false);
  const [showQRFormateurDialog, setShowQRFormateurDialog] = useState(false);
  const [lastRefreshTime, setLastRefreshTime] = useState<Date>(new Date());
  const [secondsSinceRefresh, setSecondsSinceRefresh] = useState(0);

  // Récupérer toutes les séquences (filtrées côté serveur pour les formateurs)
  const { data: sequences, isLoading: loadingSequences } = trpc.sequences.list.useQuery();

  // Générer le QR code apprenants
  const { data: qrData, mutate: generateQR, isPending: generatingQR } = trpc.presences.generateQRCode.useMutation({
    onSuccess: () => {
      setShowQRDialog(true);
    },
    onError: (error) => {
      toast.error("Erreur lors de la génération du QR code", {
        description: error.message,
      });
    },
  });

  // Générer le QR code formateur
  const { data: qrFormateurData, mutate: generateQRFormateur, isPending: generatingQRFormateur } = trpc.presences.generateQRCodeFormateur.useMutation({
    onSuccess: () => {
      setShowQRFormateurDialog(true);
    },
    onError: (error) => {
      toast.error("Erreur lors de la génération du QR code formateur", {
        description: error.message,
      });
    },
  });

  // Récupérer les inscrits avec les dates de formation
  const { data: inscrits, isLoading: loadingInscrits, refetch: refetchInscrits } = trpc.inscriptions.listWithDates.useQuery(
    { sequenceId: selectedSequenceId || 0 },
    { enabled: !!selectedSequenceId }
  );

  // Récupérer les présences de la séquence
  const { data: presences, refetch: refetchPresences } = trpc.presences.listBySequence.useQuery(
    { sequenceId: selectedSequenceId || 0 },
    { enabled: !!selectedSequenceId }
  );

  // Récupérer les signatures formateurs de la séquence
  const { data: signaturesFormateurs, refetch: refetchSignaturesFormateurs } = trpc.presences.listSignaturesFormateurs.useQuery(
    { sequenceId: selectedSequenceId || 0 },
    { enabled: !!selectedSequenceId }
  );

  // Rafraîchissement automatique toutes les 30 secondes
  useEffect(() => {
    if (!selectedSequenceId) return;
    
    const interval = setInterval(() => {
      refetchInscrits();
      refetchPresences();
      refetchSignaturesFormateurs();
      setLastRefreshTime(new Date());
      setSecondsSinceRefresh(0);
    }, 30000); // 30 secondes
    
    return () => clearInterval(interval);
  }, [selectedSequenceId, refetchInscrits, refetchPresences, refetchSignaturesFormateurs]);

  // Compteur pour "Mis à jour il y a X secondes"
  useEffect(() => {
    if (!selectedSequenceId) return;
    
    const interval = setInterval(() => {
      setSecondsSinceRefresh(Math.floor((new Date().getTime() - lastRefreshTime.getTime()) / 1000));
    }, 1000); // Mise à jour chaque seconde
    
    return () => clearInterval(interval);
  }, [selectedSequenceId, lastRefreshTime]);

  // Calculer les statistiques de présence par date et période
  const getPresenceStats = (dateFormationId: number, periode: "matin" | "apres_midi") => {
    if (!inscrits || !presences) return { present: 0, total: 0, percentage: 0 };
    
    const total = inscrits.length;
    const present = inscrits.filter(inscrit => 
      presences.some(p => 
        p.inscriptionId === inscrit.inscriptionId && 
        p.dateFormationId === dateFormationId && 
        p.periode === periode
      )
    ).length;
    
    const percentage = total > 0 ? Math.round((present / total) * 100) : 0;
    
    return { present, total, percentage };
  };

  // Valider une présence manuellement
  const { mutate: validerPresence, isPending: validating } = trpc.presences.valider.useMutation({
    onSuccess: () => {
      toast.success("Présence validée avec succès");
      refetchInscrits();
      refetchPresences();
    },
    onError: (error) => {
      toast.error("Erreur lors de la validation", {
        description: error.message,
      });
    },
  });

  const handleGenerateQR = () => {
    if (!selectedSequenceId) {
      toast.error("Veuillez sélectionner une séquence");
      return;
    }
    generateQR({ sequenceId: selectedSequenceId });
  };

  const handleGenerateQRFormateur = () => {
    if (!selectedSequenceId) {
      toast.error("Veuillez sélectionner une séquence");
      return;
    }
    generateQRFormateur({ sequenceId: selectedSequenceId });
  };

  const handleValiderPresence = (inscriptionId: number, dateFormationId: number, periode: "matin" | "apres_midi") => {
    validerPresence({
      inscriptionId,
      dateFormationId,
      periode,
      modeValidation: "manuel",
      validateurId: user?.id,
    });
  };

  // Vérifier si un apprenant a validé sa présence pour une date et une période
  const isPresent = (inscriptionId: number, dateFormationId: number, periode: "matin" | "apres_midi") => {
    return presences?.some(
      (p) => p.inscriptionId === inscriptionId && p.dateFormationId === dateFormationId && p.periode === periode
    );
  };

  // Récupérer les informations de présence pour une date et une période
  const getPresenceInfo = (inscriptionId: number, dateFormationId: number, periode: "matin" | "apres_midi") => {
    return presences?.find(
      (p) => p.inscriptionId === inscriptionId && p.dateFormationId === dateFormationId && p.periode === periode
    );
  };

  // État pour la modale de signature
  const [selectedSignature, setSelectedSignature] = useState<string | null>(null);
  const [showSignatureDialog, setShowSignatureDialog] = useState(false);

  if (loadingSequences) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
      </div>
    );
  }

  if (!sequences || sequences.length === 0) {
    return (
      <div className="container py-8">
        <Card>
          <CardHeader>
            <CardTitle>Aucune séquence</CardTitle>
            <CardDescription>
              Vous n'avez aucune séquence de formation assignée pour le moment.
            </CardDescription>
          </CardHeader>
        </Card>
      </div>
    );
  }

  return (
    <DashboardLayout>
      <div className="container py-8 space-y-6">
      <div>
        <h1 className="page-title">Émargement numérique</h1>
        <p className="text-muted-foreground mt-2">
          Gérez les présences de vos apprenants avec le QR code
        </p>
      </div>

      {/* Sélection de la séquence */}
      <Card>
        <CardHeader>
          <CardTitle>Sélectionner une séquence</CardTitle>
          <CardDescription>
            Choisissez la séquence pour laquelle vous souhaitez gérer les présences
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <Select
            value={selectedSequenceId?.toString() || ""}
            onValueChange={(value) => setSelectedSequenceId(parseInt(value))}
          >
            <SelectTrigger>
              <SelectValue placeholder="Choisir une séquence..." />
            </SelectTrigger>
            <SelectContent>
              {sequences.map((seq: any) => (
                <SelectItem key={seq.id} value={seq.id.toString()}>
                  {seq.nom} - {seq.lieu}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>

          {selectedSequenceId && (
            <div className="space-y-3">
              <div className="flex gap-2 flex-wrap">
                <Button onClick={handleGenerateQR} disabled={generatingQR}>
                  {generatingQR ? (
                    <>
                      <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                      Génération...
                    </>
                  ) : (
                    <>
                      <QrCode className="mr-2 h-4 w-4" />
                      QR Code Apprenants
                    </>
                  )}
                </Button>
                <Button onClick={handleGenerateQRFormateur} disabled={generatingQRFormateur} variant="secondary">
                  {generatingQRFormateur ? (
                    <>
                      <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                      Génération...
                    </>
                  ) : (
                    <>
                      <QrCode className="mr-2 h-4 w-4" />
                      QR Code Formateur
                    </>
                  )}
                </Button>
                <Button
                  variant="outline"
                  onClick={() => {
                    refetchInscrits();
                    refetchPresences();
                    refetchSignaturesFormateurs();
                    setLastRefreshTime(new Date());
                    setSecondsSinceRefresh(0);
                  }}
                >
                  <RefreshCw className="mr-2 h-4 w-4" />
                  Actualiser
                </Button>
              </div>
              
              {/* Indicateur de rafraîchissement */}
              <div className="flex items-center gap-2 text-sm text-muted-foreground">
                <RefreshCw className={`h-3 w-3 ${secondsSinceRefresh < 30 ? 'animate-spin' : ''}`} />
                <span>
                  Mis à jour il y a {secondsSinceRefresh} seconde{secondsSinceRefresh > 1 ? 's' : ''}
                </span>
                <Badge variant="outline" className="text-xs">
                  Rafraîchissement auto: 30s
                </Badge>
              </div>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Liste des inscrits */}
      {selectedSequenceId && (
        <Card>
          <CardHeader>
            <CardTitle>Liste des inscrits</CardTitle>
            <CardDescription>
              Validez manuellement les présences si nécessaire
            </CardDescription>
          </CardHeader>
          <CardContent>
            {loadingInscrits ? (
              <div className="flex items-center justify-center py-8">
                <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
              </div>
            ) : !inscrits || inscrits.length === 0 ? (
              <p className="text-center text-muted-foreground py-8">
                Aucun inscrit pour cette séquence
              </p>
            ) : (
              <div className="space-y-4">
                {inscrits.map((inscrit: any) => (
                  <div
                    key={inscrit.inscription.id}
                    className="border rounded-lg p-4 space-y-3"
                  >
                    <div className="flex items-center justify-between">
                      <div>
                        <p className="font-medium">
                          {inscrit.apprenant?.prenom} {inscrit.apprenant?.nom}
                        </p>
                        <p className="text-sm text-muted-foreground">
                          {inscrit.apprenant?.email}
                        </p>
                      </div>
                      <Badge variant={inscrit.inscription.statut === "confirmee" ? "default" : "secondary"}>
                        {inscrit.inscription.statut}
                      </Badge>
                    </div>

                    {/* Dates de formation */}
                    <div className="space-y-2">
                      {inscrit.dates && Array.isArray(inscrit.dates) && inscrit.dates.length > 0 ? inscrit.dates.map((date: any) => {
                        if (!date || !date.id) return null;
                        const presentMatin = isPresent(inscrit.inscription.id, date.id, "matin");
                        const presentApresMidi = isPresent(inscrit.inscription.id, date.id, "apres_midi");
                        return (
                          <div
                            key={date.id}
                            className="bg-muted/50 p-3 rounded space-y-2"
                          >
                            <div>
                              <p className="text-sm font-medium">
                                Date {date.ordre}
                              </p>
                              <p className="text-xs text-muted-foreground">
                                {new Date(date.dateDebut).toLocaleDateString("fr-FR", {
                                  weekday: "long",
                                  year: "numeric",
                                  month: "long",
                                  day: "numeric",
                                })}
                              </p>
                            </div>
                            
                            {/* Matin */}
                            <div className="flex items-center justify-between pl-4">
                              <div className="flex items-center gap-2 flex-1">
                                {presentMatin ? (
                                  <CheckCircle2 className="h-4 w-4 text-green-600" />
                                ) : (
                                  <Circle className="h-4 w-4 text-muted-foreground" />
                                )}
                                <span className="text-xs">🌅 Matin</span>
                                {(() => {
                                  const presenceInfo = getPresenceInfo(inscrit.inscription.id, date.id, "matin");
                                  if (presenceInfo) {
                                    return (
                                      <div className="flex items-center gap-2 ml-2 text-xs text-muted-foreground">
                                        <span>• {inscrit.apprenant?.prenom} {inscrit.apprenant?.nom}</span>
                                        <span>• {new Date(presenceInfo.heurePresence).toLocaleString("fr-FR", {
                                          day: "2-digit",
                                          month: "2-digit",
                                          year: "numeric",
                                          hour: "2-digit",
                                          minute: "2-digit"
                                        })}</span>
                                        {presenceInfo.signatureUrl && (
                                          <img
                                            src={presenceInfo.signatureUrl}
                                            alt="Signature"
                                            className="h-8 w-16 object-contain border border-gray-300 rounded cursor-pointer hover:border-blue-500 transition-colors"
                                            onClick={() => {
                                              setSelectedSignature(presenceInfo.signatureUrl!);
                                              setShowSignatureDialog(true);
                                            }}
                                          />
                                        )}
                                      </div>
                                    );
                                  }
                                  return null;
                                })()}
                              </div>
                              {!presentMatin && (
                                <Button
                                  size="sm"
                                  variant="outline"
                                  className="h-7 text-xs"
                                  onClick={() => handleValiderPresence(inscrit.inscription.id, date.id, "matin")}
                                  disabled={validating}
                                >
                                  {validating ? (
                                    <Loader2 className="h-3 w-3 animate-spin" />
                                  ) : (
                                    "Valider"
                                  )}
                                </Button>
                              )}
                            </div>
                            
                            {/* Après-midi */}
                            <div className="flex items-center justify-between pl-4">
                              <div className="flex items-center gap-2 flex-1">
                                {presentApresMidi ? (
                                  <CheckCircle2 className="h-4 w-4 text-green-600" />
                                ) : (
                                  <Circle className="h-4 w-4 text-muted-foreground" />
                                )}
                                <span className="text-xs">🌆 Après-midi</span>
                                {(() => {
                                  const presenceInfo = getPresenceInfo(inscrit.inscription.id, date.id, "apres_midi");
                                  if (presenceInfo) {
                                    return (
                                      <div className="flex items-center gap-2 ml-2 text-xs text-muted-foreground">
                                        <span>• {inscrit.apprenant?.prenom} {inscrit.apprenant?.nom}</span>
                                        <span>• {new Date(presenceInfo.heurePresence).toLocaleString("fr-FR", {
                                          day: "2-digit",
                                          month: "2-digit",
                                          year: "numeric",
                                          hour: "2-digit",
                                          minute: "2-digit"
                                        })}</span>
                                        {presenceInfo.signatureUrl && (
                                          <img
                                            src={presenceInfo.signatureUrl}
                                            alt="Signature"
                                            className="h-8 w-16 object-contain border border-gray-300 rounded cursor-pointer hover:border-blue-500 transition-colors"
                                            onClick={() => {
                                              setSelectedSignature(presenceInfo.signatureUrl!);
                                              setShowSignatureDialog(true);
                                            }}
                                          />
                                        )}
                                      </div>
                                    );
                                  }
                                  return null;
                                })()}
                              </div>
                              {!presentApresMidi && (
                                <Button
                                  size="sm"
                                  variant="outline"
                                  className="h-7 text-xs"
                                  onClick={() => handleValiderPresence(inscrit.inscription.id, date.id, "apres_midi")}
                                  disabled={validating}
                                >
                                  {validating ? (
                                    <Loader2 className="h-3 w-3 animate-spin" />
                                  ) : (
                                    "Valider"
                                  )}
                                </Button>
                              )}
                            </div>
                          </div>
                        );
                      }) : (
                        <p className="text-sm text-muted-foreground py-2">
                          Aucune date de formation disponible
                        </p>
                      )}
                    </div>
                  </div>
                ))}
              </div>
            )}
          </CardContent>
        </Card>
      )}

      {/* Encart des signatures formateurs */}
      {selectedSequenceId && signaturesFormateurs && signaturesFormateurs.length > 0 && (
        <Card className="border-2 border-blue-200 bg-blue-50/30">
          <CardHeader>
            <CardTitle className="text-blue-700">Signatures Formateurs</CardTitle>
            <CardDescription>
              Signatures tactiles des formateurs pour cette séquence
            </CardDescription>
          </CardHeader>
          <CardContent>
            <div className="space-y-4">
              {(() => {
                // Regrouper les signatures par date
                const signaturesByDate = signaturesFormateurs.reduce((acc: any, signature: any) => {
                  const dateKey = signature.dateFormationId;
                  if (!acc[dateKey]) {
                    acc[dateKey] = {
                      dateDebut: signature.dateDebut,
                      dateFin: signature.dateFin,
                      matin: null,
                      apres_midi: null,
                    };
                  }
                  if (signature.periode === "matin") {
                    acc[dateKey].matin = signature;
                  } else {
                    acc[dateKey].apres_midi = signature;
                  }
                  return acc;
                }, {});

                return Object.values(signaturesByDate).map((dateGroup: any) => (
                  <div
                    key={dateGroup.dateDebut}
                    className="border border-blue-200 rounded-lg p-4 bg-white space-y-2"
                  >
                    {/* En-tête de la date */}
                    <div>
                      <p className="text-xs text-muted-foreground">
                        {new Date(dateGroup.dateDebut).toLocaleDateString("fr-FR", {
                          weekday: "long",
                          year: "numeric",
                          month: "long",
                          day: "numeric",
                        })}
                      </p>
                    </div>

                    {/* Matin */}
                    <div className="flex items-center justify-between pl-4">
                      <div className="flex items-center gap-2 flex-1">
                        {dateGroup.matin ? (
                          <CheckCircle2 className="h-4 w-4 text-green-600" />
                        ) : (
                          <Circle className="h-4 w-4 text-muted-foreground" />
                        )}
                        <span className="text-xs">🌅 Matin</span>
                        {dateGroup.matin && (
                          <div className="flex items-center gap-2 ml-2 text-xs text-muted-foreground">
                            <span>• Formateur</span>
                            <span>• {new Date(dateGroup.matin.heurePresence).toLocaleString("fr-FR", {
                              day: "2-digit",
                              month: "2-digit",
                              year: "numeric",
                              hour: "2-digit",
                              minute: "2-digit"
                            })}</span>
                            {dateGroup.matin.signatureUrl && (
                              <img
                                src={dateGroup.matin.signatureUrl}
                                alt="Signature formateur"
                                className="h-8 w-16 object-contain border border-gray-300 rounded cursor-pointer hover:border-blue-500 transition-colors"
                                onClick={() => {
                                  setSelectedSignature(dateGroup.matin.signatureUrl!);
                                  setShowSignatureDialog(true);
                                }}
                              />
                            )}
                          </div>
                        )}
                      </div>
                    </div>

                    {/* Après-midi */}
                    <div className="flex items-center justify-between pl-4">
                      <div className="flex items-center gap-2 flex-1">
                        {dateGroup.apres_midi ? (
                          <CheckCircle2 className="h-4 w-4 text-green-600" />
                        ) : (
                          <Circle className="h-4 w-4 text-muted-foreground" />
                        )}
                        <span className="text-xs">🌆 Après-midi</span>
                        {dateGroup.apres_midi && (
                          <div className="flex items-center gap-2 ml-2 text-xs text-muted-foreground">
                            <span>• Formateur</span>
                            <span>• {new Date(dateGroup.apres_midi.heurePresence).toLocaleString("fr-FR", {
                              day: "2-digit",
                              month: "2-digit",
                              year: "numeric",
                              hour: "2-digit",
                              minute: "2-digit"
                            })}</span>
                            {dateGroup.apres_midi.signatureUrl && (
                              <img
                                src={dateGroup.apres_midi.signatureUrl}
                                alt="Signature formateur"
                                className="h-8 w-16 object-contain border border-gray-300 rounded cursor-pointer hover:border-blue-500 transition-colors"
                                onClick={() => {
                                  setSelectedSignature(dateGroup.apres_midi.signatureUrl!);
                                  setShowSignatureDialog(true);
                                }}
                              />
                            )}
                          </div>
                        )}
                      </div>
                    </div>
                  </div>
                ));
              })()}
            </div>
          </CardContent>
        </Card>
      )}

      {/* Dialog QR Code Apprenants */}
      <Dialog open={showQRDialog} onOpenChange={setShowQRDialog}>
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle>QR Code d'émargement apprenants</DialogTitle>
            <DialogDescription>
              Les apprenants doivent scanner ce QR code pour valider leur présence
            </DialogDescription>
          </DialogHeader>
          {qrData && (
            <div className="flex flex-col items-center gap-4 py-4">
              <img
                src={qrData.qrCodeDataURL}
                alt="QR Code"
                className="w-full max-w-[300px] border rounded-lg"
              />
              <p className="text-sm text-muted-foreground text-center">
                Affichez ce QR code en plein écran pour faciliter le scan
              </p>
            </div>
          )}
        </DialogContent>
      </Dialog>

      {/* Dialog QR Code Formateur */}
      <Dialog open={showQRFormateurDialog} onOpenChange={setShowQRFormateurDialog}>
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle>QR Code d'émargement formateur</DialogTitle>
            <DialogDescription>
              Scannez ce QR code pour valider votre présence en tant que formateur
            </DialogDescription>
          </DialogHeader>
          {qrFormateurData && (
            <div className="flex flex-col items-center gap-4 py-4">
              <img
                src={qrFormateurData.qrCodeDataURL}
                alt="QR Code Formateur"
                className="w-full max-w-[300px] border rounded-lg"
              />
              <p className="text-sm text-muted-foreground text-center">
                Mode formateur : redirige vers la page d'émargement dédiée
              </p>
            </div>
          )}
        </DialogContent>
      </Dialog>

      {/* Dialog Signature */}
      <Dialog open={showSignatureDialog} onOpenChange={setShowSignatureDialog}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>Signature de l'apprenant</DialogTitle>
            <DialogDescription>
              Signature manuscrite capturée lors de la validation de présence
            </DialogDescription>
          </DialogHeader>
          {selectedSignature && (
            <div className="flex flex-col items-center gap-4 py-4">
              <div className="w-full border-2 border-gray-300 rounded-lg p-4 bg-white">
                <img
                  src={selectedSignature}
                  alt="Signature"
                  className="w-full h-auto"
                />
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>
      </div>
    </DashboardLayout>
  );
}
