/* global React, Icon, Avatar, Modal, ProgressBar, timeAgo, formatDate */

// ============================================================================
// Admin panel — gerenciar membros, convites, aulas, ver atividade
// ============================================================================

const AdminPanel = ({ user, nav }) => {
  const [tab, setTab] = React.useState('membros');

  const members = DB.users().filter(u => u.role === 'membro');
  const admins = DB.users().filter(u => u.role === 'admin');
  const allLessons = DB.phases().flatMap(p => DB.lessonsByPhase(p.id));

  return (
    <div className="app-main">
      <div className="page-head">
        <div>
          <div className="page-eyebrow">Painel administrativo · Edson</div>
          <h1 className="page-title">Gestão do Núcleo</h1>
          <p className="page-sub">Visão completa do programa: membros, convites, conteúdo e atividade recente.</p>
        </div>
        <div className="hstack">
          <button className="btn-ghost" onClick={()=>{ if(confirm('Resetar todos os dados de demonstração?')) { DB.reset(); window.location.reload(); } }}>
            <Icon name="trash" size={14}/>Resetar dados
          </button>
        </div>
      </div>

      <div className="stat-grid">
        <div className="card stat">
          <div className="label">Mentorados ativos</div>
          <div className="value">{members.filter(m=>m.status==='ativo').length}</div>
          <div className="sub up">+2 nas últimas 4 semanas</div>
        </div>
        <div className="card stat">
          <div className="label">Convites em aberto</div>
          <div className="value">{DB.invites().filter(i=>!i.used).length}</div>
          <div className="sub">aguardando criação de conta</div>
        </div>
        <div className="card stat">
          <div className="label">Aulas publicadas</div>
          <div className="value">{allLessons.length}</div>
          <div className="sub">{allLessons.filter(l=>l.type==='live').length} lives · {allLessons.filter(l=>l.type==='video').length} gravadas</div>
        </div>
        <div className="card stat">
          <div className="label">Engajamento médio</div>
          <div className="value">
            {(() => {
              const avg = members.reduce((s,m) => s + DB.overallProgress(m), 0) / Math.max(1, members.length);
              return Math.round(avg);
            })()}<span className="unit">%</span>
          </div>
          <div className="sub">de progresso geral</div>
        </div>
      </div>

      <div className="admin-tabs">
        {[
          ['membros', 'Membros'],
          ['convites', 'Convites'],
          ['conteudo', 'Conteúdo'],
          ['atividade', 'Atividade'],
          ['lgpd', 'Auditoria & LGPD']
        ].map(([k, label]) => (
          <button key={k} className={tab===k?'active':''} onClick={()=>setTab(k)}>{label}</button>
        ))}
      </div>

      {tab==='membros' && <MembersTab members={members} admins={admins} nav={nav}/>}
      {tab==='convites' && <InvitesTab/>}
      {tab==='conteudo' && <ContentTab/>}
      {tab==='atividade' && <ActivityTab/>}
      {tab==='lgpd' && <AdminLGPDTab user={user}/>}
    </div>
  );
};

