import React, { useState, useEffect, useCallback } from 'react'
import {
  Users, Briefcase, Network, Brain, BarChart2,
  Plus, Edit2, Trash2, Check, X, ToggleLeft, ToggleRight,
  Wifi, Shield, Eye, UserCheck,
  ClipboardList, Headphones, Star, Link2,
} from 'lucide-react'
import { AccountsService, SectorsService, TeamMembersService, AdminMeService } from '../services/api'

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

// 'meu-perfil' é o sub-tab onde o admin vincula sua conta de colaborador.
// Isso permite que o admin acesse a Inbox Interna sem fazer login duplo.
type EquipeSub = 'contas' | 'setores' | 'membros' | 'cerebros' | 'performance' | 'meu-perfil'

interface Account {
  id: number; name: string; email: string | null; role: string;
  phone: string | null; phone_connected: boolean; availability: string;
  avatar_url: string | null; active: boolean; created_at: string;
  sectors: Array<{ sector_id: number; sector_name: string; function: string; is_primary: boolean; on_duty: boolean }>
}

interface Sector {
  id: number; name: string; description: string | null; icon: string;
  color: string; sla_minutes: number; sort_order: number; active: boolean;
  member_count: number; created_at: string;
}

interface TeamMember {
  id: number; account_id: number; sector_id: number;
  function: string | null; is_primary: boolean; on_duty: boolean;
  notify_escalation: boolean; notify_human_api: boolean;
  account_name: string; account_email: string; account_role: string;
  availability: string; phone_connected: boolean;
  sector_name: string; sector_color: string; sector_icon: string;
}

interface BrainNode {
  id: number; sector_id: number; type: string; content: string;
  sort_order: number; active: boolean;
}

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

const ROLE_LABELS: Record<string, { label: string; color: string; Icon: any }> = {
  owner:      { label: 'Dono',         color: 'bg-yellow-500/20 text-yellow-300 border-yellow-500/30', Icon: Star },
  manager:    { label: 'Gerente',      color: 'bg-purple-500/20 text-purple-300 border-purple-500/30', Icon: Shield },
  supervisor: { label: 'Supervisor',   color: 'bg-blue-500/20 text-blue-300 border-blue-500/30',       Icon: Eye },
  secretary:  { label: 'Secretária',   color: 'bg-cyan-500/20 text-cyan-300 border-cyan-500/30',       Icon: ClipboardList },
  agent:      { label: 'Atendente',    color: 'bg-green-500/20 text-green-300 border-green-500/30',    Icon: Headphones },
  viewer:     { label: 'Visualizador', color: 'bg-slate-500/20 text-slate-300 border-slate-500/30',    Icon: Eye },
}

const AVAIL_DOT: Record<string, string> = {
  online: 'bg-green-400', busy: 'bg-yellow-400', offline: 'bg-slate-500',
}

const BRAIN_TYPE_LABELS: Record<string, string> = {
  knowledge: 'Conhecimento', rules: 'Regras', escalation: 'Escalação', persona: 'Persona',
}
const BRAIN_TYPE_COLORS: Record<string, string> = {
  knowledge: 'text-cyan-400 bg-cyan-500/10',
  rules:     'text-yellow-400 bg-yellow-500/10',
  escalation:'text-red-400 bg-red-500/10',
  persona:   'text-purple-400 bg-purple-500/10',
}

function RoleBadge({ role }: { role: string }) {
  const r = ROLE_LABELS[role] || { label: role, color: 'bg-slate-500/20 text-slate-300 border-slate-500/30', Icon: Users }
  const { Icon } = r
  return (
    <span className={`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium border ${r.color}`}>
      <Icon size={10} />
      {r.label}
    </span>
  )
}

// Modal genérico
function Modal({ title, onClose, children }: { title: string; onClose: () => void; children: React.ReactNode }) {
  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-4">
      <div className="bg-slate-800 border border-slate-700 rounded-xl shadow-2xl w-full max-w-lg max-h-[90vh] overflow-y-auto">
        <div className="flex items-center justify-between px-5 py-4 border-b border-slate-700">
          <h2 className="font-semibold text-white">{title}</h2>
          <button onClick={onClose} className="text-slate-400 hover:text-white"><X size={18} /></button>
        </div>
        <div className="p-5">{children}</div>
      </div>
    </div>
  )
}

function Field({ label, children }: { label: string; children: React.ReactNode }) {
  return (
    <div>
      <label className="block text-xs text-slate-400 mb-1">{label}</label>
      {children}
    </div>
  )
}

function Input({ ...props }: React.InputHTMLAttributes<HTMLInputElement>) {
  return (
    <input
      {...props}
      className="w-full bg-slate-900 border border-slate-600 rounded-lg px-3 py-2 text-sm text-white placeholder-slate-500 focus:outline-none focus:border-cyan-500"
    />
  )
}

function Select({ ...props }: React.SelectHTMLAttributes<HTMLSelectElement>) {
  return (
    <select
      {...props}
      className="w-full bg-slate-900 border border-slate-600 rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-cyan-500"
    />
  )
}

