import React, { useState, useRef } from 'react';
import { FolderOpen, File, Upload, Search, Share2, Trash2, Download, Plus, RefreshCw, WifiOff, X, CheckCircle, FileText, User } from 'lucide-react';
import { useDocuments } from '../hooks/useDocuments';
import { useOfflineSync } from '../hooks/useOfflineSync';

const Modal = ({ isOpen, onClose, title, children }) => {
  if (!isOpen) return null;
  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/60 backdrop-blur-sm animate-in fade-in duration-300">
      <div className="bg-white dark:bg-[#1b1b1b] w-full max-w-xl rounded-[32px] border border-slate-200 dark:border-white/5 shadow-2xl overflow-hidden animate-in zoom-in-95 duration-300">
        <div className="flex items-center justify-between p-6 border-b border-slate-100 dark:border-white/5">
          <h3 className="text-xl font-bold text-slate-800 dark:text-white">{title}</h3>
          <button onClick={onClose} className="p-2 hover:bg-slate-100 dark:hover:bg-white/5 rounded-full transition-colors text-slate-400">
            <X size={20} />
          </button>
        </div>
        <div className="p-8 max-h-[80vh] overflow-y-auto">
          {children}
        </div>
      </div>
    </div>
  );
};

const GrDocumentosView = () => {
  const [selectedEntityType, setSelectedEntityType] = useState('ALL');
  const [searchTerm, setSearchTerm] = useState('');
  const [isUploadModalOpen, setIsUploadModalOpen] = useState(false);
  const fileInputRef = useRef(null);
  
  const { documents, stats, loading, uploading, error, refresh, deleteDocument, uploadDocument } = useDocuments({
    entityType: selectedEntityType === 'ALL' ? undefined : selectedEntityType
  });
  
  const { pending, isOnline, syncPending } = useOfflineSync();

  const filteredDocuments = documents.filter(doc => 
    doc.fileName.toLowerCase().includes(searchTerm.toLowerCase()) ||
    doc.entityName.toLowerCase().includes(searchTerm.toLowerCase())
  );

  const entityTypes = ['ALL', 'MOTORISTA', 'CAVALO', 'VEÍCULO', 'CARRETA'];

  const handleFileUpload = async (event) => {
    const file = event.target.files[0];
    if (!file) return;

    const formData = new FormData();
    formData.append('file', file);
    formData.append('fileName', file.name);
    formData.append('docType', 'GERAL');
    formData.append('entityType', selectedEntityType === 'ALL' ? 'SISTEMA' : selectedEntityType);
    formData.append('entityName', 'Documento Manual');
    formData.append('client', 'PRALOG');

    try {
      await uploadDocument(formData);
      alert('Documento enviado com sucesso!');
      setIsUploadModalOpen(false);
    } catch (err) {
      alert(`Erro no upload: ${err.message}`);
    }
  };

  const handleDelete = async (id) => {
    if (!confirm('Tem certeza que deseja excluir este documento?')) return;
    try {
      await deleteDocument(id);
      alert('Documento excluído.');
    } catch (err) {
      alert(`Erro ao excluir: ${err.message}`);
    }
  };

  const shareFile = (name) => {
    navigator.clipboard.writeText(`https://platform.sistemas.com.br/share/${name}`);
    alert('Link de compartilhamento copiado!');
  };

  return (
    <div className="flex flex-col gap-8 p-6 md:p-10 animate-in fade-in slide-in-from-bottom-4 duration-700">
      <header className="flex flex-col md:flex-row md:items-end justify-between gap-6">
        <div className="space-y-2">
          <h1 className="text-4xl md:text-6xl font-bold text-slate-800 dark:text-white tracking-tighter leading-none">
            Gestão de <span className="text-[var(--gr-primary)]">Documentos</span>
          </h1>
          <p className="text-slate-400 dark:text-slate-500 text-base md:text-lg font-medium italic opacity-80">
            Repositório seguro de arquivos digitais, contratos e licenças
          </p>
        </div>

        <div className="flex gap-3">
          {!isOnline && (
            <div className="flex items-center gap-2 px-4 py-3 bg-orange-500/10 text-orange-600 rounded-full text-[10px] font-bold uppercase tracking-widest">
              <WifiOff size={16} />
              Offline ({pending.length})
            </div>
          )}
          <button
            onClick={() => setIsUploadModalOpen(true)}
            className="flex items-center gap-2 px-6 py-4 bg-[var(--gr-primary)] text-white rounded-[24px] font-bold text-xs uppercase tracking-widest hover:bg-[var(--gr-primary)]/90 transition-all shadow-xl shadow-[var(--gr-primary)]/20"
          >
            <Upload size={18} />
            {uploading ? 'Enviando...' : 'Fazer Upload'}
          </button>
        </div>
      </header>

      {/* Grid Explorer */}
      <div className="grid grid-cols-1 xl:grid-cols-12 gap-8">
        {/* Sidebar Filters */}
        <div className="xl:col-span-3 space-y-4">
          <div className="bg-white dark:bg-[#1b1b1b] p-6 rounded-[32px] border border-slate-200 dark:border-white/5 shadow-sm space-y-6">
            <div>
              <h4 className="text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-4">Pastas</h4>
              <div className="space-y-1">
                {entityTypes.map(type => (
                  <button 
                    key={type}
                    onClick={() => setSelectedEntityType(type)}
                    className={`w-full flex items-center gap-3 px-4 py-3 rounded-2xl text-xs font-bold transition-all ${
                      selectedEntityType === type ? 'bg-[var(--gr-primary)]/10 text-[var(--gr-primary)]' : 'text-slate-500 hover:bg-slate-50'
                    }`}
                  >
                    <FolderOpen size={18} className={selectedEntityType === type ? 'text-[var(--gr-primary)]' : 'text-slate-400'} />
                    {type === 'ALL' ? 'Geral' : type}
                  </button>
                ))}
              </div>
            </div>
          </div>
        </div>

        {/* List Table */}
        <div className="xl:col-span-9 bg-white dark:bg-[#1b1b1b] rounded-[40px] border border-slate-200 dark:border-white/5 overflow-hidden">
          <div className="p-8 border-b border-slate-100 dark:border-white/5 flex items-center justify-between bg-slate-50/50 dark:bg-transparent">
            <h2 className="text-xl font-bold text-slate-800 dark:text-white tracking-tighter">Documentos Recentes</h2>
            <div className="relative group">
              <Search className="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400" size={16} />
              <input 
                type="text" 
                placeholder="PROCURAR..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="pl-12 pr-4 py-2 bg-white dark:bg-[#141414] border border-slate-200 dark:border-white/5 rounded-2xl text-[10px] font-bold outline-none"
              />
            </div>
          </div>

          <div className="overflow-x-auto">
            <table className="w-full text-left border-collapse">
              <thead>
                <tr className="bg-slate-50/50 dark:bg-white/[0.02] border-b border-slate-100 dark:border-white/5">
                  <th className="p-6 text-[10px] font-bold text-slate-400 uppercase tracking-widest">Arquivo</th>
                  <th className="p-6 text-[10px] font-bold text-slate-400 uppercase tracking-widest">Entidade</th>
                  <th className="p-6"></th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-100 dark:divide-white/5">
                {filteredDocuments.map((doc) => (
                  <tr key={doc.id} className="hover:bg-slate-50 dark:hover:bg-white/[0.02] transition-colors group">
                    <td className="p-6">
                      <div className="flex items-center gap-4">
                        <div className="p-3 bg-red-50 dark:bg-red-900/10 rounded-xl text-red-500">
                          <FileText size={20} />
                        </div>
                        <div>
                          <p className="font-bold text-sm text-slate-800 dark:text-slate-200">{doc.fileName}</p>
                          <span className="text-[9px] font-bold text-slate-400 uppercase">{doc.docType}</span>
                        </div>
                      </div>
                    </td>
                    <td className="p-6">
                      <div className="flex flex-col">
                        <span className="text-[10px] font-bold text-slate-700 dark:text-slate-300">{doc.entityName}</span>
                        <span className="text-[9px] font-bold text-slate-400 uppercase">{doc.entityType}</span>
                      </div>
                    </td>
                    <td className="p-6 text-right">
                      <div className="flex items-center justify-end gap-2 opacity-0 group-hover:opacity-100 transition-opacity">
                        <button onClick={() => alert('Iniciando download...')} className="p-2 hover:bg-white dark:hover:bg-[#141414] rounded-lg text-slate-400 hover:text-[var(--gr-primary)]"><Download size={16} /></button>
                        <button onClick={() => shareFile(doc.fileName)} className="p-2 hover:bg-white dark:hover:bg-[#141414] rounded-lg text-slate-400 hover:text-[var(--gr-primary)]"><Share2 size={16} /></button>
                        <button onClick={() => handleDelete(doc.id)} className="p-2 hover:bg-white dark:hover:bg-[#141414] rounded-lg text-slate-400 hover:text-red-500"><Trash2 size={16} /></button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      </div>

      {/* Modal de Upload */}
      <Modal isOpen={isUploadModalOpen} onClose={() => setIsUploadModalOpen(false)} title="Upload de Documento">
        <div className="space-y-6">
          <div 
            onClick={() => fileInputRef.current?.click()}
            className="border-2 border-dashed border-slate-200 dark:border-white/5 rounded-3xl p-12 flex flex-col items-center justify-center gap-4 hover:border-[var(--gr-primary)]/40 hover:bg-slate-50/50 dark:hover:bg-white/[0.02] transition-all cursor-pointer group"
          >
            <div className="p-6 bg-[var(--gr-primary)]/10 rounded-full text-[var(--gr-primary)] group-hover:scale-110 transition-transform">
              <Upload size={32} />
            </div>
            <div className="text-center">
              <p className="text-sm font-bold text-slate-800 dark:text-white">Clique ou arraste um arquivo</p>
              <p className="text-xs text-slate-400 font-medium">PNG, JPG, PDF até 10MB</p>
            </div>
          </div>
          <input 
            type="file" 
            ref={fileInputRef} 
            onChange={handleFileUpload} 
            className="hidden" 
          />
          <button 
            onClick={() => setIsUploadModalOpen(false)}
            className="w-full py-4 bg-slate-100 dark:bg-[#141414] text-slate-800 dark:text-white rounded-2xl font-bold text-xs uppercase"
          >
            Cancelar
          </button>
        </div>
      </Modal>
    </div>
  );
};

export default GrDocumentosView;
