const { useState, useRef, useCallback } = React;

const DOC_CATEGORIES = [
  { value: 'rapport_expert', label: "Rapport d'expertise" },
  { value: 'declaration', label: 'Declaration de sinistre' },
  { value: 'photo', label: 'Photo' },
  { value: 'devis', label: 'Devis / Facture' },
  { value: 'autre', label: 'Autre document' }
];

function Upload({ dossierId }) {
  const [files, setFiles] = useState([]);
  const [isUploading, setIsUploading] = useState(false);
  const [showPanel, setShowPanel] = useState(false);
  // Pending files = selected but category not yet chosen
  const [pendingFiles, setPendingFiles] = useState([]);
  const fileInputRef = useRef(null);

  const ACCEPTED = '.pdf,.jpg,.jpeg,.png';
  const MAX_SIZE = 20 * 1024 * 1024;

  const uploadFile = useCallback(async (file, category) => {
    setIsUploading(true);

    try {
      const base64 = await new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = () => resolve(reader.result.split(',')[1]);
        reader.onerror = reject;
        reader.readAsDataURL(file);
      });

      const res = await fetch('/api/upload', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          dossierId,
          fileName: file.name,
          fileType: file.type,
          fileData: base64,
          category  // Categorie choisie explicitement par l'utilisateur
        })
      });

      const data = await res.json();

      if (res.ok) {
        setFiles(prev => [...prev, {
          name: file.name,
          id: data.documentId,
          size: (file.size / 1024).toFixed(0) + ' Ko',
          category
        }]);
      } else {
        alert(`Erreur upload ${file.name}: ${data.error}`);
      }
    } catch (err) {
      alert(`Erreur: ${err.message}`);
    } finally {
      setIsUploading(false);
    }
  }, [dossierId]);

  const handleFilesSelected = useCallback((fileList) => {
    const validFiles = Array.from(fileList).filter(f => {
      if (f.size > MAX_SIZE) {
        alert(`${f.name} depasse 20 Mo`);
        return false;
      }
      if (!['application/pdf', 'image/jpeg', 'image/png'].includes(f.type)) {
        alert(`${f.name} : type non accepte. PDF, JPEG, PNG uniquement.`);
        return false;
      }
      return true;
    });

    // Ajouter en attente de categorisation
    setPendingFiles(prev => [
      ...prev,
      ...validFiles.map(f => ({ file: f, category: 'autre' }))
    ]);
  }, []);

  const updatePendingCategory = useCallback((index, category) => {
    setPendingFiles(prev => {
      const updated = [...prev];
      updated[index] = { ...updated[index], category };
      return updated;
    });
  }, []);

  const confirmUpload = useCallback(async (index) => {
    const { file, category } = pendingFiles[index];
    await uploadFile(file, category);
    setPendingFiles(prev => prev.filter((_, i) => i !== index));
  }, [pendingFiles, uploadFile]);

  const confirmAllUploads = useCallback(async () => {
    for (let i = pendingFiles.length - 1; i >= 0; i--) {
      await uploadFile(pendingFiles[i].file, pendingFiles[i].category);
    }
    setPendingFiles([]);
  }, [pendingFiles, uploadFile]);

  const handleDrop = useCallback((e) => {
    e.preventDefault();
    e.stopPropagation();
    handleFilesSelected(e.dataTransfer.files);
  }, [handleFilesSelected]);

  const handleDragOver = useCallback((e) => {
    e.preventDefault();
    e.stopPropagation();
  }, []);

  return (
    <div className="relative">
      <button
        onClick={() => setShowPanel(!showPanel)}
        className="flex items-center gap-2 text-sm text-gray-600 hover:text-blue-600 transition-colors px-3 py-1.5 rounded-lg hover:bg-gray-100"
      >
        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
          <path d="m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 18 8.84l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48"/>
        </svg>
        Documents ({files.length})
      </button>

      {showPanel && (
        <div className="absolute right-0 top-full mt-2 w-96 bg-white border border-gray-200 rounded-xl shadow-lg z-10 p-4">
          {/* Drop zone */}
          <div
            onDrop={handleDrop}
            onDragOver={handleDragOver}
            onClick={() => fileInputRef.current?.click()}
            className="border-2 border-dashed border-gray-300 rounded-lg p-6 text-center cursor-pointer hover:border-blue-400 hover:bg-blue-50 transition-colors"
          >
            <p className="text-sm text-gray-600 font-medium">Glissez vos fichiers ici</p>
            <p className="text-xs text-gray-400 mt-1">PDF, JPEG, PNG — Max 20 Mo</p>
          </div>

          <input
            ref={fileInputRef}
            type="file"
            accept={ACCEPTED}
            multiple
            onChange={e => handleFilesSelected(e.target.files)}
            className="hidden"
          />

          {/* Fichiers en attente de categorisation */}
          {pendingFiles.length > 0 && (
            <div className="mt-3 space-y-2">
              <p className="text-xs font-medium text-gray-500 uppercase tracking-wide">
                Choisir la categorie
              </p>
              {pendingFiles.map((pf, i) => (
                <div key={i} className="flex items-center gap-2 bg-yellow-50 border border-yellow-200 rounded-lg px-3 py-2">
                  <span className="text-xs text-gray-700 truncate flex-1 min-w-0">{pf.file.name}</span>
                  <select
                    value={pf.category}
                    onChange={e => updatePendingCategory(i, e.target.value)}
                    className="text-xs border border-gray-300 rounded px-1.5 py-1 bg-white flex-shrink-0"
                  >
                    {DOC_CATEGORIES.map(c => (
                      <option key={c.value} value={c.value}>{c.label}</option>
                    ))}
                  </select>
                  <button
                    onClick={() => confirmUpload(i)}
                    disabled={isUploading}
                    className="text-xs bg-blue-600 text-white px-2 py-1 rounded hover:bg-blue-700 disabled:opacity-50 flex-shrink-0"
                  >
                    OK
                  </button>
                </div>
              ))}
              {pendingFiles.length > 1 && (
                <button
                  onClick={confirmAllUploads}
                  disabled={isUploading}
                  className="w-full text-xs bg-blue-600 text-white py-1.5 rounded-lg hover:bg-blue-700 disabled:opacity-50"
                >
                  {isUploading ? 'Upload en cours...' : `Envoyer les ${pendingFiles.length} fichiers`}
                </button>
              )}
            </div>
          )}

          {/* Fichiers uploades */}
          {files.length > 0 && (
            <div className="mt-3 space-y-1.5">
              <p className="text-xs font-medium text-gray-500 uppercase tracking-wide">
                Fichiers envoyes
              </p>
              {files.map((f, i) => (
                <div key={i} className="flex items-center gap-2 text-xs text-gray-600 bg-gray-50 rounded-lg px-3 py-2">
                  <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="text-green-500 flex-shrink-0">
                    <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><path d="m9 11 3 3L22 4"/>
                  </svg>
                  <span className="truncate flex-1">{f.name}</span>
                  <span className="text-gray-400 flex-shrink-0">
                    {DOC_CATEGORIES.find(c => c.value === f.category)?.label || f.category}
                  </span>
                </div>
              ))}
            </div>
          )}
        </div>
      )}
    </div>
  );
}