function Textarea({ ...props }: React.TextareaHTMLAttributes<HTMLTextAreaElement>) {
  return (
    <textarea
      {...props}
      className="w-full bg-slate-900 border border-slate-600 rounded-lg px-3 py-2 text-sm text-white placeholder-slate-500 focus:outline-none focus:border-cyan-500 resize-none"
    />
  )
}

function Btn({ onClick, variant = 'primary', children, disabled, className = '' }: {
  onClick?: () => void; variant?: 'primary' | 'ghost' | 'danger'; children: React.ReactNode; disabled?: boolean; className?: string
}) {
  const base = 'inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-sm font-medium transition disabled:opacity-50 disabled:cursor-not-allowed'
  const styles = {
    primary: 'bg-cyan-600 hover:bg-cyan-500 text-white',
    ghost:   'bg-slate-700 hover:bg-slate-600 text-slate-200',
    danger:  'bg-red-600/20 hover:bg-red-600/40 text-red-400 border border-red-600/30',
  }
  return <button onClick={onClick} disabled={disabled} className={`${base} ${styles[variant]} ${className}`}>{children}</button>
}

// ─── Sub-aba: CONTAS ──────────────────────────────────────────────────────────

function ContasTab() {
  const [accounts, setAccounts] = useState<Account[]>([])
  const [loading, setLoading]   = useState(true)
  const [modal, setModal]       = useState<'create' | 'edit' | null>(null)
  const [editing, setEditing]   = useState<Account | null>(null)
  const [form, setForm] = useState({ name: '', email: '', password: '', role: 'agent', phone: '' })
  const [saving, setSaving] = useState(false)

  const load = useCallback(async () => {
    setLoading(true)
    try { setAccounts(await AccountsService.list()) } finally { setLoading(false) }
  }, [])

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

  function openCreate() {
    setForm({ name: '', email: '', password: '', role: 'agent', phone: '' })
    setEditing(null); setModal('create')
  }

  function openEdit(a: Account) {
    setForm({ name: a.name, email: a.email||'', password: '', role: a.role, phone: a.phone||'' })
    setEditing(a); setModal('edit')
  }

  async function save() {
    setSaving(true)
    try {
      const data: any = { name: form.name, email: form.email||undefined, role: form.role, phone: form.phone||undefined }
      if (form.password) data.password = form.password
      if (editing) await AccountsService.update(editing.id, data)
      else         await AccountsService.create(data)
      setModal(null); load()
    } catch (e: any) {
      alert(e.response?.data?.error || 'Erro ao salvar')
    } finally { setSaving(false) }
  }

  async function toggleActive(a: Account) {
    await AccountsService.update(a.id, { active: !a.active })
    load()
  }

  async function toggleAvailability(a: Account) {
    const next = a.availability === 'online' ? 'offline' : 'online'
    await AccountsService.update(a.id, { availability: next })
    load()
  }

  async function remove(a: Account) {
    if (!confirm(`Excluir "${a.name}"?`)) return
    await AccountsService.remove(a.id)
    load()
  }

  if (loading) return <div className="flex items-center justify-center h-40 text-slate-400 text-sm">Carregando...</div>

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <p className="text-sm text-slate-400">{accounts.length} colaborador(es)</p>
        <Btn onClick={openCreate}><Plus size={14} /> Nova Conta</Btn>
      </div>

      <div className="grid gap-3">
        {accounts.map(a => {
          return (
            <div key={a.id} className={`flex items-center gap-3 p-3 rounded-xl border ${a.active ? 'bg-slate-800/60 border-slate-700' : 'bg-slate-900/40 border-slate-800 opacity-60'}`}>
              {/* avatar */}
              <div className="relative flex-shrink-0">
                {a.avatar_url
                  ? <img src={a.avatar_url} className="w-10 h-10 rounded-full object-cover" />
                  : <div className="w-10 h-10 rounded-full bg-slate-700 flex items-center justify-center text-slate-300 font-semibold text-sm">
                      {a.name.charAt(0).toUpperCase()}
                    </div>
                }
                <span className={`absolute bottom-0 right-0 w-2.5 h-2.5 rounded-full border-2 border-slate-800 ${AVAIL_DOT[a.availability]||'bg-slate-500'}`} />
              </div>

              {/* info */}
              <div className="flex-1 min-w-0">
                <div className="flex items-center gap-2 flex-wrap">
                  <span className="text-sm font-medium text-white truncate">{a.name}</span>
                  <RoleBadge role={a.role} />
                  {a.phone_connected && (
                    <span className="inline-flex items-center gap-0.5 text-[10px] text-green-400"><Wifi size={10} />WA</span>
                  )}
                </div>
                {a.email && <p className="text-xs text-slate-500 truncate">{a.email}</p>}
                {a.sectors.length > 0 && (
                  <p className="text-xs text-slate-500 truncate">
                    {a.sectors.map(s => s.sector_name).join(', ')}
                  </p>
                )}
              </div>

              {/* ações */}
              <div className="flex items-center gap-1 flex-shrink-0">
                <button onClick={() => toggleAvailability(a)} title={a.availability === 'online' ? 'Online' : 'Offline'}
                  className={`p-1.5 rounded-lg transition ${a.availability === 'online' ? 'text-green-400 hover:bg-green-500/10' : 'text-slate-500 hover:bg-slate-700'}`}>
                  {a.availability === 'online' ? <ToggleRight size={16} /> : <ToggleLeft size={16} />}
                </button>
                <button onClick={() => openEdit(a)} className="p-1.5 rounded-lg text-slate-400 hover:text-white hover:bg-slate-700 transition">
                  <Edit2 size={14} />
                </button>
                <button onClick={() => toggleActive(a)} className="p-1.5 rounded-lg text-slate-400 hover:text-white hover:bg-slate-700 transition" title={a.active ? 'Suspender' : 'Ativar'}>
                  {a.active ? <Check size={14} className="text-green-400" /> : <X size={14} className="text-red-400" />}
                </button>
                <button onClick={() => remove(a)} className="p-1.5 rounded-lg text-slate-400 hover:text-red-400 hover:bg-red-500/10 transition">
                  <Trash2 size={14} />
                </button>
              </div>
            </div>
          )
        })}
        {accounts.length === 0 && (
          <div className="text-center py-12 text-slate-500 text-sm">
            Nenhum colaborador cadastrado.<br />
            <button onClick={openCreate} className="mt-2 text-cyan-400 hover:underline">Criar primeiro</button>
          </div>
        )}
      </div>

      {modal && (
        <Modal title={modal === 'create' ? 'Nova Conta' : 'Editar Conta'} onClose={() => setModal(null)}>
          <div className="space-y-4">
            <Field label="Nome *">
              <Input value={form.name} onChange={e => setForm(f => ({ ...f, name: e.target.value }))} placeholder="Nome completo" />
            </Field>
            <Field label="E-mail (login)">
              <Input type="email" value={form.email} onChange={e => setForm(f => ({ ...f, email: e.target.value }))} placeholder="email@empresa.com" />
            </Field>
            <Field label={modal === 'edit' ? 'Nova senha (deixe em branco para manter)' : 'Senha'}>
              <Input type="password" value={form.password} onChange={e => setForm(f => ({ ...f, password: e.target.value }))} placeholder="••••••••" />
            </Field>
            <Field label="WhatsApp pessoal">
              <Input value={form.phone} onChange={e => setForm(f => ({ ...f, phone: e.target.value }))} placeholder="5511999990000" />
            </Field>
            <Field label="Cargo">
              <Select value={form.role} onChange={e => setForm(f => ({ ...f, role: e.target.value }))}>
                {Object.entries(ROLE_LABELS).map(([v, r]) => (
                  <option className="bg-slate-900 text-white" key={v} value={v}>{r.label}</option>
                ))}
              </Select>
            </Field>
            <div className="flex justify-end gap-2 pt-2">
              <Btn variant="ghost" onClick={() => setModal(null)}>Cancelar</Btn>
              <Btn onClick={save} disabled={saving || !form.name}>
                {saving ? 'Salvando...' : 'Salvar'}
              </Btn>
            </div>
          </div>
        </Modal>
      )}
    </div>
  )
}

