
import { Document } from "@/types";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { useTrips } from "@/contexts/TripContext";
import { FileText, Download, Loader2, Trash } from "lucide-react";
import { formatDate } from "@/lib/utils";
import { useSupabaseStorage } from "@/hooks/useSupabaseStorage";
import { PartialDocumentDeletionError } from "@/services/documentDeletionService";
import { toast } from "sonner";
import { useRef, useState } from "react";
import { getDocumentCategoryLabel } from "@/services/documentCategories";

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

export function DocumentItemSmall({ document, tripId, isPlanner }: DocumentItemSmallProps) {
  const { deleteDocument } = useTrips();
  const { getDocumentDownloadUrl } = useSupabaseStorage();
  const [isDeleting, setIsDeleting] = useState(false);
  const deletionInProgress = useRef(false);
  const downloadInProgress = useRef(false);
  const [isDownloading, setIsDownloading] = useState(false);
  const formattedSize = document.sizeBytes == null
    ? null
    : document.sizeBytes < 1024 * 1024
      ? `${Math.ceil(document.sizeBytes / 1024)} Ko`
      : `${(document.sizeBytes / 1024 / 1024).toFixed(1)} Mo`;

  const handleDelete = async () => {
    if (deletionInProgress.current) return;
    const confirmDelete = window.confirm("Êtes-vous sûr de vouloir supprimer ce document ?");
    if (confirmDelete) {
      deletionInProgress.current = true;
      setIsDeleting(true);
      try {
        await deleteDocument(tripId, document.id);
        toast.success("Document supprimé avec succès");
      } 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);
    }
  };

  // Déterminer le badge en fonction du type de document
  const getBadgeVariant = (type: string) => {
    switch (type) {
      case 'reservation':
        return "bg-blue-100 text-blue-800 border-blue-300";
      case 'ticket':
        return "bg-green-100 text-green-800 border-green-300";
      case 'confirmation':
        return "bg-secondary/10 text-secondary border-secondary/20";
      case 'photo':
        return "bg-amber-100 text-amber-800 border-amber-300";
      default:
        return "bg-gray-100 text-gray-800 border-gray-300";
    }
  };

  return (
    <Card className="overflow-hidden">
      <CardContent className="p-2">
        <div className="flex justify-between items-center">
          <div className="flex items-center space-x-2 overflow-hidden">
            <FileText className="h-4 w-4 flex-shrink-0" />
            <div className="truncate">
              <div className="text-xs font-medium truncate">{document.name}</div>
              <Badge variant="outline" className={`text-[10px] px-1 py-0 ${getBadgeVariant(document.type)}`}>
                {getDocumentCategoryLabel(document.type)}
              </Badge>
              {formattedSize && <span className="ml-2 text-[10px] text-muted-foreground">{formattedSize}</span>}
            </div>
          </div>
          <div className="flex gap-1 flex-shrink-0">
            <Button
              variant="ghost"
              type="button"
              size="icon"
              className="h-6 w-6"
              onClick={handleDownload}
              disabled={isDownloading}
              aria-label={`Ouvrir ou télécharger ${document.name}`}
            >
              {isDownloading ? <Loader2 className="h-3 w-3 animate-spin" /> : <Download className="h-3 w-3" />}
            </Button>
            {isPlanner && (
              <Button
                variant="ghost"
                type="button"
                size="icon"
                className="h-6 w-6 text-red-500"
                onClick={handleDelete}
              disabled={isDeleting}
              aria-label={`Supprimer ${document.name}`}
              >
                <Trash className="h-3 w-3" />
              </Button>
            )}
          </div>
        </div>
      </CardContent>
    </Card>
  );
}
