
import { Document } from "../../types";
import { useTrips } from "../../contexts/TripContext";
import { useSupabaseStorage } from "../../hooks/useSupabaseStorage";
import { PartialDocumentDeletionError } from "@/services/documentDeletionService";
import { Button } from "@/components/ui/button";
import { FileText, Download, Loader2, Trash } from "lucide-react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
} from "@/components/ui/dialog";
import { useRef, useState } from "react";
import { toast } from "sonner";

interface DocumentItemProps {
  document: Document;
  tripId: string;
  isPlanner: boolean;
}

export function DocumentItem({
  document,
  tripId,
  isPlanner,
}: DocumentItemProps) {
  const { deleteDocument } = useTrips();
  const { getDocumentDownloadUrl } = useSupabaseStorage();
  const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
  const [isDeleting, setIsDeleting] = useState(false);
  const deletionInProgress = useRef(false);
  const downloadInProgress = useRef(false);
  const [isDownloading, setIsDownloading] = useState(false);

  const handleDelete = async () => {
    if (deletionInProgress.current) return;
    deletionInProgress.current = true;
    setIsDeleting(true);
    try {
      await deleteDocument(tripId, document.id);
      toast.success("Document supprimé avec succès");
      setIsDeleteDialogOpen(false);
    } catch (error) {
      console.error("Failed to delete document:", error);
      toast.error(
        error instanceof PartialDocumentDeletionError
          ? error.message
          : "Erreur lors de la suppression du document",
      );
    } finally {
      deletionInProgress.current = false;
      setIsDeleting(false);
    }
  };

  const handleDownload = async () => {
    if (downloadInProgress.current) return;
    downloadInProgress.current = true;
    setIsDownloading(true);
    try {
      const signedUrl = await getDocumentDownloadUrl(tripId, document.id);
      window.open(signedUrl, '_blank', 'noopener,noreferrer');
    } catch (error) {
      console.error("Failed to download document:", error);
      toast.error("Vous n'avez pas accès à ce document");
    } finally {
      downloadInProgress.current = false;
      setIsDownloading(false);
    }
  };

  const formatDate = (date: string) => {
    return new Date(date).toLocaleDateString("fr-FR", {
      day: "numeric",
      month: "short",
      year: "numeric",
    });
  };

  return (
    <div className={`flex items-center justify-between p-3 ${isPlanner ? "rounded-md border hover:bg-gray-50" : "group rounded-xl transition hover:bg-white/60"}`}>
      <div className="flex items-center gap-3 overflow-hidden">
        <span className={`grid flex-shrink-0 place-items-center ${isPlanner ? "" : "h-11 w-11 rounded-full bg-[#e6eee9]"}`}><FileText className={`h-5 w-5 ${isPlanner ? "text-blue-600" : "text-[#315c50]"}`} /></span>
        <div className="overflow-hidden">
          <div className="font-medium truncate">{document.name}</div>
          <div className="text-xs text-gray-500">
            Ajouté le {formatDate(document.uploadedAt)}
          </div>
        </div>
      </div>
      <div className="flex gap-2 flex-shrink-0">
        <Button type="button" variant="ghost" size="sm" className="flex-shrink-0" onClick={handleDownload} disabled={isDownloading} aria-label={`Télécharger ${document.name}`}>{isDownloading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Download className="h-4 w-4" />}</Button>
        {isPlanner && (
          <Button
            variant="ghost"
            type="button"
            size="icon"
            onClick={() => setIsDeleteDialogOpen(true)}
            className="flex-shrink-0"
            aria-label={`Supprimer ${document.name}`}
          >
            <Trash className="h-4 w-4" />
          </Button>
        )}
      </div>

      <Dialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Confirmer la suppression</DialogTitle>
            <DialogDescription>
              Êtes-vous sûr de vouloir supprimer ce document ? Cette action est
              irréversible.
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button
              variant="outline"
              type="button"
              onClick={() => setIsDeleteDialogOpen(false)}
              disabled={isDeleting}
            >
              Annuler
            </Button>
            <Button type="button" variant="destructive" onClick={handleDelete} disabled={isDeleting}>
              {isDeleting ? "Suppression..." : "Supprimer"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
