import { useState, useEffect, useCallback } from 'react';
import {
  Users, Plus, Edit2, Trash2, RefreshCw, X, Check,
  UserCheck, Shield, Eye, Briefcase, Phone, Mail, Link2,
} from 'lucide-react';
import { AccountsService, SectorsService, TeamMembersService, NwTeamsService } from '../services/api';
import type { NwSector } from '../services/api';

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

const ROLES = [
  { value: 'owner',      label: 'Owner',      icon: Shield },
  { value: 'manager',    label: 'Gerente',     icon: Shield },
  { value: 'supervisor', label: 'Supervisor',  icon: UserCheck },
  { value: 'secretary',  label: 'Secretária',  icon: Briefcase },
  { value: 'agent',      label: 'Agente',      icon: Users },
  { value: 'viewer',     label: 'Visualizador',icon: Eye },
];

const AVAIL_COLOR: Record<string, string> = {
  online:  'bg-emerald-500',
  busy:    'bg-yellow-500',
  offline: 'bg-slate-500',
};

const AVAIL_LABEL: Record<string, string> = {
  online:  'Online',
  busy:    'Ocupado',
  offline: 'Offline',
};

function RoleBadge({ role }: { role: string }) {
  const r = ROLES.find(x => x.value === role) || ROLES[4];
  const colors: Record<string, string> = {
    owner:      'bg-violet-500/20 text-violet-300 border-violet-500/30',
    manager:    'bg-blue-500/20 text-blue-300 border-blue-500/30',
    supervisor: 'bg-cyan-500/20 text-cyan-300 border-cyan-500/30',
    secretary:  'bg-teal-500/20 text-teal-300 border-teal-500/30',
    agent:      'bg-slate-700 text-slate-300 border-slate-600',
    viewer:     'bg-slate-800 text-slate-400 border-slate-700',
  };
  return (
    <span className={`text-xs px-2 py-0.5 rounded-full border font-medium ${colors[role] || colors.agent}`}>
      {r.label}
    </span>
  );
}

// ─── Modal de criação/edição ──────────────────────────────────────────────────

