import { useState, useEffect } from 'react'
import { Target, Loader2, Plus, X } from 'lucide-react'
import api from '../services/api'

interface Meta {
  id: number
  nome: string
  descricao: string
  tipo: string
  valor_meta: number
  valor_atual: number
  unidade: string
  status: string
  data_inicio: string
  data_fim: string
}

export default function Metas() {
  const [loading, setLoading] = useState(true)
  const [metas, setMetas] = useState<Meta[]>([])
  const [showForm, setShowForm] = useState(false)
  const [saving, setSaving] = useState(false)
  const [filterTipo, setFilterTipo] = useState('')
  const [filterStatus, setFilterStatus] = useState('')
  const [form, setForm] = useState({ nome: '', descricao: '', tipo: 'financeiro', valor_meta: 0, unidade: '', data_inicio: '', data_fim: '' })

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

  const fetchData = async () => {
    setLoading(true)
    try {
      const params: any = {}
      if (filterTipo) params.tipo = filterTipo
      if (filterStatus) params.status = filterStatus
      const { data } = await api.get('/metas/progresso', { params })
      setMetas(Array.isArray(data) ? data : data?.metas || [])
    } catch (err) {
      console.error('Error fetching metas:', err)
    } finally {
      setLoading(false)
    }
  }

  const handleCreate = async () => {
    setSaving(true)
    try {
      await api.post('/metas', form)
      setShowForm(false)
      setForm({ nome: '', descricao: '', tipo: 'financeiro', valor_meta: 0, unidade: '', data_inicio: '', data_fim: '' })
      fetchData()
    } catch (err) {
      console.error('Error creating meta:', err)
    } finally {
      setSaving(false)
    }
  }

  const statusBadge: Record<string, string> = {
    em_andamento: 'badge-info',
    atingida: 'badge-success',
    atrasada: 'badge-error',
  }
  const statusLabel: Record<string, string> = {
    em_andamento: 'Em Andamento',
    atingida: 'Atingida',
    atrasada: 'Atrasada',
  }

  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">
            <Target className="w-8 h-8 text-primary" /> Metas & Progresso
          </h1>
          <p className="text-gray mt-1">Acompanhe metas e objetivos da organização.</p>
        </div>
        <div className="flex items-center gap-3">
          <select value={filterTipo} onChange={e => setFilterTipo(e.target.value)} className="input-field text-sm">
            <option value="">Todos tipos</option>
            <option value="financeiro">Financeiro</option>
            <option value="operacional">Operacional</option>
            <option value="qualidade">Qualidade</option>
            <option value="esg">ESG</option>
          </select>
          <select value={filterStatus} onChange={e => setFilterStatus(e.target.value)} className="input-field text-sm">
            <option value="">Todos status</option>
            <option value="em_andamento">Em Andamento</option>
            <option value="atingida">Atingida</option>
            <option value="atrasada">Atrasada</option>
          </select>
          <button onClick={() => setShowForm(true)} className="btn-primary text-sm flex items-center gap-1">
            <Plus className="w-4 h-4" /> Nova Meta
          </button>
        </div>
      </div>

      {/* Create Form Modal */}
      {showForm && (
        <div className="card border-2 border-primary/20">
          <div className="flex items-center justify-between mb-4">
            <h3 className="font-semibold text-text">Nova Meta</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-2 gap-4">
            <input placeholder="Nome" value={form.nome} onChange={e => setForm({...form, nome: e.target.value})} className="input-field" />
            <select value={form.tipo} onChange={e => setForm({...form, tipo: e.target.value})} className="input-field">
              <option value="financeiro">Financeiro</option>
              <option value="operacional">Operacional</option>
              <option value="qualidade">Qualidade</option>
              <option value="esg">ESG</option>
            </select>
            <input placeholder="Valor Meta" type="number" value={form.valor_meta || ''} onChange={e => setForm({...form, valor_meta: Number(e.target.value)})} className="input-field" />
            <input placeholder="Unidade (ex: R$, %, un)" value={form.unidade} onChange={e => setForm({...form, unidade: e.target.value})} className="input-field" />
            <input type="date" value={form.data_inicio} onChange={e => setForm({...form, data_inicio: e.target.value})} className="input-field" />
            <input type="date" value={form.data_fim} onChange={e => setForm({...form, data_fim: e.target.value})} className="input-field" />
            <textarea placeholder="Descrição" value={form.descricao} onChange={e => setForm({...form, descricao: e.target.value})} className="input-field sm:col-span-2" rows={2} />
          </div>
          <button onClick={handleCreate} disabled={saving || !form.nome} 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 Meta
          </button>
        </div>
      )}

      {/* Goals Grid */}
      {metas.length > 0 ? (
        <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-4">
          {metas.map(meta => {
            const pct = meta.valor_meta > 0 ? Math.min((meta.valor_atual / meta.valor_meta) * 100, 100) : 0
            return (
              <div key={meta.id} className="card hover:shadow-lg transition-all duration-300">
                <div className="flex items-start justify-between mb-3">
                  <h3 className="font-semibold text-text">{meta.nome}</h3>
                  <span className={`text-xs px-2 py-1 rounded-full ${statusBadge[meta.status] || 'badge-info'}`}>
                    {statusLabel[meta.status] || meta.status}
                  </span>
                </div>
                {meta.descricao && <p className="text-sm text-gray mb-3">{meta.descricao}</p>}
                <div className="bg-gray-100 rounded-full h-4 overflow-hidden mb-2">
                  <div
                    className={`h-full rounded-full transition-all duration-500 ${
                      meta.status === 'atingida' ? 'bg-green-500' :
                      meta.status === 'atrasada' ? 'bg-red-500' : 'bg-gradient-to-r from-primary to-accent'
                    }`}
                    style={{ width: `${pct}%` }}
                  />
                </div>
                <div className="flex justify-between text-xs text-gray">
                  <span>{meta.valor_atual?.toLocaleString('pt-BR')} / {meta.valor_meta?.toLocaleString('pt-BR')} {meta.unidade}</span>
                  <span className="font-medium">{pct.toFixed(0)}%</span>
                </div>
                <p className="text-xs text-gray mt-2 capitalize">{meta.tipo}</p>
              </div>
            )
          })}
        </div>
      ) : (
        <div className="card text-center py-12">
          <Target className="w-16 h-16 text-gray-300 mx-auto mb-4" />
          <h3 className="text-lg font-medium text-gray">Nenhuma meta encontrada</h3>
          <p className="text-sm text-gray-light mt-1">Crie metas para acompanhar o progresso da organização.</p>
        </div>
      )}
    </div>
  )
}
