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

const statusConfig: Record<string, { label: string; class: string; icon: React.ReactNode }> = {
  'pendente': { label: 'Pendente', class: 'badge-warning', icon: <Clock className="w-3 h-3" /> },
  'emitida': { label: 'Emitida', class: 'badge-warning', icon: <Clock className="w-3 h-3" /> },
  'em_cotacao': { label: 'Em Cotação', class: 'badge-info', icon: <AlertCircle className="w-3 h-3" /> },
  'em_andamento': { label: 'Em Andamento', class: 'badge-info', icon: <PlayCircle className="w-3 h-3" /> },
  'em_execucao': { label: 'Em Execução', class: 'badge-info', icon: <PlayCircle className="w-3 h-3" /> },
  'aguardando_aprovacao': { label: 'Aguard. Aprovação', class: 'badge-warning', icon: <AlertCircle className="w-3 h-3" /> },
  'concluida': { label: 'Concluída', class: 'badge-success', icon: <CheckCircle2 className="w-3 h-3" /> },
  'cancelada': { label: 'Cancelada', class: 'badge-error', icon: <AlertCircle className="w-3 h-3" /> },
}

const emptyForm = { fornecedor_id: '', valor: 0, observacoes: '', demanda_id: '', data: '', uso_material_sustentavel: '', gera_residuos: '', descarte_certificado: '' }

