import { useState, useEffect } from 'react'
import { 
  Building2, Search, Plus, Eye, Edit2, Trash2, Loader2,
  Mail, Phone, MapPin, Star, CheckCircle2, XCircle, X
} from 'lucide-react'
import api from '../services/api'
import { Fornecedor } from '../types'
import Modal from '../components/Modal'

const emptyForm = { razao_social: '', nome_fantasia: '', cpf_cnpj: '', email: '', telefone: '', tipo_pessoa: 'PJ', nome_contato: '', possui_politica_ambiental: false, possui_politica_sst: false, declara_uso_epi: false, equipe_treinada: false, classificacao_esg: '' }

export default function Fornecedores() {
  const [loading, setLoading] = useState(true)
  const [fornecedores, setFornecedores] = useState<Fornecedor[]>([])
  const [searchTerm, setSearchTerm] = useState('')
  const [filterAtivo, setFilterAtivo] = useState('todos')
  const [selectedFornecedor, setSelectedFornecedor] = useState<Fornecedor | null>(null)
  const [showCreateModal, setShowCreateModal] = useState(false)
  const [editId, setEditId] = useState<string | null>(null)
  const [form, setForm] = useState(emptyForm)
  const [saving, setSaving] = useState(false)

  useEffect(() => { fetchFornecedores() }, [])

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

  const filteredFornecedores = fornecedores.filter(forn => {
    const nome = forn.razao_social || forn.nome_fantasia || ''
    const doc = forn.cpf_cnpj || forn.cnpj || ''
    const matchesSearch = nome.toLowerCase().includes(searchTerm.toLowerCase()) || doc.includes(searchTerm)
    const matchesAtivo = filterAtivo === 'todos' || (filterAtivo === 'ativos' && forn.ativo) || (filterAtivo === 'inativos' && !forn.ativo)
    return matchesSearch && matchesAtivo
  })

  const openNew = () => { setEditId(null); setForm(emptyForm); setShowCreateModal(true) }
  const openEdit = (f: Fornecedor) => {
    setEditId(f.id)
    setForm({ razao_social: f.razao_social || '', nome_fantasia: f.nome_fantasia || '', cpf_cnpj: f.cpf_cnpj || f.cnpj || '', email: f.email || '', telefone: f.telefone || '', tipo_pessoa: f.tipo_pessoa || 'PJ', nome_contato: (f as any).nome_contato || '', possui_politica_ambiental: f.possui_politica_ambiental || false, possui_politica_sst: f.possui_politica_sst || false, declara_uso_epi: f.declara_uso_epi || false, equipe_treinada: f.equipe_treinada || false, classificacao_esg: f.classificacao_esg || '' })
    setShowCreateModal(true)
  }

  const handleSubmit = async () => {
    setSaving(true)
    try {
      if (editId) {
        await api.patch(`/fornecedores/${editId}`, form)
      } else {
        await api.post('/fornecedores', form)
      }
      setShowCreateModal(false)
      fetchFornecedores()
    } catch (err) {
      console.error('Error saving:', err)
      alert('Erro ao salvar fornecedor')
    } finally {
      setSaving(false)
    }
  }

  const handleDelete = async (id: string) => {
    if (!confirm('Tem certeza que deseja excluir este fornecedor?')) return
    try { 
      await api.delete(`/fornecedores/${id}`); 
      fetchFornecedores() 
    } catch (err: any) { 
      const msg = err.response?.data?.message || 'Erro ao excluir'
      alert(msg)
    }
  }

  const getEspecialidades = (f: Fornecedor) => f.categorias_atendidas || f.especialidades || []
  const getRating = (f: Fornecedor) => f.rating ?? f.avaliacao ?? 0
  const getDoc = (f: Fornecedor) => f.cpf_cnpj || f.cnpj || ''

  const renderStars = (rating: number = 0) => (
    <div className="flex items-center gap-1">
      {[1, 2, 3, 4, 5].map((star) => (
        <Star key={star} className={`w-4 h-4 ${star <= rating ? 'text-amber-400 fill-amber-400' : 'text-gray-300'}`} />
      ))}
      <span className="text-sm text-gray ml-1">{rating?.toFixed(1)}</span>
    </div>
  )

  if (loading) {
    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">Fornecedores</h1>
          <p className="text-gray mt-1">Gerencie os fornecedores parceiros</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" />Novo Fornecedor
        </button>
      </div>

      <div className="grid grid-cols-3 gap-4">
        <div className="card"><p className="text-gray text-sm">Total</p><p className="text-2xl font-bold text-text">{fornecedores.length}</p></div>
        <div className="card"><p className="text-gray text-sm">Ativos</p><p className="text-2xl font-bold text-green-600">{fornecedores.filter(f => f.ativo).length}</p></div>
        <div className="card"><p className="text-gray text-sm">Inativos</p><p className="text-2xl font-bold text-gray">{fornecedores.filter(f => !f.ativo).length}</p></div>
      </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 por nome ou CNPJ..." value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)} className="input-field pl-12" />
          </div>
          <div className="flex gap-2">
            {['todos', 'ativos', 'inativos'].map((filter) => (
              <button key={filter} onClick={() => setFilterAtivo(filter)}
                className={`px-4 py-2 rounded-xl text-sm font-medium transition-all ${filterAtivo === filter ? 'bg-primary text-white' : 'bg-gray-100 text-gray hover:bg-gray-200'}`}>
                {filter.charAt(0).toUpperCase() + filter.slice(1)}
              </button>
            ))}
          </div>
        </div>
      </div>

      <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-4">
        {filteredFornecedores.map((fornecedor) => (
          <div key={fornecedor.id} className="card hover:shadow-lg transition-all cursor-pointer" onClick={() => setSelectedFornecedor(fornecedor)}>
            <div className="flex items-start justify-between mb-4">
              <div className="w-12 h-12 rounded-xl bg-gradient-to-br from-secondary/10 to-secondary/20 flex items-center justify-center">
                <Building2 className="w-6 h-6 text-secondary" />
              </div>
              <span className={`badge ${fornecedor.ativo ? 'badge-success' : 'badge-neutral'}`}>{fornecedor.ativo ? 'Ativo' : 'Inativo'}</span>
            </div>
            <h3 className="font-semibold text-text mb-1">{fornecedor.razao_social || fornecedor.nome_fantasia}</h3>
            <p className="text-sm text-gray mb-3">{getDoc(fornecedor)}</p>
            {renderStars(getRating(fornecedor))}
            {fornecedor.classificacao_esg && (
              <div className="mt-2">
                <span className={`text-xs px-2 py-1 rounded-lg font-medium ${fornecedor.classificacao_esg === 'Avançado' ? 'bg-green-100 text-green-700' : fornecedor.classificacao_esg === 'Intermediário' ? 'bg-amber-100 text-amber-700' : 'bg-red-100 text-red-700'}`}>
                  ESG: {fornecedor.classificacao_esg}
                </span>
              </div>
            )}
            {getEspecialidades(fornecedor).length > 0 && (
              <div className="flex flex-wrap gap-1 mt-3">
                {getEspecialidades(fornecedor).slice(0, 2).map((esp: string, i: number) => (
                  <span key={i} className="text-xs px-2 py-1 bg-primary/10 text-primary rounded-lg">{esp}</span>
                ))}
                {getEspecialidades(fornecedor).length > 2 && <span className="text-xs px-2 py-1 bg-gray-100 text-gray rounded-lg">+{getEspecialidades(fornecedor).length - 2}</span>}
              </div>
            )}
            <div className="flex items-center gap-2 mt-4 pt-4 border-t border-border">
              <button onClick={(e) => { e.stopPropagation(); setSelectedFornecedor(fornecedor) }} className="flex-1 btn-ghost !py-2 text-sm"><Eye className="w-4 h-4 mr-1 inline" />Ver</button>
              <button onClick={(e) => { e.stopPropagation(); openEdit(fornecedor) }} className="flex-1 btn-ghost !py-2 text-sm"><Edit2 className="w-4 h-4 mr-1 inline" />Editar</button>
              <button onClick={(e) => { e.stopPropagation(); handleDelete(fornecedor.id) }} className="flex-1 btn-ghost !py-2 text-sm text-red-500"><Trash2 className="w-4 h-4 mr-1 inline" />Excluir</button>
            </div>
          </div>
        ))}
        {filteredFornecedores.length === 0 && (
          <div className="col-span-full card text-center py-12"><Building2 className="w-12 h-12 text-gray-light mx-auto mb-4" /><p className="text-gray">Nenhum fornecedor encontrado</p></div>
        )}
      </div>

      {/* Detail Modal */}
      {selectedFornecedor && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50">
          <div className="bg-white rounded-2xl w-full max-w-lg shadow-2xl animate-fade-in max-h-[90vh] overflow-y-auto">
            <div className="flex items-center justify-between p-6 border-b border-border bg-gradient-to-r from-primary to-accent rounded-t-2xl">
              <h2 className="text-xl font-semibold text-white">Detalhes do Fornecedor</h2>
              <button onClick={() => setSelectedFornecedor(null)} className="p-2 rounded-lg hover:bg-white/20 text-white"><X className="w-5 h-5" /></button>
            </div>
            <div className="p-6 space-y-6">
              <div className="flex items-center gap-4">
                <div className="w-16 h-16 rounded-xl bg-gradient-to-br from-secondary to-secondary-light flex items-center justify-center">
                  <Building2 className="w-8 h-8 text-white" />
                </div>
                <div>
                  <h3 className="text-xl font-semibold text-text">{selectedFornecedor.razao_social || selectedFornecedor.nome_fantasia}</h3>
                  <p className="text-gray">{getDoc(selectedFornecedor)}</p>
                  <span className={`badge ${selectedFornecedor.ativo ? 'badge-success' : 'badge-neutral'} mt-1 inline-flex items-center gap-1`}>
                    {selectedFornecedor.ativo ? <><CheckCircle2 className="w-3 h-3" />Ativo</> : <><XCircle className="w-3 h-3" />Inativo</>}
                  </span>
                </div>
              </div>
              <div className="space-y-4">
                <div className="flex items-center gap-3 p-3 bg-card rounded-xl"><Mail className="w-5 h-5 text-gray" /><div><p className="text-xs text-gray">E-mail</p><p className="text-text">{selectedFornecedor.email || '-'}</p></div></div>
                <div className="flex items-center gap-3 p-3 bg-card rounded-xl"><Phone className="w-5 h-5 text-gray" /><div><p className="text-xs text-gray">Telefone</p><p className="text-text">{selectedFornecedor.telefone || '-'}</p></div></div>
                {selectedFornecedor.endereco && <div className="flex items-center gap-3 p-3 bg-card rounded-xl"><MapPin className="w-5 h-5 text-gray" /><div><p className="text-xs text-gray">Endereço</p><p className="text-text">{selectedFornecedor.endereco}</p></div></div>}
              </div>
              <div><p className="text-sm text-gray mb-2">Avaliação</p>{renderStars(getRating(selectedFornecedor))}</div>
              {/* ESG Info */}
              <div className="border-t border-border pt-4">
                <p className="text-sm font-semibold mb-3" style={{ color: '#1A7A4C' }}>🌿 Informações ESG</p>
                <div className="grid grid-cols-2 gap-2 text-sm">
                  <div className="flex items-center gap-2"><span>{selectedFornecedor.possui_politica_ambiental ? '✅' : '❌'}</span>Política Ambiental</div>
                  <div className="flex items-center gap-2"><span>{selectedFornecedor.possui_politica_sst ? '✅' : '❌'}</span>Política SST</div>
                  <div className="flex items-center gap-2"><span>{selectedFornecedor.declara_uso_epi ? '✅' : '❌'}</span>Uso de EPI</div>
                  <div className="flex items-center gap-2"><span>{selectedFornecedor.equipe_treinada ? '✅' : '❌'}</span>Equipe Treinada</div>
                </div>
                {selectedFornecedor.classificacao_esg && (
                  <div className="mt-3">
                    <span className={`badge ${selectedFornecedor.classificacao_esg === 'Avançado' ? 'badge-success' : selectedFornecedor.classificacao_esg === 'Intermediário' ? 'badge-warning' : 'badge-error'}`}>
                      ESG: {selectedFornecedor.classificacao_esg}
                    </span>
                  </div>
                )}
              </div>
              <div className="flex gap-3 pt-4">
                <button onClick={() => setSelectedFornecedor(null)} className="btn-ghost flex-1">Fechar</button>
                <button onClick={() => { setSelectedFornecedor(null); openEdit(selectedFornecedor) }} className="btn-primary flex-1">Editar Fornecedor</button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Create/Edit Modal */}
      <Modal open={showCreateModal} onClose={() => setShowCreateModal(false)} title={editId ? 'Editar Fornecedor' : 'Novo Fornecedor'} onSubmit={handleSubmit} submitLabel={editId ? 'Salvar' : 'Criar Fornecedor'} loading={saving}>
        <div>
          <label className="block text-sm font-medium text-text mb-2">Tipo Pessoa</label>
          <select value={form.tipo_pessoa} onChange={(e) => setForm({ ...form, tipo_pessoa: e.target.value })} className="input-field">
            <option value="PJ">Pessoa Jurídica</option><option value="PF">Pessoa Física</option>
          </select>
        </div>
        <div>
          <label className="block text-sm font-medium text-text mb-2">Razão Social</label>
          <input type="text" value={form.razao_social} onChange={(e) => setForm({ ...form, razao_social: e.target.value })} className="input-field" required />
        </div>
        <div>
          <label className="block text-sm font-medium text-text mb-2">Nome Fantasia</label>
          <input type="text" value={form.nome_fantasia} onChange={(e) => setForm({ ...form, nome_fantasia: e.target.value })} className="input-field" />
        </div>
        <div>
          <label className="block text-sm font-medium text-text mb-2">{form.tipo_pessoa === 'PJ' ? 'CNPJ' : 'CPF'}</label>
          <input type="text" value={form.cpf_cnpj} onChange={(e) => setForm({ ...form, cpf_cnpj: e.target.value })} className="input-field" required />
        </div>
        <div>
          <label className="block text-sm font-medium text-text mb-2">E-mail</label>
          <input type="email" value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} className="input-field" />
        </div>
        <div>
          <label className="block text-sm font-medium text-text mb-2">Telefone</label>
          <input type="text" value={form.telefone} onChange={(e) => setForm({ ...form, telefone: e.target.value })} className="input-field" />
        </div>
        <div>
          <label className="block text-sm font-medium text-text mb-2">Nome do Contato</label>
          <input type="text" value={form.nome_contato} onChange={(e) => setForm({ ...form, nome_contato: e.target.value })} className="input-field" placeholder="Nome da pessoa de contato" />
        </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 className="space-y-2">
          <label className="flex items-center gap-2 text-sm">
            <input type="checkbox" checked={form.possui_politica_ambiental} onChange={e => setForm({ ...form, possui_politica_ambiental: e.target.checked })} className="rounded border-gray-300 text-green-600" />
            Possui Política Ambiental
          </label>
          <label className="flex items-center gap-2 text-sm">
            <input type="checkbox" checked={form.possui_politica_sst} onChange={e => setForm({ ...form, possui_politica_sst: e.target.checked })} className="rounded border-gray-300 text-green-600" />
            Possui Política SST
          </label>
          <label className="flex items-center gap-2 text-sm">
            <input type="checkbox" checked={form.declara_uso_epi} onChange={e => setForm({ ...form, declara_uso_epi: e.target.checked })} className="rounded border-gray-300 text-green-600" />
            Declara Uso de EPI
          </label>
          <label className="flex items-center gap-2 text-sm">
            <input type="checkbox" checked={form.equipe_treinada} onChange={e => setForm({ ...form, equipe_treinada: e.target.checked })} className="rounded border-gray-300 text-green-600" />
            Equipe Treinada
          </label>
        </div>
        <div>
          <label className="block text-sm font-medium text-text mb-2">Classificação ESG</label>
          <select value={form.classificacao_esg} onChange={e => setForm({ ...form, classificacao_esg: e.target.value })} className="input-field">
            <option value="">Selecione...</option>
            <option value="Básico">Básico</option>
            <option value="Intermediário">Intermediário</option>
            <option value="Avançado">Avançado</option>
          </select>
        </div>
      </Modal>
    </div>
  )
}
