import { useState, useEffect, useCallback } from 'react'
import {
  RefreshCw, Users, Bot, AlertTriangle, Clock,
  TrendingUp, CheckCircle, XCircle, BarChart3,
  Flag, Star, Timer, ChevronLeft, ChevronRight,
} from 'lucide-react'

// ─── tipos ────────────────────────────────────────────────────────────────────

interface AccountMetric {
  account_id: number
  name: string
  email: string
  escalations_assumed: string
  messages_sent: string
  human_api_answered: string
  avg_first_response_min: string | null
}

interface SectorMetric {
  sector_id: number
  name: string
  color: string
  sla_minutes: number
  escalations_total: string
  sla_breaches: string
  avg_response_min: string | null
}

interface DayPoint { day: string; count: string }

interface MetricsData {
  period: string
  by_account: AccountMetric[]
  by_sector: SectorMetric[]
  human_api: { total: number; answered: number; timeout: number; ignored: number; rate_pct: number }
  auto_replies: { total_in: number; total_replied: number; rate_pct: number }
  daily_escalations: DayPoint[]
  flags: { complaints: number; suggestions: number; compliments: number }
  ratings: { total_sent: number; total_rated: number; avg_rating: number | null }
  resolution: { avg_minutes: number | null; total_resolved: number }
}

interface RatingHistoryRow {
  id: number
  thread_id: string
  chat_id: string
  rating: number | null
  status: string
  sent_at: string
  rated_at: string | null
  account_name: string | null
  account_email: string | null
}

// ─── Histórico de Avaliações ──────────────────────────────────────────────────

