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);
  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
        })
      });

      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;
    });

    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-ink-500 hover:text-brand-600 transition-colors px-3 py-1.5 rounded-xl hover:bg-brand-50 font-medium"
      >
        <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>
        <span className="hidden sm:inline">Documents</span>
        {files.length > 0 && (
          <span className="w-5 h-5 rounded-full bg-brand-500 text-white text-xs font-bold flex items-center justify-center">
            {files.length}
          </span>
        )}
      </button>

      {showPanel && (
        <>
          {/* Backdrop on mobile */}
          <div className="fixed inset-0 bg-black/20 z-40 sm:hidden" onClick={() => setShowPanel(false)}></div>

          <div className="fixed bottom-0 left-0 right-0 sm:absolute sm:right-0 sm:left-auto sm:bottom-auto sm:top-full sm:mt-2 sm:w-96 bg-white border border-ink-200 rounded-t-2xl sm:rounded-2xl shadow-2xl z-50 p-5 max-h-[80vh] overflow-y-auto">
            {/* Handle bar on mobile */}
            <div className="sm:hidden w-10 h-1 rounded-full bg-ink-200 mx-auto mb-4"></div>

            <p className="font-display font-bold text-sm text-ink-900 mb-3">Ajouter des documents</p>

            {/* Drop zone */}
            <div
              onDrop={handleDrop}
              onDragOver={handleDragOver}
              onClick={() => fileInputRef.current?.click()}
              className="border-2 border-dashed border-ink-200 rounded-xl p-6 text-center cursor-pointer hover:border-brand-400 hover:bg-brand-50 transition-all duration-200 group"
            >
              <div className="w-10 h-10 rounded-xl bg-ink-100 group-hover:bg-brand-100 mx-auto mb-2 flex items-center justify-center transition-colors">
                <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="text-ink-400 group-hover:text-brand-500 transition-colors">
                  <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" x2="12" y1="3" y2="15"/>
                </svg>
              </div>
              <p className="text-sm text-ink-600 font-medium">Glissez vos fichiers ici</p>
              <p className="text-xs text-ink-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-4 space-y-2">
                <p className="text-xs font-bold text-ink-400 uppercase tracking-wider">
                  Choisir la categorie
                </p>
                {pendingFiles.map((pf, i) => (
                  <div key={i} className="flex items-center gap-2 bg-brand-50 border border-brand-200 rounded-xl px-3 py-2.5">
                    <span className="text-xs text-ink-700 truncate flex-1 min-w-0 font-medium">{pf.file.name}</span>
                    <select
                      value={pf.category}
                      onChange={e => updatePendingCategory(i, e.target.value)}
                      className="text-xs border border-ink-200 rounded-lg px-2 py-1.5 bg-white text-ink-700 flex-shrink-0 focus:outline-none focus:border-brand-500"
                    >
                      {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-brand-500 text-white px-3 py-1.5 rounded-lg hover:bg-brand-600 disabled:opacity-50 flex-shrink-0 font-semibold transition-colors"
                    >
                      OK
                    </button>
                  </div>
                ))}
                {pendingFiles.length > 1 && (
                  <button
                    onClick={confirmAllUploads}
                    disabled={isUploading}
                    className="btn-primary w-full text-xs text-white py-2.5 rounded-xl disabled:opacity-50 font-semibold"
                  >
                    {isUploading ? 'Upload en cours...' : `Envoyer les ${pendingFiles.length} fichiers`}
                  </button>
                )}
              </div>
            )}

            {/* Fichiers uploades */}
            {files.length > 0 && (
              <div className="mt-4 space-y-1.5">
                <p className="text-xs font-bold text-ink-400 uppercase tracking-wider">
                  Fichiers envoyes
                </p>
                {files.map((f, i) => (
                  <div key={i} className="flex items-center gap-2 text-xs text-ink-600 bg-ink-50 rounded-xl px-3 py-2.5">
                    <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" className="text-emerald-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 font-medium">{f.name}</span>
                    <span className="text-ink-400 flex-shrink-0 text-[11px]">
                      {DOC_CATEGORIES.find(c => c.value === f.category)?.label || f.category}
                    </span>
                  </div>
                ))}
              </div>
            )}
          </div>
        </>
      )}
    </div>
  );
}