// ─── Sub-aba: SETORES ─────────────────────────────────────────────────────────

const SECTOR_COLORS = ['#6366f1','#06b6d4','#10b981','#f59e0b','#ef4444','#ec4899','#8b5cf6','#f97316']

function SetoresTab() {
  const [sectors, setSectors] = useState<Sector[]>([])
  const [loading, setLoading] = useState(true)
  const [modal, setModal]     = useState<'create' | 'edit' | null>(null)
  const [editing, setEditing] = useState<Sector | null>(null)
  const [form, setForm] = useState({ name: '', description: '', icon: 'Briefcase', color: '#6366f1', sla_minutes: 60 })
  const [saving, setSaving] = useState(false)

  const load = useCallback(async () => {
    setLoading(true)
    try { setSectors(await SectorsService.list()) } finally { setLoading(false) }
  }, [])

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

  function openCreate() {
    setForm({ name: '', description: '', icon: 'Briefcase', color: '#6366f1', sla_minutes: 60 })
    setEditing(null); setModal('create')
  }

  function openEdit(s: Sector) {
    setForm({ name: s.name, description: s.description||'', icon: s.icon, color: s.color, sla_minutes: s.sla_minutes })
    setEditing(s); setModal('edit')
  }

  async function save() {
    setSaving(true)
    try {
      if (editing) await SectorsService.update(editing.id, form)
      else         await SectorsService.create(form)
      setModal(null); load()
    } catch (e: any) {
      alert(e.response?.data?.error || 'Erro ao salvar')
    } finally { setSaving(false) }
  }

  async function remove(s: Sector) {
    if (!confirm(`Excluir setor "${s.name}"? Membros vinculados serão desvinculados.`)) return
    try { await SectorsService.remove(s.id); load() }
    catch (e: any) { alert(e.response?.data?.error || 'Erro ao excluir') }
  }

  if (loading) return <div className="flex items-center justify-center h-40 text-slate-400 text-sm">Carregando...</div>

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <p className="text-sm text-slate-400">{sectors.length} setor(es)</p>
        <Btn onClick={openCreate}><Plus size={14} /> Novo Setor</Btn>
      </div>

      <div className="grid gap-3">
        {sectors.map(s => (
          <div key={s.id} className="flex items-center gap-3 p-3 rounded-xl border bg-slate-800/60 border-slate-700">
            <div className="w-10 h-10 rounded-xl flex items-center justify-center flex-shrink-0" style={{ background: s.color + '33' }}>
              <Briefcase size={18} style={{ color: s.color }} />
            </div>
            <div className="flex-1 min-w-0">
              <div className="flex items-center gap-2">
                <span className="text-sm font-medium text-white">{s.name}</span>
                <span className="text-xs text-slate-500">SLA: {s.sla_minutes} min</span>
              </div>
              {s.description && <p className="text-xs text-slate-500 line-clamp-2">{s.description}</p>}
              <p className="text-xs text-slate-600">{s.member_count} membro(s)</p>
            </div>
            <div className="flex items-center gap-1 flex-shrink-0">
              <button onClick={() => openEdit(s)} className="p-1.5 rounded-lg text-slate-400 hover:text-white hover:bg-slate-700 transition">
                <Edit2 size={14} />
              </button>
              <button onClick={() => remove(s)} className="p-1.5 rounded-lg text-slate-400 hover:text-red-400 hover:bg-red-500/10 transition">
                <Trash2 size={14} />
              </button>
            </div>
          </div>
        ))}
        {sectors.length === 0 && (
          <div className="text-center py-12 text-slate-500 text-sm">
            Nenhum setor cadastrado.<br />
            <button onClick={openCreate} className="mt-2 text-cyan-400 hover:underline">Criar primeiro</button>
          </div>
        )}
      </div>

      {modal && (
        <Modal title={modal === 'create' ? 'Novo Setor' : 'Editar Setor'} onClose={() => setModal(null)}>
          <div className="space-y-4">
            <Field label="Nome *">
              <Input value={form.name} onChange={e => setForm(f => ({ ...f, name: e.target.value }))} placeholder="Ex: Financeiro" />
            </Field>
            <Field label="Descrição">
              <Textarea value={form.description} onChange={e => setForm(f => ({ ...f, description: e.target.value }))} rows={2} placeholder="O que este setor atende..." />
            </Field>
            <Field label="SLA (minutos)">
              <Input type="number" value={form.sla_minutes} onChange={e => setForm(f => ({ ...f, sla_minutes: Number(e.target.value) }))} min={5} />
            </Field>
            <Field label="Cor">
              <div className="flex gap-2 flex-wrap">
                {SECTOR_COLORS.map(c => (
                  <button key={c} onClick={() => setForm(f => ({ ...f, color: c }))}
                    className={`w-7 h-7 rounded-full border-2 transition ${form.color === c ? 'border-white scale-110' : 'border-transparent'}`}
                    style={{ background: c }} />
                ))}
                <input type="color" value={form.color} onChange={e => setForm(f => ({ ...f, color: e.target.value }))}
                  className="w-7 h-7 rounded-full border-0 cursor-pointer bg-transparent" />
              </div>
            </Field>
            <div className="flex justify-end gap-2 pt-2">
              <Btn variant="ghost" onClick={() => setModal(null)}>Cancelar</Btn>
              <Btn onClick={save} disabled={saving || !form.name}>
                {saving ? 'Salvando...' : 'Salvar'}
              </Btn>
            </div>
          </div>
        </Modal>
      )}
    </div>
  )
}

