import { useState, useEffect } from 'react'
import { BarChart3, Loader2, TrendingUp, TrendingDown, Minus } from 'lucide-react'
import api from '../services/api'

interface KPI {
  id?: number
  nome: string
  valor: number
  unidade: string
  categoria: string
  status: string // verde, amarelo, vermelho
  descricao?: string
}

interface KPIDashboard {
  kpis: KPI[]
  calculados: KPI[]
}

export default function KPIs() {
  const [loading, setLoading] = useState(true)
  const [data, setData] = useState<KPIDashboard | null>(null)
  const [categoria, setCategoria] = useState('')
  const [ano, setAno] = useState(new Date().getFullYear())

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

  const fetchData = async () => {
    setLoading(true)
    try {
      const params: any = { ano }
      if (categoria) params.categoria = categoria
      const { data } = await api.get('/kpis/dashboard', { params })
      setData(data)
    } catch (err) {
      console.error('Error fetching KPIs:', err)
    } finally {
      setLoading(false)
    }
  }

  const statusConfig: Record<string, { bg: string, border: string, badge: string, icon: React.ReactNode }> = {
    verde: { bg: 'bg-green-50', border: 'border-green-200', badge: 'badge-success', icon: <TrendingUp className="w-4 h-4 text-green-500" /> },
    amarelo: { bg: 'bg-yellow-50', border: 'border-yellow-200', badge: 'badge-warning', icon: <Minus className="w-4 h-4 text-yellow-500" /> },
    vermelho: { bg: 'bg-red-50', border: 'border-red-200', badge: 'badge-error', icon: <TrendingDown className="w-4 h-4 text-red-500" /> },
  }

  const allKpis = [...(data?.calculados || []), ...(data?.kpis || [])]

  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">
            <BarChart3 className="w-8 h-8 text-primary" /> Indicadores KPI
          </h1>
          <p className="text-gray mt-1">Acompanhe os principais indicadores de performance.</p>
        </div>
        <div className="flex items-center gap-3">
          <select value={categoria} onChange={e => setCategoria(e.target.value)} className="input-field text-sm">
            <option value="">Todas categorias</option>
            <option value="financeiro">Financeiro</option>
            <option value="operacional">Operacional</option>
            <option value="qualidade">Qualidade</option>
            <option value="fornecedores">Fornecedores</option>
          </select>
          <select value={ano} onChange={e => setAno(Number(e.target.value))} className="input-field text-sm">
            {[2024, 2025, 2026].map(y => <option key={y} value={y}>{y}</option>)}
          </select>
        </div>
      </div>

      {allKpis.length > 0 ? (
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4 sm:gap-6">
          {allKpis.map((kpi, i) => {
            const cfg = statusConfig[kpi.status] || statusConfig.verde
            return (
              <div key={i} className={`card border ${cfg.border} ${cfg.bg} hover:shadow-lg transition-all duration-300`}>
                <div className="flex items-start justify-between mb-3">
                  <span className={`${cfg.badge} text-xs px-2 py-1 rounded-full`}>
                    {kpi.status === 'verde' ? 'Bom' : kpi.status === 'amarelo' ? 'Atenção' : 'Crítico'}
                  </span>
                  {cfg.icon}
                </div>
                <h3 className="font-semibold text-text mb-1">{kpi.nome}</h3>
                {kpi.descricao && <p className="text-xs text-gray mb-3">{kpi.descricao}</p>}
                <div className="flex items-end gap-1">
                  <span className="text-3xl font-bold text-text">
                    {typeof kpi.valor === 'number' ? kpi.valor.toLocaleString('pt-BR', { maximumFractionDigits: 1 }) : kpi.valor}
                  </span>
                  <span className="text-sm text-gray mb-1">{kpi.unidade}</span>
                </div>
                <p className="text-xs text-gray mt-2 capitalize">{kpi.categoria}</p>
              </div>
            )
          })}
        </div>
      ) : (
        <div className="card text-center py-12">
          <BarChart3 className="w-16 h-16 text-gray-300 mx-auto mb-4" />
          <h3 className="text-lg font-medium text-gray">Nenhum KPI encontrado</h3>
          <p className="text-sm text-gray-light mt-1">Os indicadores serão calculados automaticamente conforme dados são registrados.</p>
        </div>
      )}
    </div>
  )
}