function AccountModal({ account, sectors, nwSectors, onClose, onSave }: {
  account: any | null;
  sectors: any[];
  nwSectors: NwSector[];
  onClose: () => void;
  onSave: () => void;
}) {
  const isEdit = !!account;
  const [form, setForm] = useState({
    name:        account?.name        || '',
    email:       account?.email       || '',
    password:    '',
    role:        account?.role        || 'agent',
    phone:       account?.phone       || '',
    avatar_url:  account?.avatar_url  || '',
    active:      account?.active      !== false,
    nw_sector_id: account?.nw_sector_id || '',
    nw_team_id:   account?.nw_team_id   || '',
    sector_id:   '',
    sector_function: '',
  });
  const [saving, setSaving] = useState(false);
  const [error, setError]   = useState('');

  const selectedNwSector = nwSectors.find(s => s.id === form.nw_sector_id);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!form.name.trim()) { setError('Nome é obrigatório'); return; }
    setSaving(true); setError('');
    try {
      const payload: any = {
        name: form.name.trim(), email: form.email || undefined,
        role: form.role, phone: form.phone || undefined,
        avatar_url: form.avatar_url || undefined, active: form.active,
        nw_sector_id: form.nw_sector_id || null,
        nw_team_id:   form.nw_team_id   || null,
      };
      if (!isEdit || form.password) payload.password = form.password || undefined;

      if (isEdit) {
        await AccountsService.update(account.id, payload);
      } else {
        if (!form.password) { setError('Senha é obrigatória para novo colaborador'); setSaving(false); return; }
        const created = await AccountsService.create({ ...payload, password: form.password });
        if (form.sector_id) {
          await TeamMembersService.add({
            account_id: created.id,
            sector_id: parseInt(form.sector_id),
            function: form.sector_function || undefined,
          });
        }
      }
      onSave();
    } catch (e: any) {
      setError(e?.response?.data?.error || 'Erro ao salvar');
    } finally {
      setSaving(false);
    }
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-4">
      <div className="bg-slate-900 border border-slate-700 rounded-2xl w-full max-w-lg shadow-2xl">
        <div className="flex items-center justify-between p-5 border-b border-slate-800">
          <h2 className="text-white font-semibold text-lg">
            {isEdit ? 'Editar Colaborador' : 'Novo Colaborador'}
          </h2>
          <button onClick={onClose} className="text-slate-400 hover:text-white"><X size={20} /></button>
        </div>

        <form onSubmit={handleSubmit} className="p-5 space-y-4 max-h-[75vh] overflow-y-auto">
          {error && <div className="bg-red-500/10 border border-red-500/30 text-red-400 text-sm px-3 py-2 rounded-lg">{error}</div>}

          <div className="grid grid-cols-2 gap-3">
            <div className="col-span-2">
              <label className="text-xs text-slate-400 mb-1 block">Nome *</label>
              <input value={form.name} onChange={e => setForm(f => ({ ...f, name: e.target.value }))}
                className="w-full bg-slate-800 border border-slate-700 rounded-lg px-3 py-2 text-white text-sm focus:outline-none focus:border-cyan-500" placeholder="Nome completo" />
            </div>
            <div>
              <label className="text-xs text-slate-400 mb-1 block">E-mail</label>
              <input value={form.email} onChange={e => setForm(f => ({ ...f, email: e.target.value }))}
                className="w-full bg-slate-800 border border-slate-700 rounded-lg px-3 py-2 text-white text-sm focus:outline-none focus:border-cyan-500" placeholder="email@exemplo.com" />
            </div>
            <div>
              <label className="text-xs text-slate-400 mb-1 block">{isEdit ? 'Nova senha (deixe vazio para manter)' : 'Senha *'}</label>
              <input type="password" value={form.password} onChange={e => setForm(f => ({ ...f, password: e.target.value }))}
                className="w-full bg-slate-800 border border-slate-700 rounded-lg px-3 py-2 text-white text-sm focus:outline-none focus:border-cyan-500" placeholder="••••••••" />
            </div>
            <div>
              <label className="text-xs text-slate-400 mb-1 block">Função / Role</label>
              <select value={form.role} onChange={e => setForm(f => ({ ...f, role: e.target.value }))}
                className="w-full bg-slate-800 border border-slate-700 rounded-lg px-3 py-2 text-white text-sm focus:outline-none focus:border-cyan-500">
                {ROLES.map(r => <option className="bg-slate-900 text-white" key={r.value} value={r.value}>{r.label}</option>)}
              </select>
            </div>
            <div>
              <label className="text-xs text-slate-400 mb-1 block">Telefone</label>
              <input value={form.phone} onChange={e => setForm(f => ({ ...f, phone: e.target.value }))}
                className="w-full bg-slate-800 border border-slate-700 rounded-lg px-3 py-2 text-white text-sm focus:outline-none focus:border-cyan-500" placeholder="(67) 9 9999-9999" />
            </div>
          </div>

          {/* Vínculo com Setor Interno */}
          {!isEdit && sectors.length > 0 && (
            <div className="border-t border-slate-800 pt-4">
              <label className="text-xs text-slate-400 mb-2 block font-medium">Atribuir ao Setor Interno (opcional)</label>
              <div className="grid grid-cols-2 gap-3">
                <select value={form.sector_id} onChange={e => setForm(f => ({ ...f, sector_id: e.target.value }))}
                  className="w-full bg-slate-800 border border-slate-700 rounded-lg px-3 py-2 text-white text-sm focus:outline-none focus:border-cyan-500">
                  <option className="bg-slate-900 text-white" value="">Nenhum setor</option>
                  {sectors.map((s: any) => <option className="bg-slate-900 text-white" key={s.id} value={s.id}>{s.name}</option>)}
                </select>
                <input value={form.sector_function} onChange={e => setForm(f => ({ ...f, sector_function: e.target.value }))}
                  className="w-full bg-slate-800 border border-slate-700 rounded-lg px-3 py-2 text-white text-sm focus:outline-none focus:border-cyan-500" placeholder="Função no setor" />
              </div>
            </div>
          )}

          {/* Vínculo com WA-Inbox */}
          {nwSectors.length > 0 && (
            <div className="border-t border-slate-800 pt-4">
              <label className="text-xs text-slate-400 mb-2 flex items-center gap-1.5 font-medium">
                <Link2 size={12} /> Vincular à Equipe WA-Inbox (opcional)
              </label>
              <div className="grid grid-cols-2 gap-3">
                <select value={form.nw_sector_id}
                  onChange={e => setForm(f => ({ ...f, nw_sector_id: e.target.value, nw_team_id: '' }))}
                  className="w-full bg-slate-800 border border-slate-700 rounded-lg px-3 py-2 text-white text-sm focus:outline-none focus:border-cyan-500">
                  <option className="bg-slate-900 text-white" value="">Setor WA-Inbox</option>
                  {nwSectors.map(s => <option className="bg-slate-900 text-white" key={s.id} value={s.id}>{s.name}</option>)}
                </select>
                <select value={form.nw_team_id} onChange={e => setForm(f => ({ ...f, nw_team_id: e.target.value }))}
                  className="w-full bg-slate-800 border border-slate-700 rounded-lg px-3 py-2 text-white text-sm focus:outline-none focus:border-cyan-500"
                  disabled={!selectedNwSector}>
                  <option className="bg-slate-900 text-white" value="">Equipe WA-Inbox</option>
                  {(selectedNwSector?.teams || []).map(t => <option className="bg-slate-900 text-white" key={t.id} value={t.id}>{t.name}</option>)}
                </select>
              </div>
            </div>
          )}

          {isEdit && (
            <div className="flex items-center gap-2 pt-1">
              <input type="checkbox" id="active-toggle" checked={form.active}
                onChange={e => setForm(f => ({ ...f, active: e.target.checked }))}
                className="w-4 h-4 accent-cyan-500" />
              <label htmlFor="active-toggle" className="text-sm text-slate-300">Conta ativa</label>
            </div>
          )}

          <div className="flex justify-end gap-2 pt-2">
            <button type="button" onClick={onClose}
              className="px-4 py-2 rounded-lg border border-slate-700 text-slate-300 text-sm hover:bg-slate-800">
              Cancelar
            </button>
            <button type="submit" disabled={saving}
              className="px-4 py-2 rounded-lg bg-cyan-600 hover:bg-cyan-500 text-white text-sm font-medium flex items-center gap-2 disabled:opacity-50">
              {saving ? <RefreshCw size={14} className="animate-spin" /> : <Check size={14} />}
              {isEdit ? 'Salvar' : 'Criar'}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}

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