// ─── Sub-aba: MEMBROS ─────────────────────────────────────────────────────────

function MembrosTab() {
  const [members, setMembers]   = useState<TeamMember[]>([])
  const [accounts, setAccounts] = useState<Account[]>([])
  const [sectors, setSectors]   = useState<Sector[]>([])
  const [loading, setLoading]   = useState(true)
  const [filterSector, setFilterSector] = useState<string>('')
  const [modal, setModal] = useState(false)
  const [form, setForm] = useState({ account_id: '', sector_id: '', function: '', is_primary: false })
  const [saving, setSaving] = useState(false)

  const load = useCallback(async () => {
    setLoading(true)
    try {
      const [m, a, s] = await Promise.all([
        TeamMembersService.list(filterSector ? { sector_id: Number(filterSector) } : undefined),
        AccountsService.list(),
        SectorsService.list(),
      ])
      setMembers(m); setAccounts(a); setSectors(s)
    } finally { setLoading(false) }
  }, [filterSector])

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

  async function addMember() {
    if (!form.account_id || !form.sector_id) return
    setSaving(true)
    try {
      await TeamMembersService.add({
        account_id: Number(form.account_id),
        sector_id: Number(form.sector_id),
        function: form.function || undefined,
        is_primary: form.is_primary,
      })
      setModal(false); load()
    } catch (e: any) {
      alert(e.response?.data?.error || 'Erro ao vincular')
    } finally { setSaving(false) }
  }

  async function toggleDuty(m: TeamMember) {
    await TeamMembersService.update(m.id, { on_duty: !m.on_duty })
    load()
  }

  async function toggleNotifEsc(m: TeamMember) {
    await TeamMembersService.update(m.id, { notify_escalation: !m.notify_escalation })
    load()
  }

  async function toggleNotifHapi(m: TeamMember) {
    await TeamMembersService.update(m.id, { notify_human_api: !m.notify_human_api })
    load()
  }

  async function remove(m: TeamMember) {
    if (!confirm(`Desvincular ${m.account_name} do setor ${m.sector_name}?`)) return
    await TeamMembersService.remove(m.id)
    load()
  }

  if (loading) return <div className="flex items-center justify-center h-40 text-slate-400 text-sm">Carregando...</div>

  return (
    <div className="space-y-4">
      <div className="flex items-center gap-3 flex-wrap">
        <select value={filterSector} onChange={e => setFilterSector(e.target.value)}
          className="bg-slate-800 border border-slate-700 rounded-lg px-3 py-1.5 text-sm text-white focus:outline-none">
          <option className="bg-slate-900 text-white" value="">Todos os setores</option>
          {sectors.map(s => <option className="bg-slate-900 text-white" key={s.id} value={s.id}>{s.name}</option>)}
        </select>
        <div className="ml-auto">
          <Btn onClick={() => setModal(true)}><Plus size={14} /> Vincular Membro</Btn>
        </div>
      </div>

      <div className="overflow-x-auto rounded-xl border border-slate-700">
        <table className="w-full text-sm">
          <thead>
            <tr className="border-b border-slate-700 text-slate-400 text-xs">
              <th className="text-left px-4 py-2.5">Colaborador</th>
              <th className="text-left px-4 py-2.5">Setor</th>
              <th className="text-left px-4 py-2.5">Função</th>
              <th className="text-center px-3 py-2.5">Turno</th>
              <th className="text-center px-3 py-2.5">Escal.</th>
              <th className="text-center px-3 py-2.5">H.API</th>
              <th className="px-3 py-2.5"></th>
            </tr>
          </thead>
          <tbody>
            {members.map(m => (
              <tr key={m.id} className="border-b border-slate-800 hover:bg-slate-800/30 transition">
                <td className="px-4 py-2.5">
                  <div className="flex items-center gap-2">
                    <div className="relative">
                      <div className="w-7 h-7 rounded-full bg-slate-700 flex items-center justify-center text-xs font-medium text-slate-300">
                        {m.account_name.charAt(0).toUpperCase()}
                      </div>
                      <span className={`absolute -bottom-0.5 -right-0.5 w-2 h-2 rounded-full border border-slate-900 ${AVAIL_DOT[m.availability]||'bg-slate-500'}`} />
                    </div>
                    <div>
                      <p className="text-white font-medium leading-tight">{m.account_name}</p>
                      <RoleBadge role={m.account_role} />
                    </div>
                  </div>
                </td>
                <td className="px-4 py-2.5">
                  <span className="inline-flex items-center gap-1 text-slate-300">
                    <span className="w-2 h-2 rounded-full" style={{ background: m.sector_color }} />
                    {m.sector_name}
                  </span>
                </td>
                <td className="px-4 py-2.5 text-slate-400">{m.function || '—'}</td>
                <td className="px-3 py-2.5 text-center">
                  <button onClick={() => toggleDuty(m)}
                    className={`text-xs px-2 py-0.5 rounded-full border transition ${m.on_duty ? 'border-green-500/40 text-green-400 bg-green-500/10' : 'border-slate-600 text-slate-500 bg-transparent'}`}>
                    {m.on_duty ? 'On' : 'Off'}
                  </button>
                </td>
                <td className="px-3 py-2.5 text-center">
                  <button onClick={() => toggleNotifEsc(m)} className={`transition ${m.notify_escalation ? 'text-yellow-400' : 'text-slate-600 hover:text-slate-400'}`}>
                    {m.notify_escalation ? <ToggleRight size={16} /> : <ToggleLeft size={16} />}
                  </button>
                </td>
                <td className="px-3 py-2.5 text-center">
                  <button onClick={() => toggleNotifHapi(m)} className={`transition ${m.notify_human_api ? 'text-cyan-400' : 'text-slate-600 hover:text-slate-400'}`}>
                    {m.notify_human_api ? <ToggleRight size={16} /> : <ToggleLeft size={16} />}
                  </button>
                </td>
                <td className="px-3 py-2.5">
                  <button onClick={() => remove(m)} className="p-1 rounded text-slate-500 hover:text-red-400 transition">
                    <Trash2 size={13} />
                  </button>
                </td>
              </tr>
            ))}
            {members.length === 0 && (
              <tr><td colSpan={7} className="text-center py-10 text-slate-500">Nenhum membro vinculado</td></tr>
            )}
          </tbody>
        </table>
      </div>

      {modal && (
        <Modal title="Vincular Membro" onClose={() => setModal(false)}>
          <div className="space-y-4">
            <Field label="Colaborador *">
              <Select value={form.account_id} onChange={e => setForm(f => ({ ...f, account_id: e.target.value }))}>
                <option className="bg-slate-900 text-white" value="">Selecione...</option>
                {accounts.map(a => <option className="bg-slate-900 text-white" key={a.id} value={a.id}>{a.name} — {ROLE_LABELS[a.role]?.label}</option>)}
              </Select>
            </Field>
            <Field label="Setor *">
              <Select value={form.sector_id} onChange={e => setForm(f => ({ ...f, sector_id: e.target.value }))}>
                <option className="bg-slate-900 text-white" value="">Selecione...</option>
                {sectors.map(s => <option className="bg-slate-900 text-white" key={s.id} value={s.id}>{s.name}</option>)}
              </Select>
            </Field>
            <Field label="Função no setor">
              <Input value={form.function} onChange={e => setForm(f => ({ ...f, function: e.target.value }))} placeholder="Ex: Encarregado, Especialista..." />
            </Field>
            <label className="flex items-center gap-2 text-sm text-slate-300 cursor-pointer">
              <input type="checkbox" checked={form.is_primary} onChange={e => setForm(f => ({ ...f, is_primary: e.target.checked }))}
                className="rounded" />
              Setor principal deste colaborador
            </label>
            <div className="flex justify-end gap-2 pt-2">
              <Btn variant="ghost" onClick={() => setModal(false)}>Cancelar</Btn>
              <Btn onClick={addMember} disabled={saving || !form.account_id || !form.sector_id}>
                {saving ? 'Vinculando...' : 'Vincular'}
              </Btn>
            </div>
          </div>
        </Modal>
      )}
    </div>
  )
}

