import { useState, useEffect } from 'react'
import { Bell, Loader2, Plus, X, Zap, CheckCircle, AlertTriangle } from 'lucide-react'
import api from '../services/api'

interface AlertConfig {
  id: number
  tipo: string
  limite_percentual: number
  centro_custo: string
  ativo: boolean
  criado_em?: string
}

export default function AlertasConfig() {
  const [loading, setLoading] = useState(true)
  const [configs, setConfigs] = useState<AlertConfig[]>([])
  const [showForm, setShowForm] = useState(false)
  const [saving, setSaving] = useState(false)
  const [verifying, setVerifying] = useState(false)
  const [verifyResult, setVerifyResult] = useState<any>(null)
  const [form, setForm] = useState({ tipo: 'orcamento_excedido', limite_percentual: 80, centro_custo: '' })

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

  const fetchData = async () => {
    setLoading(true)
    try {
      const { data } = await api.get('/alertas/configs')
      setConfigs(Array.isArray(data) ? data : data?.configs || [])
    } catch (err) {
      console.error('Error fetching alert configs:', err)
    } finally {
      setLoading(false)
    }
  }

  const handleCreate = async () => {
    setSaving(true)
    try {
      await api.post('/alertas/configurar', form)
      setShowForm(false)
      setForm({ tipo: 'orcamento_excedido', limite_percentual: 80, centro_custo: '' })
      fetchData()
    } catch (err) {
      console.error('Error creating alert config:', err)
    } finally {
      setSaving(false)
    }
  }

  const handleVerify = async () => {
    setVerifying(true)
    setVerifyResult(null)
    try {
      const { data } = await api.post('/alertas/verificar')
      setVerifyResult(data)
    } catch (err) {
      console.error('Error verifying alerts:', err)
    } finally {
      setVerifying(false)
    }
  }

  const handleToggle = async (config: AlertConfig) => {
    try {
      await api.put(`/alertas/configs/${config.id}`, { ...config, ativo: !config.ativo })
      setConfigs(configs.map(c => c.id === config.id ? { ...c, ativo: !c.ativo } : c))
    } catch (err) {
      console.error('Error toggling alert:', err)
    }
  }

  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 flex items-center gap-2">
            <Bell className="w-8 h-8 text-primary" /> Configuração de Alertas
          </h1>
          <p className="text-gray mt-1">Configure alertas inteligentes para monitoramento proativo.</p>
        </div>
        <div className="flex items-center gap-2">
          <button onClick={handleVerify} disabled={verifying} className="btn-outline text-sm flex items-center gap-1">
            {verifying ? <Loader2 className="w-4 h-4 animate-spin" /> : <Zap className="w-4 h-4" />} Verificar Agora
          </button>
          <button onClick={() => setShowForm(true)} className="btn-primary text-sm flex items-center gap-1">
            <Plus className="w-4 h-4" /> Novo Alerta
          </button>
        </div>
      </div>

      {/* Verify Result */}
      {verifyResult && (
        <div className="card border border-blue-200 bg-blue-50">
          <div className="flex items-center gap-2 mb-2">
            <CheckCircle className="w-5 h-5 text-blue-500" />
            <span className="font-medium text-text">Verificação concluída</span>
          </div>
          <p className="text-sm text-gray">
            {verifyResult.alertas_disparados ?? verifyResult.total ?? 0} alertas disparados.
            {verifyResult.mensagem && ` ${verifyResult.mensagem}`}
          </p>
        </div>
      )}

      {/* Create Form */}
      {showForm && (
        <div className="card border-2 border-primary/20">
          <div className="flex items-center justify-between mb-4">
            <h3 className="font-semibold text-text">Novo Alerta</h3>
            <button onClick={() => setShowForm(false)} className="p-1 rounded hover:bg-gray-100"><X className="w-5 h-5" /></button>
          </div>
          <div className="grid sm:grid-cols-3 gap-4">
            <select value={form.tipo} onChange={e => setForm({...form, tipo: e.target.value})} className="input-field">
              <option value="orcamento_excedido">Orçamento Excedido</option>
              <option value="demanda_atrasada">Demanda Atrasada</option>
              <option value="os_vencida">OS Vencida</option>
              <option value="contrato_vencendo">Contrato Vencendo</option>
            </select>
            <input type="number" placeholder="Limite %" value={form.limite_percentual} onChange={e => setForm({...form, limite_percentual: Number(e.target.value)})} className="input-field" />
            <input placeholder="Centro de Custo (opcional)" value={form.centro_custo} onChange={e => setForm({...form, centro_custo: e.target.value})} className="input-field" />
          </div>
          <button onClick={handleCreate} disabled={saving} className="btn-primary mt-4 flex items-center gap-2 disabled:opacity-50">
            {saving ? <Loader2 className="w-4 h-4 animate-spin" /> : <Plus className="w-4 h-4" />} Criar Alerta
          </button>
        </div>
      )}

      {/* Configs Table */}
      {configs.length > 0 ? (
        <div className="card overflow-x-auto">
          <table className="w-full">
            <thead>
              <tr className="table-header">
                <th className="table-cell text-left">Tipo</th>
                <th className="table-cell text-left">Limite %</th>
                <th className="table-cell text-left">Centro de Custo</th>
                <th className="table-cell text-center">Ativo</th>
              </tr>
            </thead>
            <tbody>
              {configs.map(config => (
                <tr key={config.id} className="table-row">
                  <td className="table-cell">
                    <div className="flex items-center gap-2">
                      <AlertTriangle className={`w-4 h-4 ${config.ativo ? 'text-amber-500' : 'text-gray-300'}`} />
                      <span className="text-sm font-medium capitalize">{config.tipo.replace(/_/g, ' ')}</span>
                    </div>
                  </td>
                  <td className="table-cell text-sm">{config.limite_percentual}%</td>
                  <td className="table-cell text-sm text-gray">{config.centro_custo || '—'}</td>
                  <td className="table-cell text-center">
                    <button
                      onClick={() => handleToggle(config)}
                      className={`w-12 h-6 rounded-full transition-all relative ${config.ativo ? 'bg-green-500' : 'bg-gray-300'}`}
                    >
                      <span className={`absolute top-0.5 w-5 h-5 bg-white rounded-full shadow transition-all ${config.ativo ? 'left-6' : 'left-0.5'}`} />
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      ) : (
        <div className="card text-center py-12">
          <Bell className="w-16 h-16 text-gray-300 mx-auto mb-4" />
          <h3 className="text-lg font-medium text-gray">Nenhum alerta configurado</h3>
          <p className="text-sm text-gray-light mt-1">Configure alertas para receber notificações proativas.</p>
        </div>
      )}
    </div>
  )
}
