/* global React, Icon, Button, Badge, Drawer,
          AGENTE_TIPOS, MODELOS_IA, TEMPLATE_CATEGORIAS, MSG_CANAIS_INFO */

// ─── Mensagens Module — Forms & Drawers ─────────────────────────────────────
// Configuration drawers for Channels, AI Agents, and Templates.
// ─────────────────────────────────────────────────────────────────────────────

// ─── Helper: section divider inside drawer ───────────────────────────────────

function MsgDrawerSection({ title, children }) {
  return (
    <div style={{ marginBottom: 16 }}>
      <div style={{
        fontSize: 10.5, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.08em',
        color: 'var(--tm-fg-4)', marginBottom: 8, paddingBottom: 4,
        borderBottom: '1px solid var(--tm-line-1)',
      }}>{title}</div>
      <div className="form-grid">{children}</div>
    </div>
  );
}

// ─── Blanks ─────────────────────────────────────────────────────────────────

const BLANK_CANAL = {
  tipo: 'whatsapp', nome: 'WhatsApp Business', provedor: 'z-api',
  instance_id: '', token: '', numero: '', status: 'desconectado', config: {},
};

const BLANK_AGENTE = {
  nome: '', tipo: 'sac', modelo: 'claude-sonnet-4-20250514', ativo: true,
  prompt_sistema: '', prompt_abertura: '',
  horario_inicio: '08:00', horario_fim: '18:00', dias_semana: [1,2,3,4,5],
  max_mensagens_sem_humano: 10, temperatura: 0.7,
  canal_id: '', config: {},
};

const BLANK_TEMPLATE = {
  nome: '', categoria: 'geral', conteudo: '', variaveis: [], atalho: '', ativo: true,
};

// ─── Canal Config Form ──────────────────────────────────────────────────────

function CanalConfigForm({ edit, set, onSave, onCancel, onDelete, onTestarConexao }) {
  if (!edit) return null;
  const d = edit.draft;
  const isNew = edit.mode === 'new';

  return (
    <Drawer open={true} title={isNew ? 'Conectar canal' : 'Configurar canal'} width={520}
      onClose={onCancel}
      footer={<>
        {!isNew && onDelete && <Button variant="danger-ghost" size="sm" icon="trash-2" onClick={onDelete}>Desconectar</Button>}
        <span style={{ flex: 1 }} />
        <Button variant="secondary" size="sm" onClick={onCancel}>Cancelar</Button>
        <Button variant="primary" size="sm" icon="check" onClick={onSave}>Salvar</Button>
      </>}>

      <MsgDrawerSection title="Canal">
        <div className="field"><label>Tipo</label>
          <select className="input" value={d.tipo || 'whatsapp'} onChange={e => set('tipo', e.target.value)}>
            <option value="whatsapp">WhatsApp</option>
            <option value="instagram">Instagram</option>
            <option value="email">E-mail</option>
          </select></div>
        <div className="field"><label>Nome do canal</label>
          <input className="input" placeholder="WhatsApp Business" value={d.nome || ''} onChange={e => set('nome', e.target.value)} /></div>
      </MsgDrawerSection>

      <MsgDrawerSection title="Credenciais Z-API">
        <div className="field span-2">
          <label>Instance ID</label>
          <input className="input" placeholder="Copie da sua dashboard Z-API" value={d.instance_id || ''}
            onChange={e => set('instance_id', e.target.value)} style={{ fontFamily: 'monospace', fontSize: 12.5 }} />
        </div>
        <div className="field span-2">
          <label>Token</label>
          <input className="input" type="password" placeholder="Token de autenticação" value={d.token || ''}
            onChange={e => set('token', e.target.value)} style={{ fontFamily: 'monospace', fontSize: 12.5 }} />
        </div>
        <div className="field"><label>Número</label>
          <input className="input" placeholder="5511999999999" value={d.numero || ''} onChange={e => set('numero', e.target.value)} /></div>
        <div className="field"><label>Status</label>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, height: 34 }}>
            <span style={{
              width: 8, height: 8, borderRadius: '50%',
              background: d.status === 'conectado' ? '#5BB17A' : d.status === 'erro' ? '#D9655E' : '#888',
            }} />
            <span style={{ fontSize: 13 }}>{d.status === 'conectado' ? 'Conectado' : d.status === 'erro' ? 'Erro' : 'Desconectado'}</span>
          </div>
        </div>
      </MsgDrawerSection>

      {onTestarConexao && (
        <div style={{ marginBottom: 16 }}>
          <Button variant="secondary" size="sm" icon="wifi" onClick={onTestarConexao}>
            Testar conexão
          </Button>
        </div>
      )}

      <MsgDrawerSection title="Webhook">
        <div className="field span-2"><label>URL do Webhook (configure na Z-API)</label>
          <input className="input" readOnly value={d.webhook_url || `https://ilgxpxfdrhshitkozlqs.supabase.co/functions/v1/whatsapp-webhook`}
            style={{ fontFamily: 'monospace', fontSize: 11, background: 'var(--tm-bg-2)' }}
            onClick={e => { e.target.select(); navigator.clipboard?.writeText(e.target.value); }} />
          <div style={{ fontSize: 11, color: 'var(--tm-fg-4)', marginTop: 4 }}>
            Clique para copiar. Cole este URL no campo "Webhook URL" da sua instance Z-API.
          </div>
        </div>
      </MsgDrawerSection>

      <MsgDrawerSection title="Configurações">
        <div className="field span-2">
          <label style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <input type="checkbox"
              checked={d.config?.auto_resposta !== false}
              onChange={e => set('config', { ...d.config, auto_resposta: e.target.checked })}
              style={{ accentColor: 'var(--tm-brand-champagne)' }} />
            Ativar resposta automática via IA
          </label>
        </div>
      </MsgDrawerSection>
    </Drawer>
  );
}