// ─── Sub-aba: CÉREBROS ────────────────────────────────────────────────────────

function CerebrosTab() {
  const [sectors, setSectors]   = useState<Sector[]>([])
  const [selSector, setSelSector] = useState<number | null>(null)
  const [nodes, setNodes]       = useState<BrainNode[]>([])
  const [loading, setLoading]   = useState(false)
  const [newNode, setNewNode]   = useState({ type: 'knowledge', content: '' })
  const [editNode, setEditNode] = useState<BrainNode | null>(null)
  const [saving, setSaving]     = useState(false)

  useEffect(() => {
    SectorsService.list().then(s => {
      setSectors(s)
      if (s.length > 0 && !selSector) setSelSector(s[0].id)
    })
  }, [])

  useEffect(() => {
    if (!selSector) return
    setLoading(true)
    SectorsService.getBrain(selSector).then(n => { setNodes(n); setLoading(false) })
  }, [selSector])

  async function addNode() {
    if (!selSector || !newNode.content.trim()) return
    setSaving(true)
    try {
      const n = await SectorsService.createBrain(selSector, { type: newNode.type, content: newNode.content })
      setNodes(prev => [...prev, n])
      setNewNode({ type: 'knowledge', content: '' })
    } finally { setSaving(false) }
  }

  async function saveEdit() {
    if (!editNode) return
    setSaving(true)
    try {
      const n = await SectorsService.updateBrain(editNode.id, { type: editNode.type, content: editNode.content, active: editNode.active })
      setNodes(prev => prev.map(x => x.id === n.id ? n : x))
      setEditNode(null)
    } finally { setSaving(false) }
  }

  async function toggleNode(node: BrainNode) {
    const n = await SectorsService.updateBrain(node.id, { active: !node.active })
    setNodes(prev => prev.map(x => x.id === n.id ? n : x))
  }

  async function deleteNode(node: BrainNode) {
    if (!confirm('Excluir este node?')) return
    await SectorsService.deleteBrain(node.id)
    setNodes(prev => prev.filter(x => x.id !== node.id))
  }

  const sector = sectors.find(s => s.id === selSector)

  return (
    <div className="space-y-4">
      {/* seletor de setor */}
      <div className="flex gap-2 flex-wrap">
        {sectors.map(s => (
          <button key={s.id} onClick={() => setSelSector(s.id)}
            className={`px-3 py-1.5 rounded-lg text-sm font-medium border transition ${selSector === s.id
              ? 'border-cyan-500 text-cyan-400 bg-cyan-500/10'
              : 'border-slate-700 text-slate-400 hover:text-white hover:border-slate-600'}`}>
            <span className="inline-block w-2 h-2 rounded-full mr-1.5" style={{ background: s.color }} />
            {s.name}
            <span className="ml-1.5 text-xs opacity-60">{s.member_count}</span>
          </button>
        ))}
        {sectors.length === 0 && <p className="text-sm text-slate-500">Crie setores primeiro na aba "Setores"</p>}
      </div>

      {selSector && (
        <>
          {/* adicionar novo node */}
          <div className="bg-slate-800/60 border border-slate-700 rounded-xl p-4 space-y-3">
            <p className="text-xs text-slate-400 font-medium">Adicionar conhecimento ao setor <span className="text-white">{sector?.name}</span></p>
            <div className="flex gap-2">
              <select value={newNode.type} onChange={e => setNewNode(n => ({ ...n, type: e.target.value }))}
                className="bg-slate-900 border border-slate-600 rounded-lg px-2 py-1.5 text-xs text-white focus:outline-none focus:border-cyan-500 flex-shrink-0">
                {Object.entries(BRAIN_TYPE_LABELS).map(([v, l]) => <option className="bg-slate-900 text-white" key={v} value={v}>{l}</option>)}
              </select>
              <textarea value={newNode.content} onChange={e => setNewNode(n => ({ ...n, content: e.target.value }))}
                rows={2} placeholder="Descreva o conhecimento, regra ou instrução..."
                className="flex-1 bg-slate-900 border border-slate-600 rounded-lg px-3 py-2 text-sm text-white placeholder-slate-500 focus:outline-none focus:border-cyan-500 resize-none" />
              <button onClick={addNode} disabled={saving || !newNode.content.trim()}
                className="px-3 py-1.5 bg-cyan-600 hover:bg-cyan-500 disabled:opacity-50 text-white rounded-lg text-sm font-medium transition flex-shrink-0">
                <Plus size={16} />
              </button>
            </div>
          </div>

          {/* lista de nodes */}
          {loading
            ? <div className="text-center py-8 text-slate-400 text-sm">Carregando...</div>
            : (
              <div className="space-y-2">
                {nodes.map(node => (
                  <div key={node.id} className={`rounded-xl border p-3 transition ${node.active ? 'bg-slate-800/60 border-slate-700' : 'bg-slate-900/40 border-slate-800 opacity-50'}`}>
                    {editNode?.id === node.id ? (
                      <div className="space-y-2">
                        <select value={editNode.type} onChange={e => setEditNode(n => n ? { ...n, type: e.target.value } : n)}
                          className="bg-slate-900 border border-slate-600 rounded px-2 py-1 text-xs text-white focus:outline-none">
                          {Object.entries(BRAIN_TYPE_LABELS).map(([v, l]) => <option className="bg-slate-900 text-white" key={v} value={v}>{l}</option>)}
                        </select>
                        <textarea value={editNode.content} onChange={e => setEditNode(n => n ? { ...n, content: e.target.value } : n)}
                          rows={3}
                          className="w-full bg-slate-900 border border-slate-600 rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-cyan-500 resize-none" />
                        <div className="flex gap-2">
                          <Btn onClick={saveEdit} disabled={saving}><Check size={13} /> Salvar</Btn>
                          <Btn variant="ghost" onClick={() => setEditNode(null)}><X size={13} /> Cancelar</Btn>
                        </div>
                      </div>
                    ) : (
                      <div className="flex gap-3">
                        <span className={`text-[10px] font-medium px-2 py-0.5 rounded-full self-start flex-shrink-0 ${BRAIN_TYPE_COLORS[node.type]}`}>
                          {BRAIN_TYPE_LABELS[node.type] || node.type}
                        </span>
                        <p className="text-sm text-slate-300 flex-1 leading-relaxed whitespace-pre-wrap">{node.content}</p>
                        <div className="flex items-start gap-1 flex-shrink-0">
                          <button onClick={() => setEditNode(node)} className="p-1 text-slate-500 hover:text-white transition"><Edit2 size={13} /></button>
                          <button onClick={() => toggleNode(node)} className="p-1 text-slate-500 hover:text-yellow-400 transition" title={node.active ? 'Desativar' : 'Ativar'}>
                            {node.active ? <ToggleRight size={13} className="text-green-400" /> : <ToggleLeft size={13} />}
                          </button>
                          <button onClick={() => deleteNode(node)} className="p-1 text-slate-500 hover:text-red-400 transition"><Trash2 size={13} /></button>
                        </div>
                      </div>
                    )}
                  </div>
                ))}
                {nodes.length === 0 && (
                  <div className="text-center py-8 text-slate-500 text-sm">
                    Nenhum conhecimento cadastrado para este setor.<br />
                    Adicione acima.
                  </div>
                )}
              </div>
            )
          }
        </>
      )}
    </div>
  )
}

