// PAC Sistema — Assistente IA

const AIAssistant = ({ user }) => {
  const [messages, setMessages] = React.useState([
    {
      id: 'welcome',
      role: 'assistant',
      content: 'Olá! Sou a **PAC.AI**, sua assistente jurídica. Posso analisar documentos, responder dúvidas sobre casos e clientes, e criar tarefas no Kanban.\n\nComo posso ajudar hoje?',
      ts: new Date(),
    }
  ]);
  const [input, setInput] = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const [listening, setListening] = React.useState(false);
  const [error, setError] = React.useState('');
  const [pendingTask, setPendingTask] = React.useState(null);
  const [creatingTask, setCreatingTask] = React.useState(false);

  const bottomRef = React.useRef(null);
  const inputRef = React.useRef(null);
  const recognitionRef = React.useRef(null);
  const fileInputRef = React.useRef(null);

  React.useEffect(() => {
    bottomRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [messages, loading]);

  // Inicializar SpeechRecognition
  React.useEffect(() => {
    const SR = window.SpeechRecognition || window.webkitSpeechRecognition;
    if (SR) {
      const rec = new SR();
      rec.lang = 'pt-BR';
      rec.interimResults = false;
      rec.continuous = false;
      rec.onresult = (e) => {
        const transcript = e.results[0][0].transcript;
        setInput(prev => (prev ? prev + ' ' : '') + transcript);
        setListening(false);
      };
      rec.onerror = () => setListening(false);
      rec.onend = () => setListening(false);
      recognitionRef.current = rec;
    }
    return () => recognitionRef.current?.stop();
  }, []);

  const toggleVoice = () => {
    const rec = recognitionRef.current;
    if (!rec) {
      alert('Reconhecimento de voz não suportado neste navegador. Use Chrome ou Safari.');
      return;
    }
    if (listening) {
      rec.stop();
      setListening(false);
    } else {
      rec.start();
      setListening(true);
    }
  };

  const sendMessage = async (text) => {
    const q = (text || input).trim();
    if (!q || loading) return;
    setInput('');
    setError('');

    const userMsg = { id: Date.now() + 'u', role: 'user', content: q, ts: new Date() };
    setMessages(prev => [...prev, userMsg]);
    setLoading(true);

    try {
      const result = await window.PACApi.ai.chat(q);
      const aiMsg = {
        id: Date.now() + 'a',
        role: 'assistant',
        content: result.answer,
        ts: new Date(),
        tokens: { in: result.input_tokens, out: result.output_tokens },
        suggestedTask: result.suggested_task || null,
      };
      setMessages(prev => [...prev, aiMsg]);
      if (result.suggested_task) setPendingTask(result.suggested_task);
    } catch (err) {
      setError(err.message || 'Erro ao consultar a IA.');
    } finally {
      setLoading(false);
    }
  };

  const handleFileUpload = async (file) => {
    if (!file) return;
    const allowed = ['application/pdf', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'text/plain'];
    if (!allowed.includes(file.type) && !file.name.endsWith('.docx') && !file.name.endsWith('.pdf') && !file.name.endsWith('.txt')) {
      setError('Apenas PDF, DOCX e TXT são suportados.');
      return;
    }
    setError('');
    const fileMsg = {
      id: Date.now() + 'f',
      role: 'user',
      content: `Analisando documento: **${file.name}**`,
      ts: new Date(),
      isFile: true,
    };
    setMessages(prev => [...prev, fileMsg]);
    setLoading(true);

    try {
      const result = await window.PACApi.ai.analyze(file);
      const aiMsg = {
        id: Date.now() + 'a',
        role: 'assistant',
        content: result.answer || result.analysis || 'Análise concluída.',
        ts: new Date(),
        tokens: { in: result.input_tokens, out: result.output_tokens },
        suggestedTask: result.suggested_task || null,
      };
      setMessages(prev => [...prev, aiMsg]);
      if (result.suggested_task) setPendingTask(result.suggested_task);
    } catch (err) {
      setError(err.message || 'Erro ao analisar documento.');
    } finally {
      setLoading(false);
    }
  };

  const handleCreateTask = async () => {
    if (!pendingTask) return;
    setCreatingTask(true);
    try {
      const taskPayload = {
        title: pendingTask.title,
        description: pendingTask.description || '',
        priority: pendingTask.priority || 'media',
        kanban_column: pendingTask.kanban_column || 'backlog',
        due_date: pendingTask.due_date || null,
      };
      const task = await window.PACApi.tasks.create(taskPayload);
      const confirmMsg = {
        id: Date.now() + 'c',
        role: 'assistant',
        content: `Tarefa **"${task.title}"** criada no Kanban com sucesso! Você pode encontrá-la na coluna **${task.kanban_column || 'Backlog'}**.`,
        ts: new Date(),
      };
      setMessages(prev => [...prev, confirmMsg]);
      setPendingTask(null);
    } catch (err) {
      setError('Erro ao criar tarefa: ' + err.message);
    } finally {
      setCreatingTask(false);
    }
  };

  const handleKeyDown = (e) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      sendMessage();
    }
  };

  // Ajusta altura do textarea dinamicamente
  const handleInputChange = (e) => {
    setInput(e.target.value);
    e.target.style.height = 'auto';
    e.target.style.height = Math.min(e.target.scrollHeight, 120) + 'px';
  };

  const formatTime = (d) => d.toLocaleTimeString('pt-BR', { hour: '2-digit', minute: '2-digit' });

  // Renderiza markdown simples (negrito, código, listas, quebras de linha)
  const renderContent = (text) => {
    return text.split('\n').map((line, i) => {
      if (!line) return <div key={i} style={{ height: 6 }} />;
      const parts = line.split(/(\*\*[^*]+\*\*|`[^`]+`)/g).map((p, j) => {
        if (p.startsWith('**') && p.endsWith('**'))
          return <strong key={j}>{p.slice(2, -2)}</strong>;
        if (p.startsWith('`') && p.endsWith('`'))
          return <code key={j} style={{ background: 'rgba(13,13,107,.06)', padding: '1px 5px', borderRadius: 3, fontSize: '0.9em', fontFamily: 'monospace' }}>{p.slice(1, -1)}</code>;
        return p;
      });
      // Detectar itens de lista
      if (line.match(/^[\d]+\.\s/)) {
        return <div key={i} style={{ display: 'flex', gap: 6, paddingLeft: 4 }}><span style={{ flexShrink: 0, color: '#0D0D6B', fontWeight: 700 }}>{line.match(/^([\d]+\.)/)[1]}</span><span>{parts.slice(1)}</span></div>;
      }
      return <div key={i}>{parts}</div>;
    });
  };

  const hasVoice = !!(window.SpeechRecognition || window.webkitSpeechRecognition);
  const quickPrompts = ['Quais casos têm prazo esta semana?', 'Resumir últimos eventos do escritório', 'Criar tarefa de acompanhamento'];

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%', maxWidth: 860, margin: '0 auto' }}>

      {/* Header */}
      <div style={{
        padding: '18px 24px 14px',
        borderBottom: '1px solid var(--border)',
        display: 'flex',
        alignItems: 'center',
        gap: 12,
        flexShrink: 0,
        background: 'var(--surface)',
      }}>
        <div style={{
          width: 40, height: 40, borderRadius: '50%',
          background: 'linear-gradient(135deg, #0D0D6B 0%, #3F2C5F 100%)',
          display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
        }}>
          <Icon name="sparkles" size={18} style={{ color: '#C8F135' }} />
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontWeight: 700, fontSize: 15, color: 'var(--pac-navy)' }}>PAC.AI</div>
          <div style={{ fontSize: 11.5, color: 'var(--fg-muted)' }}>Assistente jurídica · Opera sobre dados internos do escritório</div>
        </div>
        <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
          {quickPrompts.map(s => (
            <button key={s} onClick={() => { setInput(s); inputRef.current?.focus(); }} style={{
              padding: '4px 10px', borderRadius: 20,
              border: '1px solid var(--border)',
              background: 'white', fontSize: 11, cursor: 'pointer',
              color: 'var(--fg-muted)', whiteSpace: 'nowrap',
              transition: 'background .15s, color .15s',
            }}
              onMouseEnter={e => { e.currentTarget.style.background = '#0D0D6B'; e.currentTarget.style.color = 'white'; }}
              onMouseLeave={e => { e.currentTarget.style.background = 'white'; e.currentTarget.style.color = 'var(--fg-muted)'; }}
            >{s}</button>
          ))}
        </div>
      </div>

      {/* Messages */}
      <div style={{ flex: 1, overflowY: 'auto', padding: '20px 24px', display: 'flex', flexDirection: 'column', gap: 18 }}>
        {messages.map(msg => (
          <div key={msg.id} style={{
            display: 'flex',
            flexDirection: msg.role === 'user' ? 'row-reverse' : 'row',
            gap: 10,
            alignItems: 'flex-start',
          }}>
            {msg.role === 'assistant' && (
              <div style={{
                width: 32, height: 32, borderRadius: '50%', flexShrink: 0,
                background: 'linear-gradient(135deg, #0D0D6B 0%, #3F2C5F 100%)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}>
                <Icon name="sparkles" size={14} style={{ color: '#C8F135' }} />
              </div>
            )}

            <div style={{
              maxWidth: '76%',
              display: 'flex', flexDirection: 'column', gap: 6,
              alignItems: msg.role === 'user' ? 'flex-end' : 'flex-start',
            }}>
              {/* Bubble */}
              <div style={{
                padding: '11px 15px',
                borderRadius: msg.role === 'user' ? '18px 18px 4px 18px' : '4px 18px 18px 18px',
                background: msg.role === 'user' ? '#0D0D6B' : 'white',
                color: msg.role === 'user' ? 'white' : 'var(--pac-black)',
                fontSize: 13.5,
                lineHeight: 1.65,
                boxShadow: '0 1px 4px rgba(0,0,0,.08)',
                border: msg.role === 'assistant' ? '1px solid var(--border)' : 'none',
              }}>
                {msg.isFile
                  ? <span style={{ opacity: .85, fontStyle: 'italic' }}>📎 {msg.content.replace('Analisando documento: ', '')}</span>
                  : <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>{renderContent(msg.content)}</div>
                }
              </div>

              {/* Task suggestion card */}
              {msg.suggestedTask && pendingTask && msg.suggestedTask.title === pendingTask.title && (
                <div style={{
                  background: '#f3fce8',
                  border: '1.5px solid #c8f135',
                  borderRadius: 12,
                  padding: '12px 14px',
                  fontSize: 12.5,
                  maxWidth: '100%',
                }}>
                  <div style={{ fontWeight: 700, marginBottom: 6, color: '#1a4000', display: 'flex', alignItems: 'center', gap: 6 }}>
                    <Icon name="zap" size={13} style={{ color: '#4a8000' }} />
                    Tarefa sugerida pela IA
                  </div>
                  <div style={{ marginBottom: 4 }}>
                    <strong style={{ color: '#1a1a2e' }}>{pendingTask.title}</strong>
                    {pendingTask.priority && (
                      <span style={{ marginLeft: 7, fontSize: 10.5, padding: '1px 7px', borderRadius: 10, background: '#d4edaa', color: '#2a5a00', fontWeight: 600 }}>
                        {pendingTask.priority}
                      </span>
                    )}
                    {pendingTask.due_date && (
                      <span style={{ marginLeft: 7, fontSize: 10.5, color: '#666' }}>
                        📅 {pendingTask.due_date}
                      </span>
                    )}
                  </div>
                  {pendingTask.description && (
                    <div style={{ fontSize: 12, color: '#555', marginBottom: 8, lineHeight: 1.5 }}>
                      {pendingTask.description.slice(0, 120)}{pendingTask.description.length > 120 ? '…' : ''}
                    </div>
                  )}
                  <div style={{ display: 'flex', gap: 6 }}>
                    <button onClick={handleCreateTask} disabled={creatingTask} style={{
                      padding: '5px 13px', borderRadius: 7, border: 'none',
                      background: '#0D0D6B', color: 'white', fontSize: 12,
                      cursor: creatingTask ? 'not-allowed' : 'pointer', fontWeight: 600,
                      display: 'flex', alignItems: 'center', gap: 5,
                    }}>
                      {creatingTask
                        ? <><span className="spinner" style={{ width: 11, height: 11, borderColor: 'rgba(255,255,255,.2)', borderTopColor: '#fff' }} /> Criando…</>
                        : <><Icon name="plus" size={12} /> Criar no Kanban</>
                      }
                    </button>
                    <button onClick={() => setPendingTask(null)} style={{
                      padding: '5px 12px', borderRadius: 7,
                      border: '1px solid var(--border)',
                      background: 'white', fontSize: 12, cursor: 'pointer', color: '#666',
                    }}>Descartar</button>
                  </div>
                </div>
              )}

              {/* Timestamp + tokens */}
              <div style={{ fontSize: 10.5, color: 'var(--fg-muted)', paddingLeft: msg.role === 'user' ? 0 : 4 }}>
                {formatTime(msg.ts)}
                {msg.tokens && ` · ${(msg.tokens.in + msg.tokens.out).toLocaleString()} tokens`}
              </div>
            </div>
          </div>
        ))}

        {/* Loading indicator */}
        {loading && (
          <div style={{ display: 'flex', gap: 10, alignItems: 'flex-start' }}>
            <div style={{
              width: 32, height: 32, borderRadius: '50%', flexShrink: 0,
              background: 'linear-gradient(135deg, #0D0D6B 0%, #3F2C5F 100%)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>
              <Icon name="sparkles" size={14} style={{ color: '#C8F135' }} />
            </div>
            <div style={{
              padding: '14px 18px',
              borderRadius: '4px 18px 18px 18px',
              background: 'white', border: '1px solid var(--border)',
              boxShadow: '0 1px 4px rgba(0,0,0,.08)',
            }}>
              <div style={{ display: 'flex', gap: 5, alignItems: 'center' }}>
                {[0, 1, 2].map(i => (
                  <div key={i} style={{
                    width: 7, height: 7, borderRadius: '50%',
                    background: '#0D0D6B', opacity: 0.6,
                    animation: `pac-bounce 1.2s ${i * 0.2}s infinite ease-in-out`,
                  }} />
                ))}
              </div>
            </div>
          </div>
        )}

        {/* Error */}
        {error && (
          <div style={{
            padding: '10px 14px', borderRadius: 8, fontSize: 12.5,
            background: 'rgba(194,37,62,.07)', border: '1px solid rgba(194,37,62,.2)',
            color: '#C2253E', display: 'flex', alignItems: 'center', gap: 8,
          }}>
            <Icon name="alertTriangle" size={14} />
            {error}
          </div>
        )}

        <div ref={bottomRef} />
      </div>

      {/* Input area */}
      <div style={{
        padding: '12px 24px 16px',
        borderTop: '1px solid var(--border)',
        background: 'var(--surface)',
        flexShrink: 0,
      }}>
        <div style={{
          display: 'flex', gap: 8, alignItems: 'flex-end',
          background: 'white',
          border: `1.5px solid ${listening ? '#C2253E' : 'var(--border)'}`,
          borderRadius: 16, padding: '8px 8px 8px 14px',
          boxShadow: '0 1px 5px rgba(0,0,0,.07)',
          transition: 'border-color .2s',
        }}>
          {/* File upload button */}
          <button onClick={() => fileInputRef.current?.click()} title="Enviar documento (PDF, DOCX, TXT)"
            style={{
              width: 34, height: 34, borderRadius: 8, border: 'none',
              background: 'transparent', cursor: 'pointer', flexShrink: 0,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              color: 'var(--fg-muted)', transition: 'background .15s',
            }}
            onMouseEnter={e => e.currentTarget.style.background = '#f0f0f7'}
            onMouseLeave={e => e.currentTarget.style.background = 'transparent'}
          >
            <Icon name="paperclip" size={16} />
          </button>
          <input ref={fileInputRef} type="file" accept=".pdf,.docx,.txt"
            style={{ display: 'none' }}
            onChange={e => { handleFileUpload(e.target.files?.[0]); e.target.value = ''; }}
          />

          {/* Textarea */}
          <textarea
            ref={inputRef}
            value={input}
            onChange={handleInputChange}
            onKeyDown={handleKeyDown}
            placeholder={listening ? '🎙️ Ouvindo… fale agora' : 'Pergunte algo, dite sua mensagem ou envie um documento…'}
            rows={1}
            style={{
              flex: 1, border: 'none', outline: 'none', resize: 'none',
              fontSize: 13.5, lineHeight: 1.55, fontFamily: 'inherit',
              color: 'var(--pac-black)', background: 'transparent',
              maxHeight: 120, overflowY: 'auto',
            }}
          />

          {/* Voice button */}
          {hasVoice && (
            <button onClick={toggleVoice} title={listening ? 'Parar gravação' : 'Enviar mensagem de voz'}
              style={{
                width: 34, height: 34, borderRadius: 8, border: 'none', flexShrink: 0,
                background: listening ? 'rgba(194,37,62,.12)' : 'transparent',
                cursor: 'pointer',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                color: listening ? '#C2253E' : 'var(--fg-muted)',
                transition: 'background .15s, color .15s',
              }}
            >
              <Icon name="mic" size={16} />
            </button>
          )}

          {/* Send button */}
          <button onClick={() => sendMessage()} disabled={!input.trim() || loading}
            style={{
              width: 34, height: 34, borderRadius: 8, border: 'none', flexShrink: 0,
              background: input.trim() && !loading ? '#0D0D6B' : '#e8e8f0',
              cursor: input.trim() && !loading ? 'pointer' : 'default',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              color: input.trim() && !loading ? 'white' : '#bbb',
              transition: 'background .15s, color .15s',
            }}
          >
            <Icon name="send" size={15} />
          </button>
        </div>

        <div style={{ fontSize: 10.5, color: 'var(--fg-muted)', marginTop: 6, paddingLeft: 4, display: 'flex', gap: 16 }}>
          <span>Enter para enviar · Shift+Enter nova linha</span>
          <span>PDF, DOCX e TXT suportados</span>
          {hasVoice && <span>🎙️ Voz disponível</span>}
        </div>
      </div>

      <style>{`
        @keyframes pac-bounce {
          0%, 60%, 100% { transform: translateY(0); opacity: 0.5; }
          30% { transform: translateY(-6px); opacity: 1; }
        }
      `}</style>
    </div>
  );
};

window.AIAssistant = AIAssistant;
