/* Base de Conhecimento — o que a IA sabe sobre seu negócio */

const Knowledge = () => {
  const t = useTheme();
  const { confirm, alert } = useDialog();
  const isBloom = t.name === 'BLOOM';

  const { data: sourcesData, refetch } = useKnowledgeSources();
  const sources = sourcesData || [];
  const [uploading, setUploading] = React.useState(false);
  const fileInputRef = React.useRef(null);

  const handleDelete = async (id) => {
    if (!(await confirm('Tem certeza que deseja deletar este documento?'))) return;
    try {
      await window.FluxoEndpoints.knowledge.removeSource(id);
      refetch();
    } catch (err) {
      await alert('Erro ao deletar documento');
    }
  };

  const handleUpload = async (e) => {
    const file = e.target.files[0];
    if (!file) return;
    setUploading(true);
    
    const formData = new FormData();
    formData.append('file', file);
    
    try {
      const res = await fetch('/api/knowledge/upload', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('fluxo_token')}`
        },
        body: formData
      });
      if (res.ok) {
        await alert('Upload concluído com sucesso!');
        refetch();
      } else {
        await alert('Erro ao fazer upload');
      }
    } catch (err) {
      await alert('Erro de conexão ao fazer upload');
    }
    setUploading(false);
  };

  return (
    <div style={{ padding: '24px 28px 40px', maxWidth: 1320, margin: '0 auto' }}>
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginBottom: 20, gap: 16 }}>
        <div>
          <div style={{ fontSize: 11, color: t.textMuted, letterSpacing: '0.14em', fontFamily: t.fontMono, marginBottom: 4 }}>
            INTELIGÊNCIA · APRENDIZADO
          </div>
          <h1 style={{ margin: 0, fontFamily: t.fontDisplay, fontSize: 32, fontWeight: 700, letterSpacing: '-0.03em', color: t.text }}>
            Base de Conhecimento
          </h1>
          <div style={{ marginTop: 8, fontSize: 14, color: t.textMuted, maxWidth: 640 }}>
            Tudo que a Assistente estudou pra atender seus clientes. Quanto mais você alimentar, mais autônoma e precisa ela fica.
          </div>
        </div>
        <div>
          <input type="file" ref={fileInputRef} onChange={handleUpload} style={{ display: 'none' }} accept=".pdf,.txt,.md,.docx,.csv" />
          <Btn variant="primary" onClick={() => fileInputRef.current.click()} loading={uploading} icon={<Icons.Upload size={14} stroke="#fff"/>}>
            {uploading ? 'Enviando...' : 'Adicionar fonte'}
          </Btn>
        </div>
      </div>

      {/* Status banner */}
      <Card style={{ padding: 22, marginBottom: 18, display: 'flex', alignItems: 'center', gap: 24 }}>
        <div style={{
          width: 64, height: 64, borderRadius: isBloom ? 14 : 12, flexShrink: 0,
          background: `linear-gradient(135deg, ${t.green}, ${t.primary})`,
          border: isBloom ? `1.5px solid ${t.border}` : 'none',
          boxShadow: isBloom ? '3px 3px 0 0 #14131A' : '0 8px 24px -8px rgba(91,141,239,0.4)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <Icons.Brain size={28} stroke="#fff"/>
        </div>
        <div style={{ flex: 1 }}>
          <div style={{ display: 'flex', gap: 12, alignItems: 'baseline' }}>
            <div style={{ fontFamily: t.fontDisplay, fontSize: 32, fontWeight: 700, color: t.text, letterSpacing: '-0.03em' }}>
              {sources.length > 0 ? Math.min(100, sources.length * 35) : 0}%
            </div>
            <div style={{ fontSize: 13, fontWeight: 600, color: t.text }}>de cobertura de conhecimento</div>
          </div>
          <div style={{ fontSize: 12, color: t.textMuted, marginTop: 4 }}>
            {sources.length > 0 ? `A Assistente estudou ${sources.length} fonte(s). 0 lacunas detectadas nas últimas 48h.` : 'A Assistente ainda não estudou nenhuma fonte. 0 lacunas detectadas nas últimas 48h.'}
          </div>
        </div>
        <Btn variant="secondary" icon={<Icons.ArrowRight size={14}/>}>Ver lacunas</Btn>
      </Card>

      {/* Sources */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 18 }}>
        <Card style={{ padding: 0, overflow: 'hidden' }}>
          <div style={{ padding: '16px 22px',
            borderBottom: isBloom ? `1.5px solid ${t.border}` : `1px solid ${t.border}`,
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          }}>
            <h3 style={{ margin: 0, fontFamily: t.fontDisplay, fontSize: 17, fontWeight: 700, color: t.text, letterSpacing: '-0.02em' }}>
              Fontes conectadas
            </h3>
            <span style={{ fontFamily: t.fontMono, fontSize: 11, color: t.textMuted }}>{sources.length} ativas</span>
          </div>
          {sources.map((s, i) => {
            const I = Icons[s.icon] || Icons.Document;
            return (
              <div key={i} style={{
                display: 'flex', alignItems: 'center', gap: 14, padding: '14px 22px',
                borderBottom: i < sources.length - 1 ? (isBloom ? `1.5px solid ${t.border}` : `1px solid ${t.border}`) : 'none',
              }}>
                <div style={{
                  width: 36, height: 36, borderRadius: isBloom ? 8 : 8,
                  background: isBloom ? t.bg : 'rgba(255,255,255,0.04)',
                  border: isBloom ? `1.5px solid ${t.border}` : 'none',
                  display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
                }}>
                  <I size={17} stroke={t.text}/>
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13.5, fontWeight: 600, color: t.text, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{s.label}</div>
                  <div style={{ fontSize: 11.5, color: t.textMuted, marginTop: 2, fontFamily: t.fontMono }}>
                    {s.count} · atualizado {s.updated || 'agora'}
                  </div>
                </div>
                <Pill soft={s.color === t.green ? t.greenSoft : t.orangeSoft} color={isBloom ? t.text : s.color}>
                  <span style={{width:6,height:6,borderRadius:'50%',background:s.color}}/>{s.status}
                </Pill>
                <Btn variant="ghost" size="sm" style={{ padding: 6 }} onClick={() => handleDelete(s.id)}>
                  <Icons.Trash size={14} color={t.red} />
                </Btn>
              </div>
            );
          })}
          <div style={{ padding: 14, textAlign: 'center',
            background: isBloom ? t.surfaceAlt : 'rgba(255,255,255,0.02)',
          }}>
            <Btn variant="ghost" size="sm" icon={<Icons.Plus size={12}/>}>Conectar nova fonte</Btn>
          </div>
        </Card>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
          <Card style={{ padding: 22, height: '100%' }}>
            <h3 style={{ margin: '0 0 16px', fontFamily: t.fontDisplay, fontSize: 16, fontWeight: 700, color: t.text, letterSpacing: '-0.02em' }}>
              Perguntas que a Assistente não soube responder
            </h3>
            <div style={{ padding: 20, textAlign: 'center', color: t.textMuted }}>Nenhuma lacuna de conhecimento detectada ainda.</div>
          </Card>

          <Card style={{ padding: 22 }}>
            <h3 style={{ margin: '0 0 16px', fontFamily: t.fontDisplay, fontSize: 16, fontWeight: 700, color: t.text, letterSpacing: '-0.02em' }}>
              Treinamentos sugeridos
            </h3>
            <div style={{ padding: 20, textAlign: 'center', color: t.textMuted }}>Nenhum treinamento sugerido ainda.</div>
          </Card>
        </div>
      </div>
    </div>
  );
};

window.Knowledge = Knowledge;