// ─── Sub-aba: PERFORMANCE ─────────────────────────────────────────────────────

function PerformanceTab() {
  return (
    <div className="flex flex-col items-center justify-center py-16 text-center gap-3">
      <BarChart2 size={40} className="text-slate-600" />
      <p className="text-slate-400 text-sm font-medium">Performance</p>
      <p className="text-slate-600 text-xs max-w-xs">
        Métricas de tempo de resposta, taxa de resolução e satisfação serão exibidas
        aqui após a Human API entrar em operação.
      </p>
    </div>
  )
}

// ─── EquipeTab principal ──────────────────────────────────────────────────────

// ─── Meu Perfil (vínculo admin ↔ account) ────────────────────────────────────
// Este componente resolve o problema de identidade do admin na Inbox Interna.
// O admin (tabela `admins`) e o colaborador (tabela `accounts`) são entidades
// separadas. Ao vincular, o admin não precisa mais fazer login duplo para
// receber mensagens internas — o sistema usa o account vinculado como identidade.
function MeuPerfilTab() {
  const [accounts,       setAccounts]       = useState<any[]>([])
  const [linkedAccount,  setLinkedAccount]  = useState<any | null>(null)
  const [selectedId,     setSelectedId]     = useState<string>('')
  const [saving,         setSaving]         = useState(false)
  const [saved,          setSaved]          = useState(false)

  useEffect(() => {
    // Carrega accounts disponíveis e o vínculo atual do admin
    Promise.all([
      AccountsService.list(),
      AdminMeService.get(),
    ]).then(([accs, me]) => {
      setAccounts(Array.isArray(accs) ? accs : [])
      if (me.linkedAccount) {
        setLinkedAccount(me.linkedAccount)
        setSelectedId(String(me.linkedAccount.id))
      }
    }).catch(() => {})
  }, [])

  async function save() {
    setSaving(true)
    try {
      await AdminMeService.linkAccount(selectedId ? Number(selectedId) : null)
      const me = await AdminMeService.get()
      setLinkedAccount(me.linkedAccount ?? null)
      setSaved(true)
      setTimeout(() => setSaved(false), 2500)
    } catch {} finally { setSaving(false) }
  }

  return (
    <div className="max-w-md space-y-5">
      <div className="bg-slate-800 rounded-xl p-4 border border-slate-700">
        <div className="flex items-center gap-2 mb-1">
          <Link2 size={14} className="text-cyan-400" />
          <h3 className="text-sm font-semibold text-white">Identidade na Inbox Interna</h3>
        </div>
        <p className="text-xs text-slate-400 mb-4">
          Vincule seu perfil de admin a uma conta de colaborador para receber
          e enviar mensagens na Inbox Interna sem fazer login duplo.
        </p>

        {linkedAccount && (
          <div className="flex items-center gap-2 mb-3 px-3 py-2 bg-cyan-900/30 border border-cyan-500/30 rounded-lg">
            <Check size={13} className="text-cyan-400 flex-shrink-0" />
            <div>
              <p className="text-xs font-medium text-cyan-300">{linkedAccount.name}</p>
              <p className="text-[11px] text-slate-400">{linkedAccount.email} · {linkedAccount.role}</p>
            </div>
          </div>
        )}

        <label className="block text-xs text-slate-400 mb-1">Selecionar conta de colaborador</label>
        <select
          value={selectedId}
          onChange={e => setSelectedId(e.target.value)}
          className="w-full bg-slate-900 border border-slate-600 rounded-lg px-3 py-2 text-sm text-white mb-3 outline-none focus:border-cyan-500">
          <option value="" className="bg-slate-900 text-white">— Nenhum (desvinculado) —</option>
          {accounts.map(a => (
            <option key={a.id} value={a.id} className="bg-slate-900 text-white">{a.name} ({a.email})</option>
          ))}
        </select>

        <button
          onClick={save}
          disabled={saving}
          className="flex items-center gap-2 px-4 py-2 bg-cyan-600 hover:bg-cyan-700 disabled:opacity-50 text-white rounded-lg text-xs font-medium transition">
          {saved ? <Check size={13} /> : <Link2 size={13} />}
          {saved ? 'Vinculado!' : saving ? 'Salvando...' : 'Salvar vínculo'}
        </button>
      </div>

      <p className="text-[11px] text-slate-500">
        Após salvar, atualize a página. A Inbox Interna passará a usar sua identidade de colaborador automaticamente.
      </p>
    </div>
  )
}

