import { useState, useEffect, useCallback, useRef } from 'react'
import { 
  FileText, Search, Plus, Eye, Edit2, Trash2, X, Loader2,
  AlertCircle, Clock, CheckCircle2, ChevronDown, PlayCircle,
  Upload, Download, Paperclip, File, ClipboardList, DollarSign
} from 'lucide-react'
import api from '../services/api'
import { Demanda, Subcategoria, DocumentoFile, OrdemServico } from '../types'
import { useLookups } from '../hooks/useLookups'
import Modal from '../components/Modal'

const statusConfig: Record<string, { label: string; class: string; icon: React.ReactNode }> = {
  'aberta': { label: 'Aberta', class: 'badge-warning', icon: <Clock className="w-3 h-3" /> },
  'rascunho': { label: 'Rascunho', class: 'badge-neutral', icon: <Clock className="w-3 h-3" /> },
  'em_escopo': { label: 'Em Escopo', class: 'badge-info', icon: <AlertCircle className="w-3 h-3" /> },
  'em_cotacao': { label: 'Em Cotação', class: 'badge-info', icon: <AlertCircle className="w-3 h-3" /> },
  'propostas_recebidas': { label: 'Propostas Recebidas', class: 'badge-info', icon: <AlertCircle className="w-3 h-3" /> },
  'em_aprovacao': { label: 'Em Aprovação', class: 'badge-warning', icon: <Clock className="w-3 h-3" /> },
  'aprovada': { label: 'Aprovada', class: 'badge-success', icon: <CheckCircle2 className="w-3 h-3" /> },
  'em_execucao': { label: 'Em Execução', class: 'badge-info', icon: <PlayCircle className="w-3 h-3" /> },
  'concluida': { label: 'Concluída', class: 'badge-neutral', icon: <CheckCircle2 className="w-3 h-3" /> },
  'cancelada': { label: 'Cancelada', class: 'badge-error', icon: <X className="w-3 h-3" /> },
  'pendente': { label: 'Pendente', class: 'badge-warning', icon: <Clock className="w-3 h-3" /> },
  'em_analise': { label: 'Em Análise', class: 'badge-info', icon: <AlertCircle className="w-3 h-3" /> },
  'rejeitada': { label: 'Rejeitada', class: 'badge-error', icon: <X className="w-3 h-3" /> },
}

const criticidadeConfig: Record<string, { label: string; class: string }> = {
  'baixa': { label: 'Baixa', class: 'text-gray bg-gray-100' },
  'media': { label: 'Média', class: 'text-amber-700 bg-amber-100' },
  'alta': { label: 'Alta', class: 'text-red-700 bg-red-100' },
  'urgente': { label: 'Urgente', class: 'text-red-700 bg-red-200 animate-pulse' },
  'critica': { label: 'Crítica', class: 'text-red-700 bg-red-200 animate-pulse' },
}

const tipoDocIcon: Record<string, string> = {
  'planta': '📋',
  'foto': '📸',
  'laudo': '📄',
  'outro': '📎',
}

const osStatusConfig: Record<string, { label: string; class: string }> = {
  'emitida': { label: 'Emitida', class: 'badge-warning' },
  'em_cotacao': { label: 'Em Cotação', class: 'badge-info' },
  'em_execucao': { label: 'Em Execução', class: 'badge-info' },
  'concluida': { label: 'Concluída', class: 'badge-success' },
  'cancelada': { label: 'Cancelada', class: 'badge-error' },
}

const emptyForm = { titulo: '', descricao: '', criticidade: 'media', categoria_id: '', subcategoria_id: '', local_id: '', centro_custo_id: '', data_desejada: '', valor_estimado: '', impacto_ambiental_demanda: '', justificativa_manutencao_emergencial: '' }

