import { useEffect, useMemo, useState } from 'react';
import { Search, AlertTriangle, Check, Clock, UserCircle2 } from 'lucide-react';
import { CotacaoService } from '../services/api';

type Funcao = 'separador' | 'embalador' | 'auditor' | 'fiscal' | 'expedidor';

type Colaborador = {
  id: number; name: string; email: string | null; role: string;
  availability: 'online' | 'busy' | 'offline';
  avatar_url: string | null; phone_connected: boolean; on_duty: boolean;
  pedidos_ativos: number; ultimo_pedido_em: string | null;
};

const STATUS_DOT: Record<string, string> = {
  online:  'bg-emerald-400',
  busy:    'bg-amber-400',
  offline: 'bg-slate-600',
};

const STATUS_LABEL: Record<string, string> = {
  online:  'Disponível',
  busy:    'Ocupado',
  offline: 'Offline',
};

function rankColaborador(c: Colaborador): number {
  const avail = c.availability === 'online' ? 0 : c.availability === 'busy' ? 2 : 4;
  const duty  = c.on_duty ? 0 : 1;
  return avail + duty;
}

function fmtMinutosAtras(iso: string | null): string {
  if (!iso) return '';
  const min = Math.floor((Date.now() - new Date(iso).getTime()) / 60000);
  if (min < 1) return 'agora';
  if (min < 60) return `há ${min}min`;
  const h = Math.floor(min / 60);
  if (h < 24) return `há ${h}h`;
  return `há ${Math.floor(h / 24)}d`;
}