export default function OrdensServico() {
  const [loading, setLoading] = useState(true)
  const [ordens, setOrdens] = useState<OrdemServico[]>([])
  const [demandas, setDemandas] = useState<Demanda[]>([])
  const [searchTerm, setSearchTerm] = useState('')
  const [filterStatus, setFilterStatus] = useState('todos')
  const [filterDemanda, setFilterDemanda] = useState('')
  const [filterCategoria, setFilterCategoria] = useState('')
  const [filterFornecedor, setFilterFornecedor] = useState('')
  const [showModal, setShowModal] = useState(false)
  const [showDetail, setShowDetail] = useState<OrdemServico | null>(null)
  const [editId, setEditId] = useState<string | null>(null)
  const [form, setForm] = useState(emptyForm)
  const [saving, setSaving] = useState(false)
  // Documents
  const [detailDocs, setDetailDocs] = useState<DocumentoVersao[]>([])
  const [docsLoading, setDocsLoading] = useState(false)
  const [uploading, setUploading] = useState(false)
  const fileInputRef = useRef<HTMLInputElement>(null)

  const { fornecedoresMap, fornecedores, categoriaMap, categorias, loading: lookupsLoading } = useLookups()

  // Build demanda map
  const demandaMap: Record<string, string> = {}
  demandas.forEach(d => { demandaMap[d.id] = d.numero ? `#${d.numero} - ${d.titulo}` : d.titulo })

  // Build demanda->categoria map
  const demandaCategoriaMap: Record<string, string> = {}
  demandas.forEach(d => { demandaCategoriaMap[d.id] = d.categoria_id })

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

  const fetchOrdens = async () => {
    try {
      const { data } = await api.get('/ordens-servico')
      setOrdens(data)
    } catch (err) {
      console.error('Error fetching ordens:', err)
    } finally {
      setLoading(false)
    }
  }

  const fetchDemandas = async () => {
    try {
      const { data } = await api.get('/demandas')
      setDemandas(data)
    } catch {}
  }

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

  const getFornecedorNome = (o: OrdemServico) => o.fornecedor_nome || fornecedoresMap[o.fornecedor_id] || '-'

  const filteredOrdens = ordens.filter(ordem => {
    const num = typeof ordem.numero === 'number' ? `OS-${String(ordem.numero).padStart(4, '0')}` : (ordem.numero || '')
    const matchesSearch = num.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         (ordem.descricao || ordem.observacoes || '').toLowerCase().includes(searchTerm.toLowerCase()) ||
                         getFornecedorNome(ordem).toLowerCase().includes(searchTerm.toLowerCase())
    const matchesStatus = filterStatus === 'todos' || ordem.status === filterStatus
    const matchesDemanda = !filterDemanda || ordem.demanda_id === filterDemanda
    const matchesCategoria = !filterCategoria || demandaCategoriaMap[ordem.demanda_id] === filterCategoria
    const matchesFornecedor = !filterFornecedor || ordem.fornecedor_id === filterFornecedor
    return matchesSearch && matchesStatus && matchesDemanda && matchesCategoria && matchesFornecedor
  })

  const openNew = () => { setEditId(null); setForm(emptyForm); setShowModal(true) }

  const handleSubmit = async () => {
    setSaving(true)
    try {
      if (editId) {
        await api.patch(`/ordens-servico/${editId}`, form)
      } else {
        await api.post('/ordens-servico', { ...form, status: 'emitida' })
      }
      setShowModal(false)
      fetchOrdens()
    } catch (err) {
      console.error('Error saving:', err)
      alert('Erro ao salvar OS')
    } finally {
      setSaving(false)
    }
  }

  const handleDelete = async (id: string) => {
    if (!confirm('Tem certeza que deseja excluir esta OS?')) return
    try { await api.delete(`/ordens-servico/${id}`); fetchOrdens() } catch { alert('Erro ao excluir') }
  }

  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)
        if (showDetail.fornecedor_id) formData.append('fornecedor_id', showDetail.fornecedor_id)
        await api.post(`/ordens-servico/${showDetail.id}/documentos`, formData, {
          headers: { 'Content-Type': 'multipart/form-data' }
        })
      }
      fetchDetailDocs(showDetail.id)
    } catch (err) {
      alert('Erro ao fazer upload')
    } finally {
      setUploading(false)
    }
  }

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

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

  const openDetail = (o: OrdemServico) => {
    setShowDetail(o)
    fetchDetailDocs(o.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">Ordens de Serviço</h1>
          <p className="text-gray mt-1">Acompanhe todas as ordens de serviço</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 OS
        </button>
      </div>

      <div className="grid grid-cols-2 sm:grid-cols-4 lg:grid-cols-7 gap-4">
        {Object.entries(statusConfig).map(([key, config]) => {
          const count = ordens.filter(o => o.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-xs text-gray truncate">{config.label}</span></div>
              <p className="text-xl font-bold text-text">{count}</p>
            </button>
          )
        })}
      </div>

      <div className="card">
        <div className="flex flex-col gap-4">
          <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 por número, descrição ou fornecedor..." 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 className="flex flex-col sm:flex-row gap-4">
            <select value={filterDemanda} onChange={(e) => setFilterDemanda(e.target.value)} className="input-field sm:w-60">
              <option value="">Todas as Demandas</option>
              {demandas.map(d => <option key={d.id} value={d.id}>{d.numero ? `#${d.numero}` : ''} {d.titulo}</option>)}
            </select>
            <select value={filterCategoria} onChange={(e) => setFilterCategoria(e.target.value)} className="input-field sm:w-48">
              <option value="">Todas Categorias</option>
              {categorias.map(c => <option key={c.id} value={c.id}>{c.nome}</option>)}
            </select>
            <select value={filterFornecedor} onChange={(e) => setFilterFornecedor(e.target.value)} className="input-field sm:w-48">
              <option value="">Todos Fornecedores</option>
              {fornecedores.map(f => <option key={f.id} value={f.id}>{f.nome}</option>)}
            </select>
          </div>
        </div>
      </div>

      <div className="card !p-0 overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="table-header">
              <tr>
                <th className="table-cell">Número</th>
                <th className="table-cell">Demanda</th>
                <th className="table-cell">Fornecedor</th>
                <th className="table-cell text-right">Valor</th>
                <th className="table-cell">Data</th>
                <th className="table-cell text-center">Status</th>
                <th className="table-cell text-center">Ações</th>
              </tr>
            </thead>
            <tbody>
              {filteredOrdens.map((ordem) => (
                <tr key={ordem.id} className="table-row">
                  <td className="table-cell">
                    <div className="flex items-center gap-3">
                      <div className="w-10 h-10 rounded-lg bg-secondary/10 flex items-center justify-center">
                        <ClipboardList className="w-5 h-5 text-secondary" />
                      </div>
                      <span className="font-mono font-semibold text-primary">{typeof ordem.numero === 'number' ? `OS-${String(ordem.numero).padStart(4, '0')}` : ordem.numero}</span>
                    </div>
                  </td>
                  <td className="table-cell"><span className="line-clamp-1 text-sm">{demandaMap[ordem.demanda_id] || '-'}</span></td>
                  <td className="table-cell">
                    <div className="flex items-center gap-2"><Building2 className="w-4 h-4 text-gray" /><span>{getFornecedorNome(ordem)}</span></div>
                  </td>
                  <td className="table-cell text-right font-medium">{ordem.valor ? formatCurrency(ordem.valor) : '-'}</td>
                  <td className="table-cell">
                    <div className="flex items-center gap-2"><Calendar className="w-4 h-4 text-gray" /><span>{formatDate(ordem.data || ordem.data_criacao || ordem.created_at)}</span></div>
                  </td>
                  <td className="table-cell text-center">
                    <span className={`${statusConfig[ordem.status]?.class || 'badge-neutral'} inline-flex items-center gap-1`}>
                      {statusConfig[ordem.status]?.icon}{statusConfig[ordem.status]?.label || ordem.status}
                    </span>
                  </td>
                  <td className="table-cell">
                    <div className="flex items-center justify-center gap-1">
                      <button onClick={() => openDetail(ordem)} className="p-2 rounded-lg hover:bg-gray-100 text-gray hover:text-primary transition-colors"><Eye className="w-4 h-4" /></button>
                      <button onClick={() => handleDelete(ordem.id)} className="p-2 rounded-lg hover:bg-red-50 text-gray hover:text-red-500 transition-colors"><Trash2 className="w-4 h-4" /></button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        {filteredOrdens.length === 0 && (
          <div className="text-center py-12"><ClipboardList className="w-12 h-12 text-gray-light mx-auto mb-4" /><p className="text-gray">Nenhuma ordem de serviço encontrada</p></div>
        )}
      </div>

      {/* Create Modal */}
      <Modal open={showModal} onClose={() => setShowModal(false)} title="Nova Ordem de Serviço" onSubmit={handleSubmit} submitLabel="Criar OS" loading={saving}>
        <div>
          <label className="block text-sm font-medium text-text mb-2">Demanda</label>
          <select value={form.demanda_id} onChange={(e) => setForm({ ...form, demanda_id: e.target.value })} className="input-field">
            <option value="">Selecione...</option>
            {demandas.map(d => <option key={d.id} value={d.id}>{d.numero ? `#${d.numero}` : ''} {d.titulo}</option>)}
          </select>
        </div>
        <div>
          <label className="block text-sm font-medium text-text mb-2">Fornecedor</label>
          <select value={form.fornecedor_id} onChange={(e) => setForm({ ...form, fornecedor_id: e.target.value })} className="input-field" required>
            <option value="">Selecione...</option>
            {fornecedores.map(f => <option key={f.id} value={f.id}>{f.nome}</option>)}
          </select>
        </div>
        <div>
          <label className="block text-sm font-medium text-text mb-2">Data</label>
          <input type="date" value={form.data} onChange={(e) => setForm({ ...form, data: e.target.value })} className="input-field" />
        </div>
        <div>
          <label className="block text-sm font-medium text-text mb-2">Valor</label>
          <input type="number" step="0.01" value={form.valor} onChange={(e) => setForm({ ...form, valor: Number(e.target.value) })} className="input-field" />
        </div>
        <div>
          <label className="block text-sm font-medium text-text mb-2">Observações</label>
          <textarea value={form.observacoes} onChange={(e) => setForm({ ...form, observacoes: e.target.value })} className="input-field resize-none" rows={3} />
        </div>
        <div className="col-span-full 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">Material Sustentável</label>
          <select value={form.uso_material_sustentavel} onChange={e => setForm({ ...form, uso_material_sustentavel: e.target.value })} className="input-field">
            <option value="">Não Informado</option>
            <option value="Sim">Sim</option>
            <option value="Não">Não</option>
          </select>
        </div>
        <div>
          <label className="block text-sm font-medium text-text mb-2">Geração de Resíduos</label>
          <select value={form.gera_residuos} onChange={e => setForm({ ...form, gera_residuos: e.target.value })} className="input-field">
            <option value="">Não Informado</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">Descarte Certificado</label>
          <select value={form.descarte_certificado} onChange={e => setForm({ ...form, descarte_certificado: e.target.value })} className="input-field">
            <option value="">Não Informado</option>
            <option value="Sim">Sim</option>
            <option value="Não">Não</option>
          </select>
        </div>
      </Modal>

      {/* Detail Modal */}
      <Modal open={!!showDetail} onClose={() => { setShowDetail(null); setDetailDocs([]) }} title={`OS ${showDetail ? (typeof showDetail.numero === 'number' ? `OS-${String(showDetail.numero).padStart(4, '0')}` : showDetail.numero) : ''}`}>
        {showDetail && (
          <>
            <div className="grid grid-cols-2 gap-3">
              <div><strong>Demanda:</strong> {demandaMap[showDetail.demanda_id] || '-'}</div>
              <div><strong>Fornecedor:</strong> {getFornecedorNome(showDetail)}</div>
              <div><strong>Valor:</strong> {formatCurrency(showDetail.valor)}</div>
              <div><strong>Status:</strong> {statusConfig[showDetail.status]?.label || showDetail.status}</div>
              <div><strong>Data:</strong> {formatDate(showDetail.data)}</div>
              <div><strong>Data Início:</strong> {formatDate(showDetail.data_inicio)}</div>
              <div><strong>Data Conclusão:</strong> {formatDate(showDetail.data_conclusao)}</div>
            </div>
            <div><strong>Observações:</strong> {showDetail.observacoes || '-'}</div>

            {/* ESG */}
            {((showDetail as any).uso_material_sustentavel || (showDetail as any).gera_residuos || (showDetail as any).descarte_certificado) && (
              <div className="border-t border-border pt-4 mt-4">
                <h3 className="font-semibold mb-3" style={{ color: '#1A7A4C' }}>🌿 Dados ESG</h3>
                <div className="grid grid-cols-3 gap-3 text-sm">
                  <div><strong>Material Sustentável:</strong> {(showDetail as any).uso_material_sustentavel || 'Não Informado'}</div>
                  <div><strong>Geração Resíduos:</strong> {(showDetail as any).gera_residuos || 'Não Informado'}</div>
                  <div><strong>Descarte Certificado:</strong> {(showDetail as any).descarte_certificado || 'Não Informado'}</div>
                </div>
              </div>
            )}

            {/* Proposal Data */}
            {(showDetail.valor_bruto || showDetail.valor_liquido) && (
              <div className="border-t border-border pt-4 mt-4">
                <h3 className="font-semibold text-text mb-3">Dados da Proposta</h3>
                <div className="grid grid-cols-2 gap-3 text-sm">
                  <div><strong>Valor Bruto:</strong> {formatCurrency(showDetail.valor_bruto)}</div>
                  <div><strong>Valor Líquido:</strong> {formatCurrency(showDetail.valor_liquido)}</div>
                  <div><strong>ISS:</strong> {formatCurrency(showDetail.iss)}</div>
                  <div><strong>INSS:</strong> {formatCurrency(showDetail.inss)}</div>
                  <div><strong>PCC:</strong> {formatCurrency(showDetail.pcc)}</div>
                  <div><strong>Cond. Pagamento:</strong> {showDetail.condicao_pagamento || '-'}</div>
                  <div><strong>Prazo Execução:</strong> {showDetail.prazo_execucao || '-'}</div>
                  <div><strong>Data Est. Entrega:</strong> {formatDate(showDetail.data_estimada_entrega)}</div>
                </div>
              </div>
            )}

            {/* Document Versioning */}
            <div className="border-t border-border pt-4 mt-4">
              <h3 className="font-semibold text-text mb-3 flex items-center gap-2">
                <FileText className="w-4 h-4" /> Documentos (PDF)
              </h3>
              <div className="flex items-center gap-3 mb-3">
                <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 PDF'}
                </button>
                <input ref={fileInputRef} type="file" accept=".pdf" 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="p-3 rounded-lg bg-gray-50 hover:bg-gray-100 transition-colors">
                      <div className="flex items-center gap-3">
                        <FileText className="w-5 h-5 text-red-500" />
                        <div className="flex-1 min-w-0">
                          <div className="flex items-center gap-2">
                            <p className="text-sm font-medium text-text truncate">{doc.nome_arquivo}</p>
                            <span className="badge badge-info text-xs">V{doc.versao}</span>
                          </div>
                          <p className="text-xs text-gray">
                            {fornecedoresMap[doc.fornecedor_id] || ''} · {(doc.tamanho / 1024).toFixed(1)} KB · {formatDate(doc.created_at)}
                          </p>
                        </div>
                        <a href={`/api/ordens-servico/documentos/${doc.id}/download`} target="_blank" className="p-1 rounded hover:bg-white text-gray hover:text-primary">
                          <Download className="w-4 h-4" />
                        </a>
                      </div>
                      {(doc.valor_bruto || doc.valor_liquido) && (
                        <div className="mt-2 grid grid-cols-3 gap-2 text-xs text-gray">
                          <span>Bruto: {formatCurrency(doc.valor_bruto)}</span>
                          <span>Líquido: {formatCurrency(doc.valor_liquido)}</span>
                          <span>ISS: {formatCurrency(doc.iss)}</span>
                        </div>
                      )}
                    </div>
                  ))}
                </div>
              )}
            </div>
          </>
        )}
      </Modal>
    </div>
  )
}