function RatingsHistory() {
  const [rows,    setRows]    = useState<RatingHistoryRow[]>([])
  const [total,   setTotal]   = useState(0)
  const [page,    setPage]    = useState(0)
  const [filter,  setFilter]  = useState<number | ''>('')
  const [loading, setLoading] = useState(false)
  const LIMIT = 15

  const load = useCallback(async (p: number, f: number | '') => {
    setLoading(true)
    try {
      const params = new URLSearchParams({ limit: String(LIMIT), offset: String(p * LIMIT) })
      if (f !== '') params.set('rating', String(f))
      const r = await fetch(`/api/admin/metrics/ratings-history?${params}`, { credentials: 'include' })
      const data = await r.json()
      setRows(data.rows ?? [])
      setTotal(data.total ?? 0)
    } catch {}
    finally { setLoading(false) }
  }, [])

  useEffect(() => { load(page, filter) }, [page, filter, load])

  function fmtDate(s: string) { return new Date(s).toLocaleString('pt-BR', { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit' }) }

  const stars = (n: number | null) => n ? '★'.repeat(n) + '☆'.repeat(5 - n) : '—'
  const starColor = (n: number | null) => n ? (n >= 4 ? 'text-[#25d366]' : n >= 3 ? 'text-amber-400' : 'text-red-400') : 'text-[#8696a0]'

  const pages = Math.ceil(total / LIMIT)

  return (
    <div className="bg-white rounded-2xl shadow-sm border border-[#e9edef] overflow-hidden">
      <div className="px-4 py-2.5 border-b border-[#e9edef] flex items-center gap-2 flex-wrap">
        <Star size={13} className="text-amber-400 shrink-0" />
        <h3 className="text-[12px] font-semibold text-[#111b21] flex-1">Histórico de Avaliações</h3>
        {/* Filtro por nota */}
        <div className="flex gap-1">
          <button onClick={() => { setFilter(''); setPage(0) }}
            className={`px-2 py-0.5 rounded-full text-[10px] font-medium transition ${filter === '' ? 'bg-[#00a884] text-white' : 'text-[#8696a0] hover:bg-[#f0f2f5]'}`}>
            Todas
          </button>
          {[5, 4, 3, 2, 1].map(n => (
            <button key={n} onClick={() => { setFilter(n); setPage(0) }}
              className={`px-2 py-0.5 rounded-full text-[10px] font-medium transition ${filter === n ? 'bg-amber-400 text-white' : 'text-[#8696a0] hover:bg-[#f0f2f5]'}`}>
              {'★'.repeat(n)}
            </button>
          ))}
        </div>
      </div>

      {loading ? (
        <div className="flex items-center justify-center py-8 text-[#8696a0] gap-2 text-[12px]">
          <RefreshCw size={12} className="animate-spin" /> Carregando…
        </div>
      ) : rows.length === 0 ? (
        <p className="text-center py-8 text-[#8696a0] text-[12px]">Nenhuma avaliação encontrada</p>
      ) : (
        <>
          <div className="overflow-x-auto">
            <table className="w-full text-[11px]">
              <thead>
                <tr className="border-b border-[#e9edef] text-[#8696a0] text-[10px] uppercase">
                  <th className="text-left px-4 py-2">Chat</th>
                  <th className="text-left px-3 py-2">Atendente</th>
                  <th className="text-center px-3 py-2">Nota</th>
                  <th className="text-center px-3 py-2">Status</th>
                  <th className="text-right px-4 py-2">Enviado</th>
                </tr>
              </thead>
              <tbody>
                {rows.map(r => (
                  <tr key={r.id} className="border-b border-[#f5f6f6] hover:bg-[#f5f6f6] transition">
                    <td className="px-4 py-2 font-mono text-[10px] text-[#54656f] max-w-[100px] truncate">{r.chat_id.replace('@s.whatsapp.net', '')}</td>
                    <td className="px-3 py-2 text-[#111b21] max-w-[100px] truncate">{r.account_name || '—'}</td>
                    <td className={`px-3 py-2 text-center font-bold text-[13px] ${starColor(r.rating)}`}>{stars(r.rating)}</td>
                    <td className="px-3 py-2 text-center">
                      <span className={`px-1.5 py-0.5 rounded-full text-[9px] font-bold ${
                        r.status === 'rated' ? 'bg-[#25d366]/10 text-[#25d366]'
                        : r.status === 'expired' ? 'bg-slate-100 text-slate-400'
                        : 'bg-amber-50 text-amber-500'
                      }`}>{r.status === 'rated' ? 'Avaliado' : r.status === 'expired' ? 'Expirado' : 'Pendente'}</span>
                    </td>
                    <td className="px-4 py-2 text-right text-[#8696a0]">{fmtDate(r.sent_at)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
          {/* Paginação */}
          {pages > 1 && (
            <div className="px-4 py-2 flex items-center justify-between text-[11px] text-[#8696a0] border-t border-[#f0f2f5]">
              <span>{total} avaliações</span>
              <div className="flex items-center gap-1">
                <button onClick={() => setPage(p => Math.max(0, p - 1))} disabled={page === 0}
                  className="p-1 rounded hover:bg-[#e9edef] disabled:opacity-30 transition">
                  <ChevronLeft size={13} />
                </button>
                <span>{page + 1} / {pages}</span>
                <button onClick={() => setPage(p => Math.min(pages - 1, p + 1))} disabled={page >= pages - 1}
                  className="p-1 rounded hover:bg-[#e9edef] disabled:opacity-30 transition">
                  <ChevronRight size={13} />
                </button>
              </div>
            </div>
          )}
        </>
      )}
    </div>
  )
}

// ─── MiniBarChart ─────────────────────────────────────────────────────────────

function MiniBarChart({ data }: { data: DayPoint[] }) {
  if (!data.length) return (
    <p className="text-center py-6 text-[#8696a0] text-[12px]">Sem escalações no período</p>
  )
  const max = Math.max(...data.map(d => parseInt(d.count)))
  return (
    <div className="flex items-end gap-1.5 h-[72px] px-2 pb-1">
      {data.map(d => {
        const h = max > 0 ? Math.max(4, Math.round((parseInt(d.count) / max) * 64)) : 4
        return (
          <div key={d.day} className="flex flex-col items-center gap-0.5 flex-1 min-w-0">
            <span className="text-[9px] text-[#8696a0] font-medium">{d.count}</span>
            <div className="w-full rounded-t-sm bg-[#00a884]" style={{ height: h }} />
            <span className="text-[9px] text-[#8696a0] truncate w-full text-center">{d.day}</span>
          </div>
        )
      })}
    </div>
  )
}

// ─── helpers ──────────────────────────────────────────────────────────────────

function num(v: string | null | undefined) { return parseInt(v ?? '0', 10) || 0 }
function flt(v: string | null | undefined) { return v ? parseFloat(v).toFixed(1) : '—' }

function Card({ icon: Icon, label, value, sub, color = 'text-[#00a884]' }: {
  icon: any; label: string; value: string | number; sub?: string; color?: string
}) {
  return (
    <div className="bg-white rounded-2xl p-4 shadow-sm border border-[#e9edef] flex flex-col gap-1">
      <div className="flex items-center gap-2 text-[#8696a0] text-[11px] font-medium uppercase tracking-wide">
        <Icon size={12} className={color} />
        {label}
      </div>
      <p className={`text-[28px] font-bold leading-none ${color}`}>{value}</p>
      {sub && <p className="text-[11px] text-[#8696a0]">{sub}</p>}
    </div>
  )
}

// ─── MetricasTab ──────────────────────────────────────────────────────────────

export default function MetricasTab() {
  const [data,    setData]    = useState<MetricsData | null>(null)
  const [period,  setPeriod]  = useState<'today' | '7d' | '30d'>('7d')
  const [loading, setLoading] = useState(true)
  const [error,   setError]   = useState<string | null>(null)

  const load = useCallback(async () => {
    setLoading(true)
    setError(null)
    try {
      const r = await fetch(`/api/admin/metrics/attendance?period=${period}`, { credentials: 'include' })
      if (!r.ok) throw new Error(`HTTP ${r.status}`)
      setData(await r.json())
    } catch (e: any) {
      setError(e.message)
    } finally {
      setLoading(false)
    }
  }, [period])

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

  const PERIODS: [string, string][] = [['today', 'Hoje'], ['7d', '7 dias'], ['30d', '30 dias']]

  return (
    <div className="flex flex-col h-full bg-[#f0f2f5] overflow-y-auto">

      {/* header */}
      <div className="flex-shrink-0 px-4 pt-3 pb-2 bg-[#f0f2f5] border-b border-[#e9edef]">
        <div className="flex items-center gap-2 mb-2">
          <BarChart3 size={15} className="text-[#54656f]" />
          <h2 className="text-sm font-semibold text-[#111b21] flex-1">Métricas de Atendimento</h2>
          <button onClick={load} className="p-1 rounded-full hover:bg-[#e9edef] transition text-[#8696a0]">
            <RefreshCw size={13} className={loading ? 'animate-spin' : ''} />
          </button>
        </div>
        <div className="flex gap-1">
          {PERIODS.map(([k, l]) => (
            <button key={k} onClick={() => setPeriod(k as any)}
              className={`px-3 py-1 rounded-full text-[11px] font-medium transition
                ${period === k ? 'bg-[#00a884] text-white' : 'text-[#54656f] hover:bg-[#e9edef]'}`}>
              {l}
            </button>
          ))}
        </div>
      </div>

      {error && (
        <div className="m-4 p-3 bg-red-50 border border-red-200 text-red-700 text-[12px] rounded-xl">{error}</div>
      )}

      {data && (
        <div className="p-4 flex flex-col gap-4">

          {/* cards de resumo */}
          <div className="grid grid-cols-2 gap-3">
            <Card icon={Users}
              label="Escalações assumidas"
              value={data.by_account.reduce((s, a) => s + num(a.escalations_assumed), 0)}
              sub={`nos últimos ${PERIODS.find(p => p[0] === period)?.[1]}`}
              color="text-[#00a884]" />
            <Card icon={Bot}
              label="Respostas IA"
              value={`${data.auto_replies.rate_pct}%`}
              sub={`${data.auto_replies.total_replied} de ${data.auto_replies.total_in} msgs`}
              color="text-cyan-500" />
            <Card icon={CheckCircle}
              label="Human API respondidas"
              value={`${data.human_api.rate_pct}%`}
              sub={`${data.human_api.answered} de ${data.human_api.total} pedidos`}
              color="text-[#25d366]" />
            <Card icon={AlertTriangle}
              label="Timeouts Human API"
              value={data.human_api.timeout}
              sub={data.human_api.ignored > 0 ? `+ ${data.human_api.ignored} ignorados` : 'sem pedidos ignorados'}
              color="text-amber-500" />
          </div>

          {/* cards extras: flags + ratings + resolução */}
          <div className="grid grid-cols-2 gap-3">
            <div className="bg-white rounded-2xl p-4 shadow-sm border border-[#e9edef] flex flex-col gap-1.5">
              <div className="flex items-center gap-2 text-[#8696a0] text-[11px] font-medium uppercase tracking-wide">
                <Flag size={12} className="text-amber-500" /> Flags do período
              </div>
              <div className="flex gap-3 mt-0.5">
                <span className="text-[12px]"><span className="font-bold text-red-500">{data.flags.complaints}</span> <span className="text-[#8696a0]">reclam.</span></span>
                <span className="text-[12px]"><span className="font-bold text-cyan-500">{data.flags.suggestions}</span> <span className="text-[#8696a0]">sugest.</span></span>
                <span className="text-[12px]"><span className="font-bold text-[#25d366]">{data.flags.compliments}</span> <span className="text-[#8696a0]">elogios</span></span>
              </div>
            </div>
            <div className="bg-white rounded-2xl p-4 shadow-sm border border-[#e9edef] flex flex-col gap-1">
              <div className="flex items-center gap-2 text-[#8696a0] text-[11px] font-medium uppercase tracking-wide">
                <Star size={12} className="text-amber-400" /> Satisfação
              </div>
              <p className="text-[28px] font-bold leading-none text-amber-400">
                {data.ratings.avg_rating ? `${data.ratings.avg_rating.toFixed(1)}★` : '—'}
              </p>
              <p className="text-[11px] text-[#8696a0]">{data.ratings.total_rated} de {data.ratings.total_sent} avaliaram</p>
            </div>
            {/* Tempo médio de resolução */}
            <div className="col-span-2 bg-white rounded-2xl p-4 shadow-sm border border-[#e9edef] flex items-center gap-4">
              <div className="p-2.5 rounded-xl bg-[#00a884]/10 text-[#00a884]">
                <Timer size={18} />
              </div>
              <div className="flex-1">
                <p className="text-[11px] font-medium text-[#8696a0] uppercase tracking-wide">Tempo médio de resolução</p>
                <p className="text-[22px] font-bold text-[#111b21] leading-tight">
                  {data.resolution?.avg_minutes != null
                    ? data.resolution.avg_minutes >= 60
                      ? `${(data.resolution.avg_minutes / 60).toFixed(1)}h`
                      : `${data.resolution.avg_minutes.toFixed(0)} min`
                    : '—'}
                </p>
              </div>
              <div className="text-right">
                <p className="text-[10px] text-[#8696a0]">protocolos encerrados</p>
                <p className="text-[18px] font-bold text-[#54656f]">{data.resolution?.total_resolved ?? 0}</p>
              </div>
            </div>
          </div>

          {/* gráfico diário */}
          <div className="bg-white rounded-2xl shadow-sm border border-[#e9edef] overflow-hidden">
            <div className="px-4 py-2.5 border-b border-[#e9edef] flex items-center gap-2">
              <BarChart3 size={13} className="text-[#54656f]" />
              <h3 className="text-[12px] font-semibold text-[#111b21]">Escalações por dia</h3>
            </div>
            <div className="px-2 py-2">
              <MiniBarChart data={data.daily_escalations} />
            </div>
          </div>

          {/* por colaborador */}
          <div className="bg-white rounded-2xl shadow-sm border border-[#e9edef] overflow-hidden">
            <div className="px-4 py-2.5 border-b border-[#e9edef] flex items-center gap-2">
              <Users size={13} className="text-[#54656f]" />
              <h3 className="text-[12px] font-semibold text-[#111b21]">Por Colaborador</h3>
            </div>
            {data.by_account.length === 0
              ? <p className="text-center py-6 text-[#8696a0] text-[12px]">Sem dados</p>
              : (
                <div className="overflow-x-auto">
                  <table className="w-full text-[12px]">
                    <thead>
                      <tr className="border-b border-[#e9edef] text-[#8696a0] text-[10px] uppercase">
                        <th className="text-left px-4 py-2">Colaborador</th>
                        <th className="text-center px-3 py-2">Escalações</th>
                        <th className="text-center px-3 py-2">Msgs</th>
                        <th className="text-center px-3 py-2">Human API</th>
                        <th className="text-center px-3 py-2">
                          <span className="flex items-center justify-center gap-1"><Clock size={9} />1ª resp.</span>
                        </th>
                      </tr>
                    </thead>
                    <tbody>
                      {data.by_account.map(a => (
                        <tr key={a.account_id} className="border-b border-[#f5f6f6] hover:bg-[#f5f6f6] transition">
                          <td className="px-4 py-2.5">
                            <p className="font-medium text-[#111b21] truncate max-w-[120px]">{a.name}</p>
                            <p className="text-[10px] text-[#8696a0] truncate max-w-[120px]">{a.email}</p>
                          </td>
                          <td className="text-center px-3 py-2 font-bold text-[#00a884]">{num(a.escalations_assumed)}</td>
                          <td className="text-center px-3 py-2 text-[#54656f]">{num(a.messages_sent)}</td>
                          <td className="text-center px-3 py-2 text-cyan-600">{num(a.human_api_answered)}</td>
                          <td className="text-center px-3 py-2 text-[#8696a0]">
                            {a.avg_first_response_min ? `${flt(a.avg_first_response_min)}m` : '—'}
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              )
            }
          </div>

          {/* por setor */}
          <div className="bg-white rounded-2xl shadow-sm border border-[#e9edef] overflow-hidden">
            <div className="px-4 py-2.5 border-b border-[#e9edef] flex items-center gap-2">
              <TrendingUp size={13} className="text-[#54656f]" />
              <h3 className="text-[12px] font-semibold text-[#111b21]">Por Setor</h3>
            </div>
            {data.by_sector.length === 0
              ? <p className="text-center py-6 text-[#8696a0] text-[12px]">Sem dados</p>
              : (
                <div className="overflow-x-auto">
                  <table className="w-full text-[12px]">
                    <thead>
                      <tr className="border-b border-[#e9edef] text-[#8696a0] text-[10px] uppercase">
                        <th className="text-left px-4 py-2">Setor</th>
                        <th className="text-center px-3 py-2">Escalações</th>
                        <th className="text-center px-3 py-2">
                          <span className="flex items-center justify-center gap-1"><XCircle size={9} />SLA breach</span>
                        </th>
                        <th className="text-center px-3 py-2">SLA (min)</th>
                        <th className="text-center px-3 py-2">
                          <span className="flex items-center justify-center gap-1"><Clock size={9} />Resp. média</span>
                        </th>
                      </tr>
                    </thead>
                    <tbody>
                      {data.by_sector.map(s => {
                        const esc = num(s.escalations_total)
                        const brk = num(s.sla_breaches)
                        const slaOk = esc > 0 && brk === 0
                        return (
                          <tr key={s.sector_id} className="border-b border-[#f5f6f6] hover:bg-[#f5f6f6] transition">
                            <td className="px-4 py-2.5 flex items-center gap-2">
                              <span className="w-2.5 h-2.5 rounded-full flex-shrink-0" style={{ background: s.color || '#6366f1' }} />
                              <span className="font-medium text-[#111b21]">{s.name}</span>
                            </td>
                            <td className="text-center px-3 py-2 font-bold text-[#00a884]">{esc}</td>
                            <td className="text-center px-3 py-2">
                              {brk > 0
                                ? <span className="text-red-500 font-bold">{brk}</span>
                                : <span className={esc > 0 ? 'text-[#25d366]' : 'text-[#8696a0]'}>{slaOk ? '✓' : '—'}</span>
                              }
                            </td>
                            <td className="text-center px-3 py-2 text-[#8696a0]">{s.sla_minutes ?? '—'}</td>
                            <td className="text-center px-3 py-2 text-[#8696a0]">
                              {s.avg_response_min ? `${flt(s.avg_response_min)}m` : '—'}
                            </td>
                          </tr>
                        )
                      })}
                    </tbody>
                  </table>
                </div>
              )
            }
          </div>

          {/* Histórico de avaliações paginado */}
          <RatingsHistory />

          {/* rodapé */}
          <p className="text-center text-[10px] text-[#8696a0] pb-2">
            Dados calculados em tempo real · {new Date().toLocaleTimeString('pt-BR')}
          </p>
        </div>
      )}

      {loading && !data && (
        <div className="flex-1 flex items-center justify-center text-[#8696a0] text-sm gap-2">
          <RefreshCw size={14} className="animate-spin" /> Carregando métricas...
        </div>
      )}
    </div>
  )
}
