import { useState, useEffect, useRef } from 'react';
import {
  Inbox, Send, RefreshCw, Check, CheckCheck,
  MessageSquare, Package, X, ChevronRight, HelpCircle,
  AlertTriangle, Clock, MessageCircle,
} from 'lucide-react';
import { InboxInternoService, CotacaoService } from '../services/api';
import InboxInternoHelpModal from '../components/InboxInternoHelpModal';

// ─── Widget: WhatsApp sem resposta ────────────────────────────────────────────

function WppSemResposta() {
  const [pendentes, setPendentes] = useState<any[]>([])
  const [expanded, setExpanded]   = useState(false)
  const [loading, setLoading]     = useState(false)

  async function carregar() {
    setLoading(true)
    try {
      const rows = await CotacaoService.wppSemResposta()
      setPendentes(rows)
    } catch { /* silent */ }
    finally { setLoading(false) }
  }

  useEffect(() => {
    carregar()
    const iv = setInterval(carregar, 60_000)
    return () => clearInterval(iv)
  }, [])

  if (!pendentes.length) return null

  const fmtPhone = (chatId: string) => chatId.replace('@s.whatsapp.net', '').replace('@c.us', '')
  const fmtMins  = (m: number) => m >= 60
    ? `${Math.floor(m / 60)}h${m % 60 > 0 ? String(m % 60).padStart(2,'0')+'min' : ''}`
    : `${m}min`

  return (
    <div className="border-b border-amber-500/30 bg-amber-500/5">
      {/* Header clicável */}
      <button
        onClick={() => setExpanded(e => !e)}
        className="w-full flex items-center gap-3 px-4 py-2.5 text-left hover:bg-amber-500/5 transition-colors"
      >
        <AlertTriangle size={14} className="text-amber-400 shrink-0 animate-pulse" />
        <span className="text-amber-400 font-black text-xs flex-1">
          {pendentes.length} chat{pendentes.length > 1 ? 's' : ''} sem resposta da IA
        </span>
        <button
          onClick={e => { e.stopPropagation(); carregar() }}
          className="p-1 text-amber-600 hover:text-amber-400 transition-colors"
        >
          <RefreshCw size={11} className={loading ? 'animate-spin' : ''} />
        </button>
        <span className="text-amber-600 text-[10px]">{expanded ? '▲' : '▼'}</span>
      </button>

      {/* Lista expandida */}
      {expanded && (
        <div className="max-h-52 overflow-y-auto border-t border-amber-500/20">
          {pendentes.map((p, i) => (
            <div key={i} className="flex items-start gap-3 px-4 py-2.5 border-b border-white/5 last:border-0">
              <MessageCircle size={13} className="text-amber-500 shrink-0 mt-0.5" />
              <div className="flex-1 min-w-0">
                <p className="text-xs font-bold text-white truncate">{fmtPhone(p.chat_id)}</p>
                <p className="text-[11px] text-slate-400 truncate">"{p.ultima_msg || '—'}"</p>
                {p.ultima_reply_status === 'failed' && (
                  <p className="text-[10px] text-rose-400 font-bold mt-0.5">IA falhou na última tentativa</p>
                )}
              </div>
              <div className="flex items-center gap-1 shrink-0 text-amber-400">
                <Clock size={10} />
                <span className="text-[10px] font-bold">{fmtMins(Number(p.minutos_aguardando))}</span>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  )
}

// ─── Tipos ────────────────────────────────────────────────────────────────────

interface Mensagem {
  id: number;
  tenant_id: number;
  pedido_id: number | null;
  setor: string;
  remetente: string;
  mensagem: string;
  lida: boolean;
  created_at: string;
  // joins
  pedido_status?: string;
  pedido_total?: string;
}

// ─── Setores disponíveis ──────────────────────────────────────────────────────

const SETORES = [
  { id: 'geral',       label: 'Geral',      emoji: '💬' },
  { id: 'atendimento', label: 'Atendimento', emoji: '🎧' },
  { id: 'cotacao',     label: 'Cotação',     emoji: '📋' },
  { id: 'separacao',   label: 'Separação',   emoji: '📦' },
  { id: 'embalagem',   label: 'Embalagem',   emoji: '🎁' },
  { id: 'auditoria',   label: 'Auditoria',   emoji: '🔍' },
  { id: 'fiscal',      label: 'Fiscal',      emoji: '🧾' },
  { id: 'expedicao',   label: 'Expedição',   emoji: '🚚' },
  { id: 'financeiro',  label: 'Financeiro',  emoji: '💰' },
  { id: 'suporte',     label: 'Suporte',     emoji: '🛠' },
];

// ─── Helpers ──────────────────────────────────────────────────────────────────

function fmtDt(s: string) {
  const d = new Date(s);
  const diff = Date.now() - d.getTime();
  if (diff < 60_000) return 'agora';
  if (diff < 3_600_000) return `${Math.floor(diff / 60_000)}min`;
  if (diff < 86_400_000) return d.toLocaleTimeString('pt-BR', { hour: '2-digit', minute: '2-digit' });
  return d.toLocaleDateString('pt-BR');
}

// ─── Linha de mensagem ────────────────────────────────────────────────────────

function MsgRow({
  msg,
  onLer,
}: { msg: Mensagem; onLer: (id: number) => void }) {
  return (
    <div className={`flex gap-3 p-4 border-b border-white/5 transition-colors
      ${msg.lida ? 'opacity-60' : 'bg-amber-500/3 hover:bg-white/3'}`}>
      <div className={`w-2 h-2 rounded-full mt-1.5 shrink-0 ${msg.lida ? 'bg-slate-700' : 'bg-amber-400'}`} />
      <div className="flex-1 min-w-0">
        <div className="flex items-baseline gap-2 mb-0.5">
          <span className="text-sm font-semibold text-white">{msg.remetente}</span>
          {msg.pedido_id && (
            <span className="text-[10px] text-slate-500 flex items-center gap-0.5">
              <Package size={9} /> #{msg.pedido_id}
            </span>
          )}
          <span className="ml-auto text-[10px] text-slate-600 shrink-0">{fmtDt(msg.created_at)}</span>
        </div>
        <p className="text-sm text-slate-300 leading-snug">{msg.mensagem}</p>
      </div>
      {!msg.lida && (
        <button
          onClick={() => onLer(msg.id)}
          title="Marcar como lida"
          className="text-slate-600 hover:text-emerald-400 transition-colors shrink-0 mt-0.5"
        >
          <Check size={14} />
        </button>
      )}
    </div>
  );
}

// ─── Painel de compose ────────────────────────────────────────────────────────

function ComposePanel({
  setorAtivo,
  onSent,
}: { setorAtivo: string; onSent: () => void }) {
  const [texto, setTexto] = useState('');
  const [pedidoId, setPedidoId] = useState('');
  const [enviando, setEnviando] = useState(false);
  const [erro, setErro] = useState('');

  async function enviar() {
    if (!texto.trim()) return;
    setEnviando(true);
    setErro('');
    try {
      await InboxInternoService.enviar({
        setor:     setorAtivo,
        mensagem:  texto.trim(),
        pedido_id: pedidoId ? Number(pedidoId) : undefined,
      });
      setTexto('');
      setPedidoId('');
      onSent();
    } catch (e: any) {
      setErro(e?.response?.data?.error ?? 'Erro ao enviar');
    } finally {
      setEnviando(false);
    }
  }

  function onKey(e: React.KeyboardEvent) {
    if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) enviar();
  }

  return (
    <div className="border-t border-white/10 p-4 bg-slate-950/50">
      {erro && (
        <p className="text-xs text-rose-400 mb-2 flex items-center gap-1">
          <X size={12} /> {erro}
        </p>
      )}
      <div className="flex gap-2 mb-2">
        <input
          type="number"
          value={pedidoId}
          onChange={e => setPedidoId(e.target.value)}
          placeholder="Pedido # (opcional)"
          className="w-32 bg-slate-900 border border-white/10 rounded-lg px-3 py-1.5 text-sm text-white placeholder:text-slate-600 focus:outline-none focus:border-amber-500/50"
        />
        <span className="text-xs text-slate-600 self-center">Ctrl+Enter para enviar</span>
      </div>
      <div className="flex gap-2">
        <textarea
          value={texto}
          onChange={e => setTexto(e.target.value)}
          onKeyDown={onKey}
          placeholder={`Mensagem para ${SETORES.find(s => s.id === setorAtivo)?.label ?? setorAtivo}...`}
          rows={2}
          className="flex-1 bg-slate-900 border border-white/10 rounded-xl px-3 py-2 text-sm text-white placeholder:text-slate-600 resize-none focus:outline-none focus:border-amber-500/50"
        />
        <button
          onClick={enviar}
          disabled={enviando || !texto.trim()}
          className="self-end px-4 py-2 bg-amber-500 text-black font-bold rounded-xl hover:bg-amber-400 disabled:opacity-50 transition-colors flex items-center gap-1.5"
        >
          {enviando ? <RefreshCw size={14} className="animate-spin" /> : <Send size={14} />}
          Enviar
        </button>
      </div>
    </div>
  );
}

// ─── Página principal ─────────────────────────────────────────────────────────

export default function InboxPage() {
  const [setorAtivo, setSetorAtivo] = useState('geral');
  const [mensagens, setMensagens] = useState<Mensagem[]>([]);
  const [loading, setLoading] = useState(false);
  const [badges, setBadges] = useState<Record<string, number>>({});
  const [somenteNaoLidas, setSomenteNaoLidas] = useState(false);
  const [showHelp, setShowHelp] = useState(false);
  const listaRef = useRef<HTMLDivElement>(null);

  async function carregarBadges() {
    try {
      const { por_setor } = await InboxInternoService.contadores();
      const m: Record<string, number> = {};
      for (const row of por_setor) m[row.setor] = Number(row.total);
      setBadges(m);
    } catch { /* silent */ }
  }

  async function carregarMensagens(setor: string, naoLidas: boolean) {
    setLoading(true);
    try {
      const rows = await InboxInternoService.listBySetor(setor, naoLidas || undefined);
      setMensagens(rows);
    } catch { /* silent */ }
    finally { setLoading(false) }
  }

  useEffect(() => {
    carregarBadges();
    carregarMensagens(setorAtivo, somenteNaoLidas);
    const iv = setInterval(carregarBadges, 30_000);
    return () => clearInterval(iv);
  }, []);

  useEffect(() => {
    carregarMensagens(setorAtivo, somenteNaoLidas);
  }, [setorAtivo, somenteNaoLidas]);

  async function lerMensagem(id: number) {
    await InboxInternoService.marcarLida(id);
    setMensagens(prev => prev.map(m => m.id === id ? { ...m, lida: true } : m));
    carregarBadges();
  }

  async function lerTodasSetor() {
    await InboxInternoService.marcarTodasSetor(setorAtivo);
    setMensagens(prev => prev.map(m => ({ ...m, lida: true })));
    carregarBadges();
  }

  function onSent() {
    carregarMensagens(setorAtivo, somenteNaoLidas);
  }

  const naoLidasSetor = mensagens.filter(m => !m.lida).length;

  return (
    <div className="flex h-screen bg-black overflow-hidden">
      {showHelp && <InboxInternoHelpModal onClose={() => setShowHelp(false)} />}

      {/* ── Sidebar setores ──────────────────────────────────────────────────── */}
      <div className="w-52 shrink-0 bg-slate-950 border-r border-white/10 flex flex-col">
        {/* MON-01 — Alerta de chats sem resposta */}
        <WppSemResposta />
        <div className="px-4 py-3 border-b border-white/10 flex items-center gap-2">
          <h2 className="text-sm font-black text-white flex items-center gap-2 flex-1">
            <Inbox size={15} className="text-amber-400" /> Inbox
          </h2>
          <button
            onClick={() => setShowHelp(true)}
            title="Ajuda"
            className="p-1 rounded-full text-slate-600 hover:text-amber-400 hover:bg-white/5 transition-colors"
          >
            <HelpCircle size={14} />
          </button>
        </div>
        <div className="flex-1 overflow-y-auto py-2">
          {SETORES.map(s => (
            <button
              key={s.id}
              onClick={() => setSetorAtivo(s.id)}
              className={`w-full flex items-center gap-2.5 px-4 py-2.5 text-left transition-colors
                ${setorAtivo === s.id
                  ? 'bg-amber-500/10 text-amber-400'
                  : 'text-slate-400 hover:text-white hover:bg-white/3'
                }`}
            >
              <span className="text-base leading-none">{s.emoji}</span>
              <span className="text-sm font-medium flex-1">{s.label}</span>
              {badges[s.id] > 0 && (
                <span className="bg-rose-500 text-white text-[10px] font-black px-1.5 py-0.5 rounded-full leading-none">
                  {badges[s.id]}
                </span>
              )}
              {setorAtivo === s.id && <ChevronRight size={12} className="shrink-0" />}
            </button>
          ))}
        </div>
      </div>

      {/* ── Área principal ───────────────────────────────────────────────────── */}
      <div className="flex-1 flex flex-col min-w-0">

        {/* Header do setor */}
        <div className="flex items-center justify-between gap-3 px-5 py-3 border-b border-white/10 bg-slate-950/60">
          <div className="flex items-center gap-2">
            <span className="text-lg leading-none">
              {SETORES.find(s => s.id === setorAtivo)?.emoji}
            </span>
            <span className="font-bold text-white">
              {SETORES.find(s => s.id === setorAtivo)?.label}
            </span>
            {badges[setorAtivo] > 0 && (
              <span className="bg-rose-500/10 text-rose-400 border border-rose-500/20 text-xs px-2 py-0.5 rounded-full font-bold">
                {badges[setorAtivo]} não lida{badges[setorAtivo] > 1 ? 's' : ''}
              </span>
            )}
          </div>
          <div className="flex items-center gap-2">
            <label className="flex items-center gap-1.5 text-xs text-slate-400 cursor-pointer select-none">
              <input
                type="checkbox"
                checked={somenteNaoLidas}
                onChange={e => setSomenteNaoLidas(e.target.checked)}
                className="accent-amber-500"
              />
              Só não lidas
            </label>
            {naoLidasSetor > 0 && (
              <button
                onClick={lerTodasSetor}
                className="flex items-center gap-1.5 text-xs text-emerald-400 hover:text-emerald-300 transition-colors"
              >
                <CheckCheck size={13} /> Marcar todas lidas
              </button>
            )}
            <button
              onClick={() => carregarMensagens(setorAtivo, somenteNaoLidas)}
              className="p-1.5 text-slate-500 hover:text-white rounded-lg hover:bg-white/5 transition-colors"
            >
              <RefreshCw size={13} />
            </button>
          </div>
        </div>

        {/* Lista de mensagens */}
        <div ref={listaRef} className="flex-1 overflow-y-auto">
          {loading ? (
            <div className="flex items-center justify-center py-20">
              <div className="w-6 h-6 border-2 border-amber-500 border-t-transparent rounded-full animate-spin" />
            </div>
          ) : mensagens.length === 0 ? (
            <div className="flex flex-col items-center justify-center py-20 gap-3 text-slate-600">
              <MessageSquare size={36} className="opacity-30" />
              <p className="text-sm">Nenhuma mensagem{somenteNaoLidas ? ' não lida' : ''} neste setor.</p>
            </div>
          ) : (
            mensagens.map(m => (
              <MsgRow key={m.id} msg={m} onLer={lerMensagem} />
            ))
          )}
        </div>

        {/* Compose */}
        <ComposePanel setorAtivo={setorAtivo} onSent={onSent} />
      </div>
    </div>
  );
}
