
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";
import type { TripStep } from "@/types";

interface DocumentUploadProps {
  tripId: string;
  isOpen: boolean;
  onClose: () => void;
  steps?: TripStep[];
}

export function DocumentUpload({ tripId, isOpen, onClose, steps = [] }: DocumentUploadProps) {
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [documentType, setDocumentType] = useState<DocumentCategory>("other");
  const [stepId, setStepId] = useState("general");
  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 {
      await uploadDocumentFile(tripId, selectedFile, documentType, stepId === "general" ? undefined : stepId);

      toast.success("Document ajouté");
      setSelectedFile(null);
      if (fileInputRef.current) fileInputRef.current.value = '';
      setDocumentType("other");
      setStepId("general");
      onClose();
    } catch (error) {
      console.error("Error uploading document:", error);
      toast.error(error instanceof Error ? error.message : "Impossible d’importer ce 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</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}
            />
            <p className="text-xs text-muted-foreground">PDF, images, documents Office ou texte · 6 Mio maximum</p>
          </div>
          {steps.length > 0 && <div className="grid gap-2"><Label htmlFor="document-step">Contexte</Label><Select value={stepId} onValueChange={setStepId}><SelectTrigger id="document-step"><SelectValue /></SelectTrigger><SelectContent><SelectItem value="general">Aucune étape — document général</SelectItem>{[...steps].sort((a, b) => a.day - b.day || (a.startTime || a.time).localeCompare(b.startTime || b.time)).map((step) => <SelectItem key={step.id} value={step.id}>Jour {step.day} · {step.activity}</SelectItem>)}</SelectContent></Select><p className="text-xs text-muted-foreground">L’étape est facultative et peut être choisie sans resélectionner le voyage.</p></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 ? "Importation…" : "Ajouter"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