export default function SelectColaborador({
  funcao, value, onChange, allowSelf, accentColor = 'cyan',
}: {
  funcao: Funcao;
  value: number | null;
  onChange: (accountId: number | null, nome?: string) => void;
  allowSelf?: { id: number; nome: string };
  accentColor?: 'cyan' | 'purple' | 'orange' | 'teal' | 'emerald';
}) {
  const [data, setData]       = useState<Awaited<ReturnType<typeof CotacaoService.listColaboradores>> | null>(null);
  const [loading, setLoading] = useState(true);
  const [busca, setBusca]     = useState('');
  const [open, setOpen]       = useState(false);

  useEffect(() => {
    let alive = true;
    setLoading(true);
    CotacaoService.listColaboradores(funcao)
      .then(d => { if (alive) setData(d); })
      .catch(() => { if (alive) setData({ configurado: false, colaboradores: [] }); })
      .finally(() => { if (alive) setLoading(false); });
    return () => { alive = false; };
  }, [funcao]);

  const lista = useMemo(() => {
    const arr = (data?.colaboradores || []).slice().sort((a, b) => {
      const r = rankColaborador(a) - rankColaborador(b);
      if (r !== 0) return r;
      return a.pedidos_ativos - b.pedidos_ativos;
    });
    if (!busca.trim()) return arr;
    const q = busca.toLowerCase();
    return arr.filter(c => c.name.toLowerCase().includes(q) || (c.email || '').toLowerCase().includes(q));
  }, [data, busca]);

  const selecionado = data?.colaboradores.find(c => c.id === value) || null;

  const accentMap: Record<string, { ring: string; bg: string; text: string; border: string }> = {
    cyan:    { ring: 'focus:border-cyan-500',    bg: 'bg-cyan-500/10',    text: 'text-cyan-400',    border: 'border-cyan-500/30' },
    purple:  { ring: 'focus:border-purple-500',  bg: 'bg-purple-500/10',  text: 'text-purple-400',  border: 'border-purple-500/30' },
    orange:  { ring: 'focus:border-orange-500',  bg: 'bg-orange-500/10',  text: 'text-orange-400',  border: 'border-orange-500/30' },
    teal:    { ring: 'focus:border-teal-500',    bg: 'bg-teal-500/10',    text: 'text-teal-400',    border: 'border-teal-500/30' },
    emerald: { ring: 'focus:border-emerald-500', bg: 'bg-emerald-500/10', text: 'text-emerald-400', border: 'border-emerald-500/30' },
  };
  const ac = accentMap[accentColor];

  // Caso a lista venha vazia: significa que nenhum colaborador tem o setor
  // correspondente vinculado em /admin-v2/equipe → guia o admin a corrigir.
  if (!loading && data && data.colaboradores.length === 0) {
    return (
      <div className="bg-amber-500/10 border border-amber-500/30 rounded-2xl p-4 space-y-2">
        <div className="flex items-start gap-2">
          <AlertTriangle size={14} className="text-amber-400 shrink-0 mt-0.5" />
          <div className="flex-1">
            <p className="text-xs font-black text-amber-400 uppercase tracking-widest">Nenhum colaborador para "{funcao}"</p>
            <p className="text-xs text-amber-400/80 mt-1">
              Vincule colaboradores ao setor correspondente em <strong>Equipe → editar colaborador</strong>.
            </p>
            {data.setores_aceitos && (
              <p className="text-xs text-amber-400/60 mt-1">
                Setores aceitos: <strong>{data.setores_aceitos.join(', ')}</strong>
              </p>
            )}
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-2">
      {/* Botão / display do selecionado */}
      <button
        type="button"
        onClick={() => setOpen(o => !o)}
        className={`w-full bg-slate-800 border border-slate-700 rounded-xl px-3 py-2.5 text-left transition-colors hover:border-slate-600 ${ac.ring}`}>
        {selecionado ? (
          <div className="flex items-center gap-2.5">
            <div className="relative shrink-0">
              {selecionado.avatar_url ? (
                <img src={selecionado.avatar_url} alt="" className="w-8 h-8 rounded-full object-cover" />
              ) : (
                <div className="w-8 h-8 rounded-full bg-slate-700 flex items-center justify-center">
                  <UserCircle2 size={20} className="text-slate-500" />
                </div>
              )}
              <span className={`absolute -bottom-0.5 -right-0.5 w-2.5 h-2.5 rounded-full ring-2 ring-slate-800 ${STATUS_DOT[selecionado.availability]}`} />
            </div>
            <div className="flex-1 min-w-0">
              <p className="text-sm font-bold text-white truncate">{selecionado.name}</p>
              <p className="text-[10px] text-slate-500">{STATUS_LABEL[selecionado.availability]} · {selecionado.pedidos_ativos} ativos</p>
            </div>
            <Check size={14} className={ac.text} />
          </div>
        ) : (
          <div className="flex items-center gap-2 text-slate-500">
            <UserCircle2 size={18} />
            <span className="text-sm">Selecionar colaborador…</span>
          </div>
        )}
      </button>

      {/* Botão "Eu mesmo" — atalho rápido */}
      {allowSelf && !selecionado && (
        <button
          type="button"
          onClick={() => onChange(allowSelf.id, allowSelf.nome)}
          className={`w-full text-xs font-bold py-2 rounded-xl border ${ac.bg} ${ac.text} ${ac.border} hover:opacity-80 transition-opacity`}>
          Atribuir a mim mesmo
        </button>
      )}

      {/* Painel expansível com busca + lista */}
      {open && (
        <div className="bg-slate-900 border border-slate-700 rounded-xl overflow-hidden">
          <div className="p-2 border-b border-slate-800">
            <div className="relative">
              <Search size={12} className="absolute left-2.5 top-1/2 -translate-y-1/2 text-slate-500" />
              <input
                value={busca}
                onChange={e => setBusca(e.target.value)}
                placeholder="Buscar por nome ou email…"
                className="w-full bg-slate-800 border border-slate-700 rounded-lg pl-7 pr-2 py-1.5 text-xs text-white focus:outline-none focus:border-slate-500"
                autoFocus
              />
            </div>
          </div>

          {loading ? (
            <div className="py-6 text-center text-xs text-slate-500">Carregando…</div>
          ) : lista.length === 0 ? (
            <div className="py-6 text-center text-xs text-slate-500">
              {busca ? 'Nenhum colaborador encontrado' : 'Nenhum colaborador na equipe'}
            </div>
          ) : (
            <ul className="max-h-64 overflow-y-auto">
              {lista.map(c => {
                const sel = value === c.id;
                return (
                  <li key={c.id}>
                    <button
                      type="button"
                      onClick={() => { onChange(c.id, c.name); setOpen(false); setBusca(''); }}
                      className={`w-full flex items-center gap-2.5 px-3 py-2 text-left transition-colors hover:bg-slate-800/60 ${sel ? 'bg-slate-800' : ''}`}>
                      <div className="relative shrink-0">
                        {c.avatar_url ? (
                          <img src={c.avatar_url} alt="" className="w-7 h-7 rounded-full object-cover" />
                        ) : (
                          <div className="w-7 h-7 rounded-full bg-slate-700 flex items-center justify-center">
                            <UserCircle2 size={16} className="text-slate-500" />
                          </div>
                        )}
                        <span className={`absolute -bottom-0.5 -right-0.5 w-2 h-2 rounded-full ring-2 ring-slate-900 ${STATUS_DOT[c.availability]}`} />
                      </div>

                      <div className="flex-1 min-w-0">
                        <div className="flex items-center gap-1.5">
                          <p className="text-xs font-bold text-white truncate">{c.name}</p>
                          {c.on_duty && <span className="text-[9px] font-black text-emerald-400 bg-emerald-500/10 px-1 rounded">PLANTÃO</span>}
                        </div>
                        <div className="flex items-center gap-2 text-[10px] text-slate-500 mt-0.5">
                          <span>{STATUS_LABEL[c.availability]}</span>
                          <span>·</span>
                          <span className={c.pedidos_ativos > 0 ? 'text-amber-400' : ''}>{c.pedidos_ativos} ativos</span>
                          {c.ultimo_pedido_em && (
                            <>
                              <span>·</span>
                              <span className="flex items-center gap-0.5"><Clock size={8} />{fmtMinutosAtras(c.ultimo_pedido_em)}</span>
                            </>
                          )}
                        </div>
                      </div>

                      {sel && <Check size={14} className={ac.text} />}
                    </button>
                  </li>
                );
              })}
            </ul>
          )}

          {selecionado && (
            <div className="p-2 border-t border-slate-800">
              <button
                type="button"
                onClick={() => { onChange(null); setOpen(false); }}
                className="w-full text-[11px] text-slate-500 hover:text-rose-400 transition-colors py-1">
                Limpar seleção
              </button>
            </div>
          )}
        </div>
      )}
    </div>
  );
}
