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 } 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);

  // 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
  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,
      });
    },
  });

  // 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 }
  );

  // 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 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="flex gap-2">
              <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" />
                    Afficher le QR code
                  </>
                )}
              </Button>
              <Button
                variant="outline"
                onClick={() => {
                  refetchInscrits();
                  refetchPresences();
                }}
              >
                <RefreshCw className="mr-2 h-4 w-4" />
                Actualiser
              </Button>
            </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 && (
                                          <Button
                                            size="sm"
                                            variant="ghost"
                                            className="h-5 w-5 p-0"
                                            onClick={() => {
                                              setSelectedSignature(presenceInfo.signatureUrl!);
                                              setShowSignatureDialog(true);
                                            }}
                                          >
                                            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="h-4 w-4 text-blue-600">
                                              <path d="M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z"/>
                                            </svg>
                                          </Button>
                                        )}
                                      </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 && (
                                          <Button
                                            size="sm"
                                            variant="ghost"
                                            className="h-5 w-5 p-0"
                                            onClick={() => {
                                              setSelectedSignature(presenceInfo.signatureUrl!);
                                              setShowSignatureDialog(true);
                                            }}
                                          >
                                            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="h-4 w-4 text-blue-600">
                                              <path d="M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z"/>
                                            </svg>
                                          </Button>
                                        )}
                                      </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>
      )}

      {/* Dialog QR Code */}
      <Dialog open={showQRDialog} onOpenChange={setShowQRDialog}>
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle>QR Code d'émargement</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 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>
  );
}