const SUB_TABS: Array<{ id: EquipeSub; label: string; Icon: any }> = [
  { id: 'contas',      label: 'Contas',       Icon: Users },
  { id: 'setores',     label: 'Setores',      Icon: Network },
  { id: 'membros',     label: 'Membros',      Icon: UserCheck },
  { id: 'cerebros',    label: 'Cérebros',     Icon: Brain },
  { id: 'performance', label: 'Performance',  Icon: BarChart2 },
  { id: 'meu-perfil',  label: 'Meu Perfil',  Icon: Link2 },
]

export default function EquipeTab() {
  const [sub, setSub] = useState<EquipeSub>('contas')

  return (
    <div className="flex flex-col h-full">
      {/* header */}
      <div className="flex-shrink-0 px-4 pt-4 pb-3 border-b border-slate-800">
        <div className="flex items-center gap-2 mb-3">
          <Users size={16} className="text-cyan-400" />
          <h2 className="text-sm font-semibold text-white">Equipe</h2>
        </div>
        {/* sub-tabs */}
        <div className="flex gap-1 overflow-x-auto pb-0.5">
          {SUB_TABS.map(t => (
            <button key={t.id} onClick={() => setSub(t.id)}
              className={`flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-xs font-medium whitespace-nowrap transition flex-shrink-0
                ${sub === t.id
                  ? 'bg-cyan-600/20 text-cyan-400 border border-cyan-500/30'
                  : 'text-slate-400 hover:text-white hover:bg-slate-800'}`}>
              <t.Icon size={12} />
              {t.label}
            </button>
          ))}
        </div>
      </div>

      {/* conteúdo
          min-h-0 é obrigatório em flex-col: sem ele, o flex child não respeita
          o overflow-y-auto e expande além do pai ("div explodiu").
          Referência: https://css-tricks.com/flexbox-truncated-text/ */}
      <div className="flex-1 min-h-0 overflow-y-auto p-4">
        {sub === 'contas'      && <ContasTab />}
        {sub === 'setores'     && <SetoresTab />}
        {sub === 'membros'     && <MembrosTab />}
        {sub === 'cerebros'    && <CerebrosTab />}
        {sub === 'performance' && <PerformanceTab />}
        {sub === 'meu-perfil'  && <MeuPerfilTab />}
      </div>
    </div>
  )
}