export default function EquipePage() {
  const [accounts, setAccounts]   = useState<any[]>([]);
  const [sectors,  setSectors]    = useState<any[]>([]);
  const [nwSectors, setNwSectors] = useState<NwSector[]>([]);
  const [loading,  setLoading]    = useState(true);
  const [search,   setSearch]     = useState('');
  const [filterRole, setFilterRole] = useState('');
  const [modalAcc, setModalAcc]   = useState<any | null | false>(false); // false = fechado
  const [deleting, setDeleting]   = useState<number | null>(null);

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const [accs, secs, nwSecs] = await Promise.all([
        AccountsService.list(),
        SectorsService.list(),
        NwTeamsService.list().catch(() => []),
      ]);
      setAccounts(accs);
      setSectors(secs);
      setNwSectors(nwSecs);
    } finally {
      setLoading(false);
    }
  }, []);

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

  async function handleDelete(id: number) {
    if (!confirm('Remover este colaborador? Esta ação não pode ser desfeita.')) return;
    setDeleting(id);
    try {
      await AccountsService.remove(id);
      setAccounts(a => a.filter(x => x.id !== id));
    } finally {
      setDeleting(null);
    }
  }

  const filtered = accounts.filter(a => {
    const matchSearch = !search || a.name.toLowerCase().includes(search.toLowerCase()) ||
      (a.email || '').toLowerCase().includes(search.toLowerCase());
    const matchRole = !filterRole || a.role === filterRole;
    return matchSearch && matchRole;
  });

  // Mapa de nwSector/nwTeam para label
  function getNwLabel(acc: any) {
    if (!acc.nw_team_id && !acc.nw_sector_id) return null;
    const sec = nwSectors.find(s => s.id === acc.nw_sector_id);
    const team = sec?.teams.find(t => t.id === acc.nw_team_id);
    if (sec && team) return `${sec.name} › ${team.name}`;
    if (sec) return sec.name;
    return null;
  }

  return (
    <div className="p-6 max-w-6xl mx-auto space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-white flex items-center gap-2">
            <Users size={24} className="text-cyan-400" /> Equipe
          </h1>
          <p className="text-slate-400 text-sm mt-0.5">{accounts.length} colaborador{accounts.length !== 1 ? 'es' : ''} cadastrado{accounts.length !== 1 ? 's' : ''}</p>
        </div>
        <div className="flex items-center gap-2">
          <button onClick={load} className="p-2 rounded-lg border border-slate-700 text-slate-400 hover:text-white hover:bg-slate-800">
            <RefreshCw size={16} className={loading ? 'animate-spin' : ''} />
          </button>
          <button onClick={() => setModalAcc(null)}
            className="flex items-center gap-2 px-4 py-2 bg-cyan-600 hover:bg-cyan-500 text-white rounded-lg text-sm font-medium">
            <Plus size={16} /> Novo Colaborador
          </button>
        </div>
      </div>

      {/* Filtros */}
      <div className="flex flex-wrap gap-3">
        <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Buscar por nome ou e-mail..."
          className="flex-1 min-w-48 bg-slate-800 border border-slate-700 rounded-lg px-3 py-2 text-white text-sm focus:outline-none focus:border-cyan-500" />
        <select value={filterRole} onChange={e => setFilterRole(e.target.value)}
          className="bg-slate-800 border border-slate-700 rounded-lg px-3 py-2 text-white text-sm focus:outline-none focus:border-cyan-500">
          <option className="bg-slate-900 text-white" value="">Todas as funções</option>
          {ROLES.map(r => <option className="bg-slate-900 text-white" key={r.value} value={r.value}>{r.label}</option>)}
        </select>
      </div>

      {/* Tabela */}
      {loading ? (
        <div className="flex items-center justify-center py-16 text-slate-400">
          <RefreshCw size={24} className="animate-spin mr-3" /> Carregando...
        </div>
      ) : filtered.length === 0 ? (
        <div className="text-center py-16 text-slate-500">
          <Users size={40} className="mx-auto mb-3 opacity-30" />
          <p>Nenhum colaborador encontrado.</p>
        </div>
      ) : (
        <div className="bg-slate-900 border border-slate-800 rounded-2xl overflow-hidden">
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-slate-800 text-slate-400 text-xs uppercase tracking-wider">
                <th className="text-left px-5 py-3">Colaborador</th>
                <th className="text-left px-4 py-3">Função</th>
                <th className="text-left px-4 py-3">Setores</th>
                <th className="text-left px-4 py-3 hidden lg:table-cell">WA-Inbox</th>
                <th className="text-left px-4 py-3 hidden md:table-cell">Status</th>
                <th className="px-4 py-3" />
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-800/60">
              {filtered.map(acc => {
                const initials = acc.name.split(' ').map((n: string) => n[0]).slice(0, 2).join('').toUpperCase();
                const nwLabel = getNwLabel(acc);
                return (
                  <tr key={acc.id} className={`hover:bg-slate-800/40 transition-colors ${!acc.active ? 'opacity-50' : ''}`}>
                    <td className="px-5 py-3">
                      <div className="flex items-center gap-3">
                        <div className="relative">
                          {acc.avatar_url
                            ? <img src={acc.avatar_url} className="w-9 h-9 rounded-full object-cover" />
                            : <div className="w-9 h-9 rounded-full bg-slate-700 flex items-center justify-center text-slate-300 font-semibold text-xs">{initials}</div>
                          }
                          <span className={`absolute -bottom-0.5 -right-0.5 w-2.5 h-2.5 rounded-full border-2 border-slate-900 ${AVAIL_COLOR[acc.availability] || AVAIL_COLOR.offline}`} />
                        </div>
                        <div>
                          <p className="text-white font-medium leading-tight">{acc.name}</p>
                          {acc.email && <p className="text-slate-500 text-xs flex items-center gap-1"><Mail size={10} />{acc.email}</p>}
                          {acc.phone && <p className="text-slate-500 text-xs flex items-center gap-1"><Phone size={10} />{acc.phone}</p>}
                        </div>
                      </div>
                    </td>
                    <td className="px-4 py-3"><RoleBadge role={acc.role} /></td>
                    <td className="px-4 py-3">
                      <div className="flex flex-wrap gap-1">
                        {(acc.sectors || []).slice(0, 2).map((s: any) => (
                          <span key={s.sector_id} className={`text-xs px-2 py-0.5 rounded-full border ${s.on_duty ? 'bg-emerald-500/10 text-emerald-400 border-emerald-500/30' : 'bg-slate-800 text-slate-400 border-slate-700'}`}>
                            {s.sector_name}
                          </span>
                        ))}
                        {(acc.sectors || []).length > 2 && <span className="text-xs text-slate-500">+{acc.sectors.length - 2}</span>}
                        {(acc.sectors || []).length === 0 && <span className="text-xs text-slate-600 italic">Sem setor</span>}
                      </div>
                    </td>
                    <td className="px-4 py-3 hidden lg:table-cell">
                      {nwLabel
                        ? <span className="text-xs text-cyan-400 flex items-center gap-1"><Link2 size={10} />{nwLabel}</span>
                        : <span className="text-xs text-slate-600 italic">—</span>
                      }
                    </td>
                    <td className="px-4 py-3 hidden md:table-cell">
                      <span className="text-xs text-slate-400">{AVAIL_LABEL[acc.availability] || 'Offline'}</span>
                    </td>
                    <td className="px-4 py-3">
                      <div className="flex items-center gap-1 justify-end">
                        <button onClick={() => setModalAcc(acc)}
                          className="p-1.5 rounded-lg text-slate-400 hover:text-cyan-400 hover:bg-slate-800">
                          <Edit2 size={14} />
                        </button>
                        <button onClick={() => handleDelete(acc.id)} disabled={deleting === acc.id}
                          className="p-1.5 rounded-lg text-slate-400 hover:text-red-400 hover:bg-slate-800 disabled:opacity-40">
                          <Trash2 size={14} />
                        </button>
                      </div>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      )}

      {/* Modal */}
      {modalAcc !== false && (
        <AccountModal
          account={modalAcc}
          sectors={sectors}
          nwSectors={nwSectors}
          onClose={() => setModalAcc(false)}
          onSave={() => { setModalAcc(false); load(); }}
        />
      )}
    </div>
  );
}
