import { useState, useEffect } from 'react'
import { Leaf, Droplets, Trash2, Wind, Loader2, TrendingDown, TrendingUp, Target } from 'lucide-react'
import api from '../services/api'

interface ESGMetric {
  tipo: string
  valor: number
  unidade: string
  mes: number
  ano: number
}

interface ESGGoal {
  id: number
  tipo: string
  meta: number
  atual: number
  unidade: string
  ano: number
}

interface ResumoItem {
  tipo: string
  unidade: string
  total: number
  media: number
  registros: string
}

interface MetricaPorMes {
  tipo: string
  mes: number
  total: number
}

interface ESGMeta {
  id: string
  tipo: string
  meta_valor: number
  periodo_ano: number
  local_id: string | null
  created_at: string
}

interface ESGDashboard {
  ano: number
  resumo: ResumoItem[]
  metricas_por_mes: MetricaPorMes[]
  metas: ESGMeta[]
}

export default function ESG() {
  const [loading, setLoading] = useState(true)
  const [data, setData] = useState<ESGDashboard | null>(null)
  const [ano, setAno] = useState(new Date().getFullYear())
  const [tipo, setTipo] = useState('')

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

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

  const getResumoValue = (tipo: string) => {
    if (!data?.resumo || !Array.isArray(data.resumo)) return 0
    const item = data.resumo.find(r => r.tipo === tipo)
    return item?.total ?? 0
  }

  const summaryCards = [
    { title: 'Energia Total', value: getResumoValue('energia'), unit: 'kWh', icon: <Wind className="w-6 h-6" />, color: 'from-yellow-500 to-orange-500', bg: 'bg-yellow-100', text: 'text-yellow-600' },
    { title: 'Água Total', value: getResumoValue('agua'), unit: 'm³', icon: <Droplets className="w-6 h-6" />, color: 'from-blue-500 to-cyan-500', bg: 'bg-blue-100', text: 'text-blue-600' },
    { title: 'Resíduos Total', value: getResumoValue('residuos'), unit: 'kg', icon: <Trash2 className="w-6 h-6" />, color: 'from-green-500 to-emerald-500', bg: 'bg-green-100', text: 'text-green-600' },
    { title: 'Emissões CO₂', value: getResumoValue('emissoes'), unit: 'tCO₂', icon: <Wind className="w-6 h-6" />, color: 'from-gray-500 to-gray-700', bg: 'bg-gray-100', text: 'text-gray-600' },
  ]

  const monthNames = ['Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez']

  const getMaxValue = (metrics: MetricaPorMes[], tipoFilter: string) => {
    const filtered = metrics.filter(m => m.tipo === tipoFilter)
    return Math.max(...filtered.map(m => m.total), 1)
  }

  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">
            <Leaf className="w-8 h-8 text-green-600" /> ESG & Sustentabilidade
          </h1>
          <p className="text-gray mt-1">Monitoramento de indicadores ambientais e metas de sustentabilidade.</p>
        </div>
        <div className="flex items-center gap-3">
          <select value={tipo} onChange={e => setTipo(e.target.value)} className="input-field text-sm">
            <option value="">Todos os tipos</option>
            <option value="energia">Energia</option>
            <option value="agua">Água</option>
            <option value="residuos">Resíduos</option>
            <option value="emissoes">Emissões</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>

      {/* Summary Cards */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 sm:gap-6">
        {summaryCards.map((card, i) => (
          <div key={i} className="card group hover:shadow-lg transition-all duration-300">
            <div className="flex items-start justify-between mb-4">
              <div className={`w-12 h-12 rounded-xl bg-gradient-to-br ${card.color} flex items-center justify-center text-white shadow-lg`}>
                {card.icon}
              </div>
            </div>
            <p className="text-gray text-sm mb-1">{card.title}</p>
            <p className="text-2xl sm:text-3xl font-bold text-text">
              {typeof card.value === 'number' ? card.value.toLocaleString('pt-BR') : card.value}
            </p>
            <p className="text-xs text-gray mt-1">{card.unit}</p>
          </div>
        ))}
      </div>

      {/* Monthly Metrics */}
      {data?.metricas_por_mes && data.metricas_por_mes.length > 0 && (
        <div className="card">
          <h2 className="text-lg font-semibold text-text mb-4">Métricas Mensais</h2>
          <div className="grid md:grid-cols-2 gap-6">
            {['energia', 'agua', 'residuos', 'emissoes'].map(t => {
              const metrics = (data?.metricas_por_mes || []).filter(m => m.tipo === t)
              if (metrics.length === 0) return null
              const max = getMaxValue(data?.metricas_por_mes || [], t)
              return (
                <div key={t} className="space-y-2">
                  <h3 className="font-medium text-text capitalize">{t === 'agua' ? 'Água' : t === 'emissoes' ? 'Emissões' : t === 'residuos' ? 'Resíduos' : t}</h3>
                  {metrics.sort((a, b) => a.mes - b.mes).map(m => (
                    <div key={m.mes} className="flex items-center gap-3">
                      <span className="text-xs text-gray w-8">{monthNames[m.mes - 1]}</span>
                      <div className="flex-1 bg-gray-100 rounded-full h-4 overflow-hidden">
                        <div
                          className="h-full rounded-full bg-gradient-to-r from-primary to-accent transition-all duration-500"
                          style={{ width: `${(m.total / max) * 100}%` }}
                        />
                      </div>
                      <span className="text-xs text-gray w-16 text-right">{m.total.toLocaleString('pt-BR')} {summaryCards.find(c => c.title.toLowerCase().includes(t))?.unit || ""}</span>
                    </div>
                  ))}
                </div>
              )
            })}
          </div>
        </div>
      )}

      {/* Goals */}
      {data?.metas && data.metas.length > 0 && (
        <div className="card">
          <h2 className="text-lg font-semibold text-text mb-4 flex items-center gap-2">
            <Target className="w-5 h-5 text-primary" /> Metas de Sustentabilidade
          </h2>
          <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-4">
            {data.metas.map((goal: any) => {
              const metaVal = goal.meta_valor ?? goal.meta ?? 0
              const atualVal = getResumoValue(goal.tipo)
              const pct = metaVal > 0 ? Math.min((atualVal / metaVal) * 100, 100) : 0
              const isGood = atualVal <= metaVal
              const unit = summaryCards.find(c => c.title.toLowerCase().includes(goal.tipo))?.unit || ''
              return (
                <div key={goal.id} className="p-4 bg-gray-50 rounded-xl space-y-3">
                  <div className="flex items-center justify-between">
                    <span className="font-medium text-text capitalize">{goal.tipo === 'agua' ? 'Água' : goal.tipo === 'emissoes' ? 'Emissões' : goal.tipo === 'residuos' ? 'Resíduos' : goal.tipo}</span>
                    {isGood ? <TrendingDown className="w-4 h-4 text-green-500" /> : <TrendingUp className="w-4 h-4 text-red-500" />}
                  </div>
                  <div className="bg-gray-200 rounded-full h-3 overflow-hidden">
                    <div
                      className={`h-full rounded-full transition-all duration-500 ${isGood ? 'bg-green-500' : 'bg-red-500'}`}
                      style={{ width: `${pct}%` }}
                    />
                  </div>
                  <div className="flex justify-between text-xs text-gray">
                    <span>Atual: {atualVal.toLocaleString('pt-BR')} {unit}</span>
                    <span>Meta: {metaVal.toLocaleString('pt-BR')} {unit}</span>
                  </div>
                </div>
              )
            })}
          </div>
        </div>
      )}

      {/* Empty state */}
      {!data?.metricas_por_mes?.length && !data?.metas?.length && (
        <div className="card text-center py-12">
          <Leaf className="w-16 h-16 text-gray-300 mx-auto mb-4" />
          <h3 className="text-lg font-medium text-gray">Nenhum dado ESG encontrado</h3>
          <p className="text-sm text-gray-light mt-1">Registre métricas ambientais para visualizar o dashboard.</p>
        </div>
      )}
    </div>
  )
}