// ─── Agente IA Config Form ──────────────────────────────────────────────────

function AgenteConfigForm({ edit, set, onSave, onCancel, onDelete, canais }) {
  if (!edit) return null;
  const d = edit.draft;
  const isNew = edit.mode === 'new';

  const DIAS = [
    { v: 0, l: 'Dom' }, { v: 1, l: 'Seg' }, { v: 2, l: 'Ter' },
    { v: 3, l: 'Qua' }, { v: 4, l: 'Qui' }, { v: 5, l: 'Sex' }, { v: 6, l: 'Sáb' },
  ];

  const toggleDia = (dia) => {
    const curr = d.dias_semana || [1,2,3,4,5];
    const next = curr.includes(dia) ? curr.filter(x => x !== dia) : [...curr, dia].sort();
    set('dias_semana', next);
  };

  return (
    <Drawer open={true} title={isNew ? 'Novo agente IA' : 'Configurar agente'} width={560}
      onClose={onCancel}
      footer={<>
        {!isNew && onDelete && <Button variant="danger-ghost" size="sm" icon="trash-2" onClick={onDelete}>Excluir</Button>}
        <span style={{ flex: 1 }} />
        <Button variant="secondary" size="sm" onClick={onCancel}>Cancelar</Button>
        <Button variant="primary" size="sm" icon="check" onClick={onSave}>Salvar</Button>
      </>}>

      <MsgDrawerSection title="Identificação">
        <div className="field"><label>Nome do agente</label>
          <input className="input" placeholder="SAC TopMix, Vendas IA…" value={d.nome || ''} onChange={e => set('nome', e.target.value)} /></div>
        <div className="field"><label>Tipo</label>
          <select className="input" value={d.tipo || 'sac'} onChange={e => set('tipo', e.target.value)}>
            {AGENTE_TIPOS.map(a => <option key={a.value} value={a.value}>{a.label}</option>)}
          </select></div>
        <div className="field"><label>Modelo IA</label>
          <select className="input" value={d.modelo || 'claude-sonnet-4-20250514'} onChange={e => set('modelo', e.target.value)}>
            {MODELOS_IA.map(m => <option key={m.value} value={m.value}>{m.label}</option>)}
          </select></div>
        <div className="field"><label>Canal vinculado</label>
          <select className="input" value={d.canal_id || ''} onChange={e => set('canal_id', e.target.value)}>
            <option value="">Nenhum (global)</option>
            {(canais || []).map(c => <option key={c.id} value={c.id}>{c.nome} — {c.numero || 'S/N'}</option>)}
          </select></div>
      </MsgDrawerSection>

      <MsgDrawerSection title="Prompt do sistema">
        <div className="field span-2">
          <label>Instruções do agente (system prompt)</label>
          <textarea className="input" rows={6} placeholder="Descreva o papel, tom de voz, regras e limites do agente…"
            value={d.prompt_sistema || ''} onChange={e => set('prompt_sistema', e.target.value)}
            style={{ fontFamily: 'monospace', fontSize: 12, lineHeight: 1.5 }} />
          <div style={{ fontSize: 11, color: 'var(--tm-fg-4)', marginTop: 4 }}>
            Deixe vazio para usar o prompt padrão do tipo ({(AGENTE_TIPOS.find(a => a.value === d.tipo) || {}).label}).
          </div>
        </div>
        <div className="field span-2">
          <label>Mensagem de boas-vindas (enviada na 1ª interação)</label>
          <textarea className="input" rows={2} placeholder="Olá! Sou a assistente virtual da TopMix. Como posso te ajudar? 😊"
            value={d.prompt_abertura || ''} onChange={e => set('prompt_abertura', e.target.value)} />
        </div>
      </MsgDrawerSection>

      <MsgDrawerSection title="Horário de atendimento">
        <div className="field"><label>Início</label>
          <input className="input" type="time" value={d.horario_inicio || '08:00'} onChange={e => set('horario_inicio', e.target.value)} /></div>
        <div className="field"><label>Fim</label>
          <input className="input" type="time" value={d.horario_fim || '18:00'} onChange={e => set('horario_fim', e.target.value)} /></div>
        <div className="field span-2"><label>Dias ativos</label>
          <div style={{ display: 'flex', gap: 6, marginTop: 4 }}>
            {DIAS.map(dia => (
              <button key={dia.v} type="button" onClick={() => toggleDia(dia.v)}
                style={{
                  width: 38, height: 32, borderRadius: 6, border: '1px solid var(--tm-line-1)',
                  background: (d.dias_semana || [1,2,3,4,5]).includes(dia.v) ? 'var(--tm-brand-champagne)' : 'var(--tm-bg-2)',
                  color: (d.dias_semana || [1,2,3,4,5]).includes(dia.v) ? '#0B0B0D' : 'var(--tm-fg-3)',
                  fontSize: 11, fontWeight: 600, cursor: 'pointer',
                }}>
                {dia.l}
              </button>
            ))}
          </div>
        </div>
      </MsgDrawerSection>

      <MsgDrawerSection title="Limites e comportamento">
        <div className="field"><label>Máx. msgs sem humano</label>
          <input className="input" type="number" min="1" max="50" value={d.max_mensagens_sem_humano || 10}
            onChange={e => set('max_mensagens_sem_humano', parseInt(e.target.value) || 10)} />
          <div style={{ fontSize: 11, color: 'var(--tm-fg-4)', marginTop: 2 }}>Escala para humano após este limite</div>
        </div>
        <div className="field"><label>Temperatura</label>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <input type="range" min="0" max="1" step="0.1" value={d.temperatura || 0.7}
              onChange={e => set('temperatura', parseFloat(e.target.value))}
              style={{ flex: 1, accentColor: 'var(--tm-brand-champagne)' }} />
            <span style={{ fontSize: 12, fontWeight: 600, width: 28, textAlign: 'right' }}>{d.temperatura || 0.7}</span>
          </div>
          <div style={{ fontSize: 11, color: 'var(--tm-fg-4)', marginTop: 2 }}>0 = preciso, 1 = criativo</div>
        </div>
        <div className="field span-2">
          <label style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <input type="checkbox" checked={d.ativo !== false}
              onChange={e => set('ativo', e.target.checked)}
              style={{ accentColor: 'var(--tm-brand-champagne)' }} />
            Agente ativo
          </label>
        </div>
      </MsgDrawerSection>

      <MsgDrawerSection title="Mensagens especiais">
        <div className="field span-2"><label>Mensagem fora do horário</label>
          <textarea className="input" rows={2} placeholder="Olá! Nosso horário de atendimento é de seg a sex, 08h às 18h…"
            value={d.config?.mensagem_fora_horario || ''} onChange={e => set('config', { ...d.config, mensagem_fora_horario: e.target.value })} /></div>
        <div className="field span-2"><label>Mensagem de escalação</label>
          <textarea className="input" rows={2} placeholder="Vou transferir você para um atendente. Um momento! 🙏"
            value={d.config?.mensagem_escalacao || ''} onChange={e => set('config', { ...d.config, mensagem_escalacao: e.target.value })} /></div>
      </MsgDrawerSection>
    </Drawer>
  );
}