export default function Demandas() {
  const [loading, setLoading] = useState(true)
  const [demandas, setDemandas] = useState<Demanda[]>([])
  const [searchTerm, setSearchTerm] = useState('')
  const [filterStatus, setFilterStatus] = useState('todos')
  const [showModal, setShowModal] = useState(false)
  const [showDetail, setShowDetail] = useState<Demanda | null>(null)
  const [editId, setEditId] = useState<string | null>(null)
  const [form, setForm] = useState(emptyForm)
  const [saving, setSaving] = useState(false)
  const [subcategorias, setSubcategorias] = useState<Subcategoria[]>([])
  const [subcategoriaMap, setSubcategoriaMap] = useState<Record<string, string>>({})
  const [allSubcategorias, setAllSubcategorias] = useState<Subcategoria[]>([])
  // Documents
  const [detailDocs, setDetailDocs] = useState<DocumentoFile[]>([])
  const [docsLoading, setDocsLoading] = useState(false)
  const [uploading, setUploading] = useState(false)
  const [uploadTipo, setUploadTipo] = useState('outro')
  const [dragOver, setDragOver] = useState(false)
  const fileInputRef = useRef<HTMLInputElement>(null)
  const [docCounts, setDocCounts] = useState<Record<string, number>>({})
  // OS linked
  const [detailOS, setDetailOS] = useState<OrdemServico[]>([])
  const [osLoading, setOsLoading] = useState(false)
  const [showOS, setShowOS] = useState(false)

  const { categoriaMap, centrosCustoMap, locaisMap, categorias, centrosCusto, locais, fornecedoresMap, loading: lookupsLoading } = useLookups()

  useEffect(() => { fetchDemandas(); fetchAllSubcategorias() }, [])

  const fetchDemandas = async () => {
    try {
      const { data } = await api.get('/demandas')
      setDemandas(data)
    } catch (err) {
      console.error('Error fetching demandas:', err)
    } finally {
      setLoading(false)
    }
  }

  const fetchAllSubcategorias = async () => {
    try {
      const { data } = await api.get('/subcategorias')
      setAllSubcategorias(data)
      const map: Record<string, string> = {}
      data.forEach((s: Subcategoria) => { map[s.id] = s.nome })
      setSubcategoriaMap(map)
    } catch (err) {
      console.error('Error fetching subcategorias:', err)
    }
  }

  const fetchSubcategorias = async (categoriaId: string) => {
    if (!categoriaId) { setSubcategorias([]); return }
    try {
      const { data } = await api.get(`/subcategorias?categoria_id=${categoriaId}`)
      setSubcategorias(data)
    } catch (err) {
      setSubcategorias([])
    }
  }

  const fetchDetailDocs = async (demandaId: string) => {
    setDocsLoading(true)
    try {
      const { data } = await api.get(`/demandas/${demandaId}/documentos`)
      setDetailDocs(data)
    } catch { setDetailDocs([]) }
    finally { setDocsLoading(false) }
  }

  const fetchDetailOS = async (demandaId: string) => {
    setOsLoading(true)
    try {
      const { data } = await api.get(`/ordens-servico/by-demanda/${demandaId}`)
      setDetailOS(data)
    } catch { setDetailOS([]) }
    finally { setOsLoading(false) }
  }

  useEffect(() => {
    if (demandas.length === 0) return
    const fetchCounts = async () => {
      const counts: Record<string, number> = {}
      await Promise.all(demandas.map(async (d) => {
        try {
          const { data } = await api.get(`/demandas/${d.id}/documentos`)
          counts[d.id] = data.length
        } catch { counts[d.id] = 0 }
      }))
      setDocCounts(counts)
    }
    fetchCounts()
  }, [demandas])

  const filteredDemandas = demandas.filter(demanda => {
    const matchesSearch = (demanda.titulo || '').toLowerCase().includes(searchTerm.toLowerCase()) ||
                         (demanda.descricao || '').toLowerCase().includes(searchTerm.toLowerCase())
    const matchesStatus = filterStatus === 'todos' || demanda.status === filterStatus
    return matchesSearch && matchesStatus
  })

  const openNew = () => { setEditId(null); setForm(emptyForm); setSubcategorias([]); setShowModal(true) }
  const openEdit = (d: Demanda) => {
    setEditId(d.id)
    setForm({
      titulo: d.titulo, descricao: d.descricao, criticidade: d.criticidade || d.prioridade || 'media',
      categoria_id: d.categoria_id || '', subcategoria_id: d.subcategoria_id || '',
      local_id: d.local_id || '', centro_custo_id: d.centro_custo_id || '',
      data_desejada: d.data_desejada || '',
      valor_estimado: d.valor_estimado ? String(d.valor_estimado) : '',
      impacto_ambiental_demanda: (d as any).impacto_ambiental_demanda || '',
      justificativa_manutencao_emergencial: (d as any).justificativa_manutencao_emergencial || '',
    })
    if (d.categoria_id) fetchSubcategorias(d.categoria_id)
    setShowModal(true)
  }

  const handleCategoriaChange = (categoriaId: string) => {
    setForm({ ...form, categoria_id: categoriaId, subcategoria_id: '' })
    fetchSubcategorias(categoriaId)
  }

  const handleSubmit = async () => {
    setSaving(true)
    try {
      const payload: any = { ...form }
      payload.valor_estimado = payload.valor_estimado ? Number(payload.valor_estimado) : null
      if (editId) {
        await api.patch(`/demandas/${editId}`, payload)
      } else {
        await api.post('/demandas', { ...payload, status: 'rascunho' })
      }
      setShowModal(false)
      fetchDemandas()
    } catch (err) {
      console.error('Error saving:', err)
      alert('Erro ao salvar demanda')
    } finally {
      setSaving(false)
    }
  }

  const handleDelete = async (id: string) => {
    if (!confirm('Tem certeza que deseja excluir esta demanda?')) return
    try {
      await api.delete(`/demandas/${id}`)
      fetchDemandas()
    } catch (err) { alert('Erro ao excluir') }
  }

  const handleChangeOSStatus = async (osId: string, status: string) => {
    try {
      await api.post(`/ordens-servico/${osId}/status`, { status })
      if (showDetail) fetchDetailOS(showDetail.id)
    } catch { alert('Erro ao alterar status da OS') }
  }

  const handleFileUpload = async (files: FileList | null) => {
    if (!files || !showDetail) return
    setUploading(true)
    try {
      for (const file of Array.from(files)) {
        const formData = new FormData()
        formData.append('file', file)
        formData.append('tipo', uploadTipo)
        await api.post(`/demandas/${showDetail.id}/documentos`, formData, {
          headers: { 'Content-Type': 'multipart/form-data' }
        })
      }
      fetchDetailDocs(showDetail.id)
      setDocCounts(prev => ({ ...prev, [showDetail.id]: (prev[showDetail.id] || 0) + files.length }))
    } catch (err) {
      alert('Erro ao fazer upload')
    } finally {
      setUploading(false)
    }
  }

  const handleDocDownload = (doc: DocumentoFile) => {
    window.open(`/api/documentos/${doc.id}/download`, '_blank')
  }

  const handleDocDelete = async (doc: DocumentoFile) => {
    if (!confirm(`Excluir ${doc.nome_arquivo}?`)) return
    try {
      await api.delete(`/documentos/${doc.id}`)
      if (showDetail) {
        fetchDetailDocs(showDetail.id)
        setDocCounts(prev => ({ ...prev, [showDetail.id]: Math.max(0, (prev[showDetail.id] || 1) - 1) }))
      }
    } catch { alert('Erro ao excluir documento') }
  }

  const handleDrop = useCallback((e: React.DragEvent) => {
    e.preventDefault()
    setDragOver(false)
    handleFileUpload(e.dataTransfer.files)
  }, [showDetail, uploadTipo])

  const formatDate = (dateStr?: string | null) => {
    if (!dateStr) return '-'
    try { return new Date(dateStr).toLocaleDateString('pt-BR') } catch { return '-' }
  }

  const formatFileSize = (bytes: number) => {
    if (bytes < 1024) return `${bytes} B`
    if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
    return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
  }

  const formatCurrency = (v: number | null | undefined) => {
    if (v == null) return '-'
    return new Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(v)
  }

  const getCriticidade = (d: Demanda) => d.criticidade || d.prioridade || ''
  const topStatuses = ['aberta', 'em_cotacao', 'em_aprovacao', 'em_execucao']

  const openDetail = (d: Demanda) => {
    setShowDetail(d)
    setShowOS(false)
    fetchDetailDocs(d.id)
    fetchDetailOS(d.id)
  }

  if (loading || lookupsLoading) {
    return <div className="flex items-center justify-center h-96"><Loader2 className="w-8 h-8 animate-spin text-primary" /></div>
  }

  return (
    <div className="space-y-6 animate-fade-in">
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <h1 className="text-2xl sm:text-3xl font-bold text-text">Demandas</h1>
          <p className="text-gray mt-1">Gerencie as solicitações de facilities</p>
        </div>
        <button onClick={openNew} className="btn-primary flex items-center gap-2 w-full sm:w-auto justify-center">
          <Plus className="w-5 h-5" />Nova Demanda
        </button>
      </div>

      <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
        {topStatuses.map((key) => {
          const config = statusConfig[key]
          if (!config) return null
          const count = demandas.filter(d => d.status === key).length
          return (
            <button key={key} onClick={() => setFilterStatus(filterStatus === key ? 'todos' : key)}
              className={`card text-left transition-all ${filterStatus === key ? 'ring-2 ring-primary' : ''}`}>
              <div className="flex items-center gap-2 mb-2">{config.icon}<span className="text-sm text-gray">{config.label}</span></div>
              <p className="text-2xl font-bold text-text">{count}</p>
            </button>
          )
        })}
      </div>

      <div className="card">
        <div className="flex flex-col sm:flex-row gap-4">
          <div className="flex-1 relative">
            <Search className="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-light" />
            <input type="text" placeholder="Buscar demandas..." value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)} className="input-field pl-12" />
          </div>
          <div className="relative">
            <select value={filterStatus} onChange={(e) => setFilterStatus(e.target.value)} className="input-field appearance-none pr-10 w-full sm:w-48">
              <option value="todos">Todos os status</option>
              {Object.entries(statusConfig).map(([key, config]) => (<option key={key} value={key}>{config.label}</option>))}
            </select>
            <ChevronDown className="absolute right-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray pointer-events-none" />
          </div>
        </div>
      </div>

      <div className="grid gap-4">
        {filteredDemandas.map((demanda) => {
          const crit = getCriticidade(demanda)
          const docsCount = docCounts[demanda.id] || 0
          return (
            <div key={demanda.id} className="card hover:shadow-md transition-all">
              <div className="flex flex-col sm:flex-row sm:items-center gap-4">
                <div className="flex-1 min-w-0">
                  <div className="flex items-start gap-3">
                    <div className="w-12 h-12 rounded-xl bg-primary/10 flex items-center justify-center flex-shrink-0">
                      <FileText className="w-6 h-6 text-primary" />
                    </div>
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2 flex-wrap">
                        <h3 className="font-semibold text-text">{demanda.numero ? `#${demanda.numero} - ` : ''}{demanda.titulo}</h3>
                        <span className={`${statusConfig[demanda.status]?.class || 'badge-neutral'} flex items-center gap-1`}>
                          {statusConfig[demanda.status]?.icon}{statusConfig[demanda.status]?.label || demanda.status}
                        </span>
                        {crit && <span className={`badge ${criticidadeConfig[crit]?.class || ''}`}>{criticidadeConfig[crit]?.label || crit}</span>}
                      </div>
                      <p className="text-gray text-sm mt-1 line-clamp-1">{demanda.descricao}</p>
                      <div className="flex items-center gap-4 mt-2 text-xs text-gray-light flex-wrap">
                        {demanda.categoria_id && <span>Cat: {categoriaMap[demanda.categoria_id] || '-'}</span>}
                        {demanda.subcategoria_id && <span>Sub: {subcategoriaMap[demanda.subcategoria_id] || '-'}</span>}
                        {demanda.local_id && <span>Local: {locaisMap[demanda.local_id] || '-'}</span>}
                        {demanda.centro_custo_id && <span>CC: {centrosCustoMap[demanda.centro_custo_id] || '-'}</span>}
                        {demanda.valor_estimado && <span className="flex items-center gap-1"><DollarSign className="w-3 h-3" />{formatCurrency(demanda.valor_estimado)}</span>}
                        {demanda.data_desejada && <span>🗓️ {formatDate(demanda.data_desejada)}</span>}
                        <span>{formatDate(demanda.created_at || demanda.data_criacao)}</span>
                        {docsCount > 0 && <span className="flex items-center gap-1"><Paperclip className="w-3 h-3" />{docsCount}</span>}
                      </div>
                    </div>
                  </div>
                </div>
                <div className="flex items-center gap-2 sm:flex-shrink-0">
                  <button onClick={() => openDetail(demanda)} className="p-2 rounded-lg hover:bg-gray-100 text-gray hover:text-primary transition-colors"><Eye className="w-5 h-5" /></button>
                  <button onClick={() => openEdit(demanda)} className="p-2 rounded-lg hover:bg-gray-100 text-gray hover:text-primary transition-colors"><Edit2 className="w-5 h-5" /></button>
                  <button onClick={() => handleDelete(demanda.id)} className="p-2 rounded-lg hover:bg-red-50 text-gray hover:text-red-500 transition-colors"><Trash2 className="w-5 h-5" /></button>
                </div>
              </div>
            </div>
          )
        })}
        {filteredDemandas.length === 0 && (
          <div className="card text-center py-12"><FileText className="w-12 h-12 text-gray-light mx-auto mb-4" /><p className="text-gray">Nenhuma demanda encontrada</p></div>
        )}
      </div>

      {/* Create/Edit Modal */}
      <Modal open={showModal} onClose={() => setShowModal(false)} title={editId ? 'Editar Demanda' : 'Nova Demanda'} onSubmit={handleSubmit} submitLabel={editId ? 'Salvar' : 'Criar Demanda'} loading={saving}>
        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
          <div className="sm:col-span-2">
            <label className="block text-sm font-medium text-text mb-2">Título</label>
            <input type="text" value={form.titulo} onChange={(e) => setForm({ ...form, titulo: e.target.value })} className="input-field" placeholder="Título da demanda" required />
          </div>
          <div className="sm:col-span-2">
            <label className="block text-sm font-medium text-text mb-2">Descrição</label>
            <textarea value={form.descricao} onChange={(e) => setForm({ ...form, descricao: e.target.value })} className="input-field resize-none" rows={3} placeholder="Descreva a demanda..." required />
          </div>
          <div>
            <label className="block text-sm font-medium text-text mb-2">Criticidade</label>
            <select value={form.criticidade} onChange={(e) => setForm({ ...form, criticidade: e.target.value })} className="input-field">
              <option value="baixa">Baixa</option><option value="media">Média</option><option value="alta">Alta</option><option value="urgente">Urgente</option>
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-text mb-2">Categoria</label>
            <select value={form.categoria_id} onChange={(e) => handleCategoriaChange(e.target.value)} className="input-field">
              <option value="">Selecione...</option>
              {categorias.map(c => <option key={c.id} value={c.id}>{c.nome}</option>)}
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-text mb-2">Subcategoria</label>
            <select value={form.subcategoria_id} onChange={(e) => setForm({ ...form, subcategoria_id: e.target.value })} className="input-field" disabled={!form.categoria_id}>
              <option value="">Selecione...</option>
              {subcategorias.map(s => <option key={s.id} value={s.id}>{s.nome}</option>)}
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-text mb-2">Data Desejada</label>
            <input type="date" value={form.data_desejada} onChange={(e) => setForm({ ...form, data_desejada: e.target.value })} className="input-field" />
          </div>
          <div>
            <label className="block text-sm font-medium text-text mb-2">Local</label>
            <select value={form.local_id} onChange={(e) => setForm({ ...form, local_id: e.target.value })} className="input-field">
              <option value="">Selecione...</option>
              {locais.map(l => <option key={l.id} value={l.id}>{l.nome}</option>)}
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-text mb-2">Centro de Custo</label>
            <select value={form.centro_custo_id} onChange={(e) => setForm({ ...form, centro_custo_id: e.target.value })} className="input-field">
              <option value="">Selecione...</option>
              {centrosCusto.map(c => <option key={c.id} value={c.id}>{c.nome}</option>)}
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-text mb-2">Valor Estimado (R$)</label>
            <input type="number" step="0.01" value={form.valor_estimado} onChange={(e) => setForm({ ...form, valor_estimado: e.target.value })} className="input-field" placeholder="0,00" />
          </div>
          <div className="sm:col-span-2 border-t border-border pt-3 mt-2">
            <p className="text-sm font-semibold mb-3" style={{ color: '#1A7A4C' }}>🌿 Campos ESG</p>
          </div>
          <div>
            <label className="block text-sm font-medium text-text mb-2">Impacto Ambiental</label>
            <select value={form.impacto_ambiental_demanda} onChange={(e) => setForm({ ...form, impacto_ambiental_demanda: e.target.value })} className="input-field">
              <option value="">Herdar da Categoria</option>
              <option value="Baixo">Baixo</option>
              <option value="Médio">Médio</option>
              <option value="Alto">Alto</option>
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-text mb-2">Justificativa Emergencial</label>
            <textarea value={form.justificativa_manutencao_emergencial} onChange={(e) => setForm({ ...form, justificativa_manutencao_emergencial: e.target.value })} className="input-field resize-none" rows={2} placeholder="Obrigatório para manutenção emergencial..." />
          </div>
        </div>
      </Modal>

      {/* Detail Modal */}
      <Modal open={!!showDetail} onClose={() => { setShowDetail(null); setDetailDocs([]); setDetailOS([]) }} title={`Demanda #${showDetail?.numero || ''}`}>
        {showDetail && (
          <>
            <div><strong>Título:</strong> {showDetail.titulo}</div>
            <div><strong>Descrição:</strong> {showDetail.descricao}</div>
            <div><strong>Status:</strong> {statusConfig[showDetail.status]?.label || showDetail.status}</div>
            <div><strong>Criticidade:</strong> {criticidadeConfig[getCriticidade(showDetail)]?.label || getCriticidade(showDetail)}</div>
            <div><strong>Categoria:</strong> {categoriaMap[showDetail.categoria_id] || '-'}</div>
            <div><strong>Subcategoria:</strong> {subcategoriaMap[showDetail.subcategoria_id] || '-'}</div>
            <div><strong>Local:</strong> {locaisMap[showDetail.local_id] || '-'}</div>
            <div><strong>Centro de Custo:</strong> {centrosCustoMap[showDetail.centro_custo_id] || '-'}</div>
            <div><strong>Data Desejada:</strong> {formatDate(showDetail.data_desejada)}</div>
            <div><strong>Valor Estimado:</strong> {formatCurrency(showDetail.valor_estimado)}</div>
            <div><strong>Data de Criação:</strong> {formatDate(showDetail.created_at)}</div>
            {/* ESG Info */}
            {((showDetail as any).impacto_ambiental_demanda || (showDetail as any).justificativa_manutencao_emergencial) && (
              <div className="border-t border-border pt-3 mt-3">
                <p className="text-sm font-semibold mb-2" style={{ color: '#1A7A4C' }}>🌿 ESG</p>
                {(showDetail as any).impacto_ambiental_demanda && (
                  <div><strong>Impacto Ambiental:</strong>{' '}
                    <span className={`badge ${(showDetail as any).impacto_ambiental_demanda === 'Alto' ? 'badge-error' : (showDetail as any).impacto_ambiental_demanda === 'Médio' ? 'badge-warning' : 'badge-success'}`}>
                      {(showDetail as any).impacto_ambiental_demanda}
                    </span>
                  </div>
                )}
                {(showDetail as any).justificativa_manutencao_emergencial && (
                  <div className="mt-2"><strong>Justificativa Emergencial:</strong> {(showDetail as any).justificativa_manutencao_emergencial}</div>
                )}
              </div>
            )}

            {/* Ordens de Serviço Section */}
            <div className="border-t border-border pt-4 mt-4">
              <button onClick={() => setShowOS(!showOS)} className="font-semibold text-text mb-3 flex items-center gap-2 hover:text-primary transition-colors">
                <ClipboardList className="w-4 h-4" /> Ordens de Serviço ({detailOS.length})
                <ChevronDown className={`w-4 h-4 transition-transform ${showOS ? 'rotate-180' : ''}`} />
              </button>
              {showOS && (
                osLoading ? (
                  <div className="flex justify-center py-4"><Loader2 className="w-5 h-5 animate-spin text-gray" /></div>
                ) : detailOS.length === 0 ? (
                  <p className="text-sm text-gray text-center py-2">Nenhuma OS vinculada</p>
                ) : (
                  <div className="space-y-2">
                    {detailOS.map(os => (
                      <div key={os.id} className="flex items-center gap-3 p-3 rounded-lg bg-gray-50 hover:bg-gray-100 transition-colors">
                        <ClipboardList className="w-5 h-5 text-secondary" />
                        <div className="flex-1 min-w-0">
                          <p className="text-sm font-medium text-text">OS-{String(os.numero).padStart(4, '0')}</p>
                          <p className="text-xs text-gray">{fornecedoresMap[os.fornecedor_id] || '-'} · {formatCurrency(os.valor)}</p>
                        </div>
                        <span className={`${osStatusConfig[os.status]?.class || 'badge-neutral'} text-xs`}>
                          {osStatusConfig[os.status]?.label || os.status}
                        </span>
                        {os.status === 'emitida' && (
                          <button onClick={() => handleChangeOSStatus(os.id, 'em_cotacao')} className="text-xs btn-primary !py-1 !px-2">
                            → Em Cotação
                          </button>
                        )}
                      </div>
                    ))}
                  </div>
                )
              )}
            </div>

            {/* Documents Section */}
            <div className="border-t border-border pt-4 mt-4">
              <h3 className="font-semibold text-text mb-3 flex items-center gap-2">
                <Paperclip className="w-4 h-4" /> Documentos
              </h3>

              <div
                className={`border-2 border-dashed rounded-xl p-4 text-center transition-colors mb-3 ${dragOver ? 'border-primary bg-primary/5' : 'border-gray-300'}`}
                onDragOver={(e) => { e.preventDefault(); setDragOver(true) }}
                onDragLeave={() => setDragOver(false)}
                onDrop={handleDrop}
              >
                <div className="flex items-center justify-center gap-3 mb-2">
                  <select value={uploadTipo} onChange={(e) => setUploadTipo(e.target.value)} className="input-field w-auto text-sm py-1">
                    <option value="planta">📋 Planta</option>
                    <option value="foto">📸 Foto</option>
                    <option value="laudo">📄 Laudo</option>
                    <option value="outro">📎 Outro</option>
                  </select>
                  <button onClick={() => fileInputRef.current?.click()} disabled={uploading}
                    className="btn-primary text-sm py-1 px-3 flex items-center gap-1">
                    {uploading ? <Loader2 className="w-4 h-4 animate-spin" /> : <Upload className="w-4 h-4" />}
                    {uploading ? 'Enviando...' : 'Upload'}
                  </button>
                </div>
                <p className="text-xs text-gray">Arraste arquivos aqui ou clique no botão</p>
                <input ref={fileInputRef} type="file" multiple className="hidden"
                  onChange={(e) => handleFileUpload(e.target.files)} />
              </div>

              {docsLoading ? (
                <div className="flex justify-center py-4"><Loader2 className="w-5 h-5 animate-spin text-gray" /></div>
              ) : detailDocs.length === 0 ? (
                <p className="text-sm text-gray text-center py-2">Nenhum documento anexado</p>
              ) : (
                <div className="space-y-2">
                  {detailDocs.map(doc => (
                    <div key={doc.id} className="flex items-center gap-3 p-2 rounded-lg bg-gray-50 hover:bg-gray-100 transition-colors">
                      <span className="text-lg">{tipoDocIcon[doc.tipo] || '📎'}</span>
                      <div className="flex-1 min-w-0">
                        <p className="text-sm font-medium text-text truncate">{doc.nome_arquivo}</p>
                        <p className="text-xs text-gray">{formatFileSize(doc.tamanho)} · {formatDate(doc.created_at)}</p>
                      </div>
                      <button onClick={() => handleDocDownload(doc)} className="p-1 rounded hover:bg-white text-gray hover:text-primary">
                        <Download className="w-4 h-4" />
                      </button>
                      <button onClick={() => handleDocDelete(doc)} className="p-1 rounded hover:bg-white text-gray hover:text-red-500">
                        <Trash2 className="w-4 h-4" />
                      </button>
                    </div>
                  ))}
                </div>
              )}
            </div>
          </>
        )}
      </Modal>
    </div>
  )
}