// ----- Members tab -----
const MembersTab = ({ members, admins, nav }) => {
  const [q, setQ] = React.useState('');
  const [filter, setFilter] = React.useState('todos');

  let list = [...admins, ...members];
  if (filter === 'ativo') list = list.filter(u => u.status === 'ativo');
  if (filter === 'inativo') list = list.filter(u => u.status === 'inativo');
  if (q.trim()) {
    const term = q.toLowerCase();
    list = list.filter(u => u.name.toLowerCase().includes(term) || u.email.toLowerCase().includes(term));
  }

  return (
    <div>
      <div className="hstack" style={{ marginBottom: 18, gap: 12 }}>
        <div style={{ position: 'relative', flex: 1, maxWidth: 400 }}>
          <Icon name="search" size={16} style={{ position: 'absolute', left: 14, top: '50%', transform:'translateY(-50%)', color:'var(--text-muted)' }}/>
          <input
            placeholder="Buscar por nome ou e-mail…"
            value={q}
            onChange={e=>setQ(e.target.value)}
            style={{ width: '100%', background: 'rgba(16,36,72,0.5)', border: '1px solid var(--line-dark)', borderRadius: 6, padding: '11px 14px 11px 40px', color:'var(--text-light)', fontSize: 14 }}
          />
        </div>
        <select value={filter} onChange={e=>setFilter(e.target.value)} style={{ background: 'rgba(16,36,72,0.5)', border:'1px solid var(--line-dark)', borderRadius: 6, padding: '11px 14px', color:'var(--text-light)', fontSize: 14 }}>
          <option value="todos">Todos</option>
          <option value="ativo">Ativos</option>
          <option value="inativo">Inativos</option>
        </select>
        <div className="spacer"/>
        <span className="muted text-small">{list.length} resultado(s)</span>
      </div>

      <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
        <table className="table">
          <thead>
            <tr>
              <th>Membro</th>
              <th>Status</th>
              <th>Progresso</th>
              <th>Último acesso</th>
              <th>Cadastro</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            {list.map(u => (
              <MemberRow key={u.id} member={u}/>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
};

const MemberRow = ({ member }) => {
  const progress = DB.overallProgress(member);
  const [open, setOpen] = React.useState(false);
  const isAdmin = member.role === 'admin';

  return (
    <>
      <tr>
        <td>
          <div className="user-cell">
            <Avatar user={member}/>
            <div>
              <div className="name">{member.name}</div>
              <div className="email">{member.email}</div>
            </div>
          </div>
        </td>
        <td>
          {isAdmin ? <span className="status-pill admin">Admin</span> :
            <span className={`status-pill ${member.status}`}>{member.status}</span>}
        </td>
        <td style={{ width: 180 }}>
          {isAdmin ? <span className="muted">—</span> : (
            <div>
              <div className="hstack" style={{ gap: 8 }}>
                <ProgressBar value={progress}/>
                <span style={{ fontSize: 12, fontWeight: 700, minWidth: 36 }}>{progress}%</span>
              </div>
            </div>
          )}
        </td>
        <td>{timeAgo(member.lastLogin)} atrás</td>
        <td>{formatDate(member.createdAt)}</td>
        <td style={{ textAlign: 'right' }}>
          <button className="btn-icon" onClick={()=>setOpen(true)}><Icon name="eye" size={14}/></button>
        </td>
      </tr>
      {open && <MemberDetailModal member={member} onClose={()=>setOpen(false)}/>}
    </>
  );
};

const MemberDetailModal = ({ member, onClose }) => {
  const phases = DB.phases();
  const isAdmin = member.role === 'admin';
  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" style={{ maxWidth: 680 }} onClick={e=>e.stopPropagation()}>
        <div className="hstack" style={{ marginBottom: 22, gap: 16 }}>
          <Avatar user={member} size="lg"/>
          <div>
            <h3 style={{ marginBottom: 4 }}>{member.name}</h3>
            <div className="muted text-small">{member.email} · {member.phone || 'sem telefone'}</div>
            <div style={{ marginTop: 8 }}>
              {isAdmin ? <span className="status-pill admin">Administrador</span> :
                <span className={`status-pill ${member.status}`}>{member.status}</span>}
            </div>
          </div>
        </div>

        {member.bio && (
          <div style={{ background: 'rgba(16,36,72,0.4)', padding: 14, borderRadius: 6, fontSize: 13.5, color: 'var(--text-light)', lineHeight: 1.55, marginBottom: 18 }}>
            {member.bio}
          </div>
        )}

        {member.declaracaoIntencao && (
          <div style={{ borderLeft: '3px solid var(--gold)', padding: '12px 16px', background: 'rgba(212,165,90,0.06)', fontStyle: 'italic', fontFamily:'Archivo, sans-serif', fontSize: 14, color: 'var(--text-light)', marginBottom: 22 }}>
            <div style={{ fontStyle: 'normal', fontSize: 10, letterSpacing: '0.28em', textTransform: 'uppercase', color: 'var(--gold-bright)', fontWeight: 700, marginBottom: 8 }}>Declaração de intenção</div>
            "{member.declaracaoIntencao}"
          </div>
        )}

        {!isAdmin && (
          <div>
            <div style={{ fontSize: 11, letterSpacing: '0.16em', textTransform: 'uppercase', color: 'var(--text-muted)', fontWeight: 700, marginBottom: 12 }}>Progresso por fase</div>
            <div className="vstack" style={{ gap: 10 }}>
              {phases.map(p => {
                const pr = DB.progressForPhase(member, p.id);
                return (
                  <div key={p.id} className="hstack" style={{ gap: 14 }}>
                    <div style={{ width: 220, fontSize: 13 }}>
                      <div style={{ fontWeight: 700, color: 'var(--text-light)' }}>{p.pillar}</div>
                      <div className="muted text-small">{p.title.split(':')[0]}</div>
                    </div>
                    <div style={{ flex: 1 }}>
                      <ProgressBar value={pr.pct}/>
                    </div>
                    <div style={{ fontSize: 12.5, fontWeight: 700, minWidth: 70, textAlign: 'right' }}>
                      {pr.done}/{pr.total} <span className="muted">({pr.pct}%)</span>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        )}

        <div className="modal-actions">
          {!isAdmin && (
            <>
              <button className="btn-icon btn-danger" onClick={() => {
                if (confirm(`Remover ${member.name} do programa?`)) { DB.deleteMember(member.id); onClose(); }
              }} style={{ width:'auto', padding:'10px 14px', display:'inline-flex', gap: 8 }}>
                <Icon name="trash" size={14}/>Remover
              </button>
              <button className="btn-ghost" onClick={() => { DB.setMemberStatus(member.id, member.status === 'ativo' ? 'inativo' : 'ativo'); }}>
                {member.status === 'ativo' ? 'Desativar' : 'Reativar'}
              </button>
            </>
          )}
          <button className="btn-primary" style={{ width:'auto', padding: '11px 22px' }} onClick={onClose}>Fechar</button>
        </div>
      </div>
    </div>
  );
};

// ----- Invites tab -----
const InvitesTab = () => {
  const [showInvite, setShowInvite] = React.useState(false);
  const [form, setForm] = React.useState({ name: '', email: '' });
  const [lastToken, setLastToken] = React.useState(null);
  const [copied, setCopied] = React.useState(false);
  const invites = DB.invites();

  const submit = () => {
    if (!form.name || !form.email) return;
    const token = DB.inviteMember(form);
    setLastToken({ token, ...form });
    setForm({ name: '', email: '' });
    setShowInvite(false);
  };

  const copy = (token) => {
    navigator.clipboard?.writeText(token);
    setCopied(token);
    setTimeout(()=>setCopied(false), 2000);
  };

  return (
    <div>
      <div className="hstack" style={{ marginBottom: 18 }}>
        <p className="muted text-small" style={{ flex: 1 }}>
          Convites são pessoais e usados uma única vez. Envie o token para o aprovado junto do link da plataforma.
        </p>
        <button className="btn-gold" onClick={()=>setShowInvite(true)}>
          <Icon name="plus" size={14}/>Novo convite
        </button>
      </div>

      {lastToken && (
        <div className="alert alert-success" style={{ marginBottom: 18 }}>
          <Icon name="check" size={16}/>
          <div style={{ flex: 1 }}>
            <div><b>Convite criado para {lastToken.name}</b> ({lastToken.email})</div>
            <div style={{ marginTop: 8, display:'flex', alignItems:'center', gap: 10 }}>
              <span className="invite-token">{lastToken.token}</span>
              <button className="btn-ghost" style={{ padding:'6px 10px', fontSize: 11 }} onClick={()=>copy(lastToken.token)}>
                {copied === lastToken.token ? 'Copiado!' : 'Copiar token'}
              </button>
            </div>
          </div>
        </div>
      )}

      <div className="card" style={{ padding: 0, overflow:'hidden' }}>
        <table className="table">
          <thead>
            <tr>
              <th>Aprovado</th>
              <th>E-mail</th>
              <th>Token</th>
              <th>Criado</th>
              <th>Status</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            {invites.map(inv => (
              <tr key={inv.token}>
                <td><div className="user-cell"><div><div className="name">{inv.name || '—'}</div></div></div></td>
                <td className="muted">{inv.email}</td>
                <td><span className="invite-token">{inv.token}</span></td>
                <td>{formatDate(inv.createdAt)}</td>
                <td>
                  {inv.used ? <span className="status-pill ativo">Utilizado</span> : <span className="status-pill admin">Em aberto</span>}
                </td>
                <td style={{ textAlign:'right' }}>
                  <button className="btn-icon" onClick={()=>copy(inv.token)} title="Copiar token">
                    <Icon name="copy" size={14}/>
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {showInvite && (
        <Modal
          title="Novo convite"
          sub="Gere um token único para um candidato aprovado."
          onClose={()=>setShowInvite(false)}
          actions={
            <>
              <button className="btn-ghost" onClick={()=>setShowInvite(false)}>Cancelar</button>
              <button className="btn-primary" style={{ width:'auto', padding:'11px 22px' }} onClick={submit} disabled={!form.name || !form.email}>Gerar convite</button>
            </>
          }
        >
          <div className="field"><label>Nome do aprovado</label><input value={form.name} onChange={e=>setForm({...form, name:e.target.value})}/></div>
          <div className="field"><label>E-mail</label><input type="email" value={form.email} onChange={e=>setForm({...form, email:e.target.value})}/></div>
        </Modal>
      )}
    </div>
  );
};

// ----- Content tab -----
const ContentTab = () => {
  const phases = DB.phases();
  const [activePhase, setActivePhase] = React.useState(phases[0].id);
  const [addModal, setAddModal] = React.useState(false);
  const [form, setForm] = React.useState({ title:'', type:'video', duration:'', description:'' });

  const lessons = DB.lessonsByPhase(activePhase);

  const add = () => {
    if (!form.title) return;
    DB.addLesson({ phaseId: activePhase, ...form, order: lessons.length + 1 });
    setForm({ title:'', type:'video', duration:'', description:'' });
    setAddModal(false);
  };

  return (
    <div>
      <div className="hstack" style={{ marginBottom: 22, gap: 8, flexWrap:'wrap' }}>
        {phases.map(p => (
          <button key={p.id} className={activePhase === p.id ? '' : 'btn-ghost'}
            onClick={()=>setActivePhase(p.id)}
            style={activePhase === p.id ? { background:'var(--blue)', color:'#fff', padding:'10px 16px', borderRadius: 6, fontSize: 12.5, fontWeight: 700, letterSpacing:'0.06em', textTransform:'uppercase' } : {}}>
            {p.pillar}
          </button>
        ))}
        <div className="spacer"/>
        <button className="btn-gold" onClick={()=>setAddModal(true)}><Icon name="plus" size={14}/>Nova aula</button>
      </div>

      <div className="card" style={{ padding: 0, overflow:'hidden' }}>
        <table className="table">
          <thead>
            <tr>
              <th style={{ width: 50 }}>#</th>
              <th>Título</th>
              <th>Tipo</th>
              <th>Duração</th>
              <th>Materiais</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            {lessons.map(l => (
              <tr key={l.id}>
                <td className="muted fw-700">{String(l.order).padStart(2,'0')}</td>
                <td>
                  <div className="fw-700" style={{ color: 'var(--text-light)' }}>{l.title}</div>
                  <div className="muted text-small" style={{ marginTop: 4, maxWidth: 480 }}>{l.description?.slice(0,90)}…</div>
                </td>
                <td><span className={`status-pill ${l.type === 'live' ? 'inativo' : l.type === 'workbook' ? 'admin' : 'ativo'}`}>{l.type}</span></td>
                <td>{l.duration}</td>
                <td className="muted">{l.materials.length || '—'}</td>
                <td style={{ textAlign:'right' }}>
                  <button className="btn-icon" style={{ marginRight: 6 }}><Icon name="edit" size={14}/></button>
                  <button className="btn-icon btn-danger" onClick={()=>{ if(confirm('Apagar aula?')) DB.deleteLesson(l.id); }}><Icon name="trash" size={14}/></button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {addModal && (
        <Modal title="Nova aula" sub="Adiciona aula à fase selecionada." onClose={()=>setAddModal(false)}
          actions={<>
            <button className="btn-ghost" onClick={()=>setAddModal(false)}>Cancelar</button>
            <button className="btn-primary" style={{ width:'auto', padding:'11px 22px' }} onClick={add} disabled={!form.title}>Criar aula</button>
          </>}>
          <div className="field"><label>Título</label><input value={form.title} onChange={e=>setForm({...form, title:e.target.value})}/></div>
          <div className="field-row">
            <div className="field">
              <label>Tipo</label>
              <select value={form.type} onChange={e=>setForm({...form, type:e.target.value})}>
                <option value="video">Aula gravada</option>
                <option value="live">Live</option>
                <option value="workbook">Exercício</option>
              </select>
            </div>
            <div className="field"><label>Duração</label><input value={form.duration} onChange={e=>setForm({...form, duration:e.target.value})} placeholder="ex: 28:14"/></div>
          </div>
          <div className="field"><label>Descrição</label><textarea rows={4} value={form.description} onChange={e=>setForm({...form, description:e.target.value})}/></div>
        </Modal>
      )}
    </div>
  );
};

// ----- Activity tab -----
const ActivityTab = () => {
  const acts = DB.activity(50);
  const kinds = {
    login: { label: 'Login', color: 'var(--blue-soft)' },
    signup: { label: 'Cadastro novo', color: 'var(--gold-bright)' },
    lesson_complete: { label: 'Concluiu aula', color: 'var(--success)' },
    post: { label: 'Novo post', color: 'var(--blue-bright)' }
  };

  return (
    <div className="card" style={{ padding: 0, overflow:'hidden' }}>
      <table className="table">
        <thead>
          <tr><th>Quando</th><th>Membro</th><th>Evento</th><th>Detalhe</th></tr>
        </thead>
        <tbody>
          {acts.map(a => {
            const u = DB.userById(a.userId);
            const k = kinds[a.kind] || { label: a.kind, color: 'var(--text-muted)' };
            let detail = '';
            if (a.kind === 'lesson_complete') {
              const l = DB.lesson(a.payload.lessonId);
              detail = l?.title || '—';
            } else if (a.kind === 'post') {
              detail = 'em Comunidade';
            }
            return (
              <tr key={a.id}>
                <td className="muted text-small">{timeAgo(a.createdAt)} atrás</td>
                <td><div className="user-cell"><Avatar user={u}/><div><div className="name">{u?.name}</div></div></div></td>
                <td><span style={{ color: k.color, fontWeight: 700, fontSize: 12.5, letterSpacing: '0.04em' }}>{k.label}</span></td>
                <td className="muted">{detail}</td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
};

Object.assign(window, { AdminPanel });