// ─── Template Form ──────────────────────────────────────────────────────────

function TemplateForm({ edit, set, onSave, onCancel, onDelete }) {
  if (!edit) return null;
  const d = edit.draft;
  const isNew = edit.mode === 'new';

  // Detect variables like {{nome}}, {{pedido}}
  const varsDetected = (d.conteudo || '').match(/\{\{(\w+)\}\}/g) || [];
  const varsClean = [...new Set(varsDetected.map(v => v.replace(/[{}]/g, '')))];

  return (
    <Drawer open={true} title={isNew ? 'Novo template' : 'Editar template'} width={480}
      onClose={onCancel}
      footer={<>
        {!isNew && onDelete && <Button variant="danger-ghost" size="sm" icon="trash-2" onClick={onDelete}>Excluir</Button>}
        <span style={{ flex: 1 }} />
        <Button variant="secondary" size="sm" onClick={onCancel}>Cancelar</Button>
        <Button variant="primary" size="sm" icon="check" onClick={onSave}>Salvar</Button>
      </>}>

      <MsgDrawerSection title="Dados do template">
        <div className="field"><label>Nome</label>
          <input className="input" placeholder="Boas-vindas, Rastreio…" value={d.nome || ''} onChange={e => set('nome', e.target.value)} /></div>
        <div className="field"><label>Categoria</label>
          <select className="input" value={d.categoria || 'geral'} onChange={e => set('categoria', e.target.value)}>
            {TEMPLATE_CATEGORIAS.map(c => <option key={c} value={c}>{c.charAt(0).toUpperCase() + c.slice(1)}</option>)}
          </select></div>
        <div className="field"><label>Atalho</label>
          <input className="input" placeholder="/boasvindas" value={d.atalho || ''} onChange={e => set('atalho', e.target.value)} />
          <div style={{ fontSize: 11, color: 'var(--tm-fg-4)', marginTop: 2 }}>Use no compositor: /atalho</div>
        </div>
      </MsgDrawerSection>

      <MsgDrawerSection title="Conteúdo">
        <div className="field span-2">
          <label>Mensagem</label>
          <textarea className="input" rows={5}
            placeholder={'Olá {{nome}}, tudo bem? 😊\n\nSeu pedido {{pedido}} está a caminho!\nPrevisão de entrega: {{data}}.'}
            value={d.conteudo || ''} onChange={e => set('conteudo', e.target.value)} />
          <div style={{ fontSize: 11, color: 'var(--tm-fg-4)', marginTop: 4 }}>
            Use {'{{variavel}}'} para campos dinâmicos. Variáveis detectadas: {varsClean.length > 0 ? varsClean.map(v => `{{${v}}}`).join(', ') : 'nenhuma'}
          </div>
        </div>
      </MsgDrawerSection>

      {varsClean.length > 0 && (
        <div style={{ padding: 12, background: 'var(--tm-bg-2)', borderRadius: 8, marginBottom: 16 }}>
          <div style={{ fontSize: 10.5, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--tm-fg-4)', marginBottom: 8 }}>
            Preview
          </div>
          <div style={{ fontSize: 13, color: 'var(--tm-fg-2)', whiteSpace: 'pre-wrap' }}>
            {(d.conteudo || '').replace(/\{\{(\w+)\}\}/g, (_, v) => `[${v}]`)}
          </div>
        </div>
      )}

      <div className="field span-2" style={{ marginTop: 0 }}>
        <label style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <input type="checkbox" checked={d.ativo !== false}
            onChange={e => set('ativo', e.target.checked)}
            style={{ accentColor: 'var(--tm-brand-champagne)' }} />
          Template ativo
        </label>
      </div>
    </Drawer>
  );
}

// ─── Exports ────────────────────────────────────────────────────────────────

Object.assign(window, {
  BLANK_CANAL, BLANK_AGENTE, BLANK_TEMPLATE,
  CanalConfigForm, AgenteConfigForm, TemplateForm,
});
