
import { useRef, useState } from "react";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { useDocumentUploadFlow } from "@/hooks/useDocumentUploadFlow";
import { Select, SelectTrigger, SelectValue, SelectContent, SelectItem } from "@/components/ui/select";
import { toast } from "sonner";
import { DOCUMENT_CATEGORIES, type DocumentCategory } from "@/services/documentCategories";

interface DocumentUploadForStepProps {
  tripId: string;
  stepId: string;
  isOpen: boolean;
  onClose: () => void;
}

export function DocumentUploadForStep({ tripId, stepId, isOpen, onClose }: DocumentUploadForStepProps) {
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [documentType, setDocumentType] = useState<DocumentCategory>("reservation");
  const [isUploading, setIsUploading] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const uploadingRef = useRef(false);
  const { uploadDocumentFile } = useDocumentUploadFlow();

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files[0]) {
      setSelectedFile(e.target.files[0]);
    }
  };

  const handleUpload = async () => {
    if (uploadingRef.current) return;
    if (!selectedFile) {
      toast.error("Veuillez sélectionner un fichier");
      return;
    }

    uploadingRef.current = true;
    setIsUploading(true);
    try {
      const document = await uploadDocumentFile(tripId, selectedFile, documentType, stepId);
      if (document.stepId !== stepId) throw new Error("Le document n’a pas été associé à cette étape.");

      toast.success("Document associé à l’étape avec succès");
      setSelectedFile(null);
      if (fileInputRef.current) fileInputRef.current.value = '';
      setDocumentType("reservation");
      onClose();
    } catch (error) {
      console.error("Error uploading document:", error);
      toast.error(error instanceof Error ? error.message : "Erreur lors de l'ajout du document");
    } finally {
      uploadingRef.current = false;
      setIsUploading(false);
    }
  };

  return (
    <Dialog open={isOpen} onOpenChange={(open) => !open && onClose()}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle>Ajouter un document pour cette étape</DialogTitle>
        </DialogHeader>
        <div className="grid gap-4 py-4">
          <div className="grid gap-2">
            <Label htmlFor="file">Fichier</Label>
            <Input
              id="file"
              type="file"
              ref={fileInputRef}
              onChange={handleFileChange}
              accept=".pdf,.txt,.csv,.jpg,.jpeg,.png,.webp,.gif,.heic,.doc,.docx,.xls,.xlsx,.ppt,.pptx"
              disabled={isUploading}
            />
          </div>
          <div className="grid gap-2">
            <Label htmlFor="type">Type de document</Label>
            <Select value={documentType} onValueChange={(value) => setDocumentType(value as DocumentCategory)}>
              <SelectTrigger>
                <SelectValue placeholder="Sélectionner un type" />
              </SelectTrigger>
              <SelectContent>
                {DOCUMENT_CATEGORIES.map((category) => (
                  <SelectItem key={category.value} value={category.value}>{category.label}</SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
        </div>
        <DialogFooter>
          <Button type="button" variant="outline" onClick={onClose} disabled={isUploading}>
            Annuler
          </Button>
          <Button
            type="button"
            onClick={handleUpload}
            disabled={!selectedFile || isUploading}
          >
            {isUploading ? "Téléchargement..." : "Ajouter"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
