import { useState, useRef, useEffect, useCallback } from 'react';
import { useAppStore, type AdbConfig, type AdbTable } from '@/stores/app';
import { embeddingsApi, type ConsultResult } from '@/api/endpoints/embeddings';
import { useI18n } from '@/i18n';
import {
  Search, Send, Loader2, Database, Trash2, User, Bot,
  FileText, Hash,
} from 'lucide-react';

/* ── Types ── */
interface ChatMessage {
  role: 'user' | 'assistant';
  content: string;
  sources?: ConsultResult['documents'];
  totalSources?: number;
}

/* ── Markdown-lite renderer ── */
function renderMarkdown(text: string): string {
  let html = text
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;');

  // Bold
  html = html.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>');
  // Italic
  html = html.replace(/\*(.+?)\*/g, '<em>$1</em>');
  // Inline code
  html = html.replace(/`(.+?)`/g, '<code style="background:var(--bg);padding:1px 4px;border-radius:3px;font-size:.72rem;font-family:var(--fm)">$1</code>');
  // Horizontal rule
  html = html.replace(/\n---\n/g, '<hr style="border:none;border-top:1px solid var(--bd);margin:8px 0">');
  // Line breaks
  html = html.replace(/\n/g, '<br>');

  return html;
}

/* ── Main ── */
export default function EmbConsultPage() {
  const { t } = useI18n();
  const { adbCfg } = useAppStore();

  // Config selectors
  const [selTable, setSelTable] = useState('');
  const [topK, setTopK] = useState(10);

  // Chat
  const [messages, setMessages] = useState<ChatMessage[]>([]);
  const [query, setQuery] = useState('');
  const [loading, setLoading] = useState(false);

  const msgsRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLInputElement>(null);

  // Auto scroll
  const scrollToBottom = useCallback(() => {
    if (msgsRef.current) {
      msgsRef.current.scrollTop = msgsRef.current.scrollHeight;
    }
  }, []);

  useEffect(() => {
    scrollToBottom();
  }, [messages, loading, scrollToBottom]);

  // Focus input on mount
  useEffect(() => {
    inputRef.current?.focus();
  }, []);

  // Table options from all active ADB configs
  const allTables: { name: string; configName: string }[] = [];
  for (const cfg of adbCfg) {
    for (const t of (cfg.tables || []).filter((t) => t.is_active)) {
      allTables.push({ name: t.table_name, configName: cfg.config_name });
    }
  }

  // Preconditions
  if (!adbCfg.length) {
    return (
      <div className="page-full flex items-center justify-center">
        <div className="empty-state">
          <Database size={36} />
          <h3>{t('emb.noAdb')}</h3>
          <p>{t('emb.noAdbHint')}</p>
        </div>
      </div>
    );
  }

  /* ── Submit ── */
  const handleSubmit = async () => {
    const q = query.trim();
    if (!q || loading) return;

    const userMsg: ChatMessage = { role: 'user', content: q };
    setMessages((prev) => [...prev, userMsg]);
    setQuery('');
    setLoading(true);

    try {
      const d = await embeddingsApi.consult(q, selTable || undefined, topK);
      let answer = d.answer || t('ec.noAnswer');

      const assistantMsg: ChatMessage = {
        role: 'assistant',
        content: answer,
        sources: d.documents,
        totalSources: d.total,
      };
      setMessages((prev) => [...prev, assistantMsg]);
    } catch (err) {
      const assistantMsg: ChatMessage = {
        role: 'assistant',
        content: `Erro: ${err instanceof Error ? err.message : 'Erro desconhecido'}`,
      };
      setMessages((prev) => [...prev, assistantMsg]);
    } finally {
      setLoading(false);
      inputRef.current?.focus();
    }
  };

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSubmit();
    }
  };

  const clearChat = () => {
    setMessages([]);
    inputRef.current?.focus();
  };

  return (
    <div className="page-full flex flex-col">
      <div className="max-w-5xl mx-auto w-full flex flex-col h-full p-6 gap-3">

        {/* Header */}
        <div className="card flex items-center justify-between flex-shrink-0" style={{ marginBottom: 0, padding: '14px 20px' }}>
          <div className="flex items-center gap-3">
            <div className="card-header icon" style={{ background: 'color-mix(in srgb, var(--bl) 12%, transparent)', margin: 0, padding: 0, border: 'none' }}>
              <Search size={18} style={{ color: 'var(--bl)' }} />
            </div>
            <div>
              <h1 style={{ fontSize: '1rem', fontWeight: 700, color: 'var(--t1)' }}>{t('ec.title')}</h1>
              <p className="subtitle" style={{ fontSize: '.72rem' }}>
                {t('ec.subtitle')}
              </p>
            </div>
          </div>
          {messages.length > 0 && (
            <button onClick={clearChat} className="btn btn-secondary btn-sm">
              <Trash2 size={12} />
              {t('ec.clear')}
            </button>
          )}
        </div>

        {/* Config bar */}
        <div className="flex gap-3 flex-wrap flex-shrink-0">
          <div className="flex-1 min-w-[180px]">
            <label className="block text-[.68rem] font-semibold mb-1" style={{ color: 'var(--t4)' }}>{t('ec.tableOptional')}</label>
            <select
              value={selTable}
              onChange={(e) => setSelTable(e.target.value)}
              className="w-full px-3 py-1.5 rounded-lg text-[.76rem] outline-none"
              style={{ background: 'var(--bg1)', border: '1px solid var(--bd)', color: 'var(--t1)' }}
            >
              <option value="">{t('ec.allTables')}</option>
              {allTables.map((t) => (
                <option key={t.name} value={t.name}>{t.name}</option>
              ))}
            </select>
          </div>
          <div className="w-[80px]">
            <label className="block text-[.68rem] font-semibold mb-1" style={{ color: 'var(--t4)' }}>Top-K</label>
            <input
              type="number"
              value={topK}
              onChange={(e) => setTopK(Math.max(1, Math.min(30, parseInt(e.target.value) || 10)))}
              min={1}
              max={30}
              className="w-full px-3 py-1.5 rounded-lg text-[.76rem] outline-none text-center"
              style={{ background: 'var(--bg1)', border: '1px solid var(--bd)', color: 'var(--t1)' }}
            />
          </div>
        </div>

        {/* Messages area */}
        <div
          ref={msgsRef}
          className="flex-1 overflow-y-auto rounded-xl p-4 flex flex-col gap-3 min-h-0"
          style={{ background: 'var(--bg1)', border: '1px solid var(--bd)' }}
        >
          {messages.length === 0 && !loading && (
            <div className="flex-1 flex items-center justify-center">
              <div className="text-center">
                <Search size={32} style={{ color: 'var(--t4)', margin: '0 auto 10px', opacity: 0.5 }} />
                <p className="text-[.82rem] font-medium" style={{ color: 'var(--t3)' }}>
                  {t('ec.emptyTitle')}
                </p>
                <p className="text-[.7rem] mt-2" style={{ color: 'var(--t4)' }}>
                  {t('ec.emptyHint')}
                </p>
              </div>
            </div>
          )}

          {messages.map((msg, i) => (
            <div key={i} className={`flex gap-2.5 ${msg.role === 'user' ? 'justify-end' : 'justify-start'}`}>
              {msg.role === 'assistant' && (
                <div className="flex-shrink-0 w-7 h-7 rounded-lg flex items-center justify-center mt-0.5" style={{ background: 'color-mix(in srgb, var(--bl) 12%, transparent)' }}>
                  <Bot size={14} style={{ color: 'var(--bl)' }} />
                </div>
              )}
              <div
                className="max-w-[80%] rounded-xl px-4 py-3"
                style={{
                  background: msg.role === 'user' ? 'var(--ac)' : 'var(--bg2)',
                  color: msg.role === 'user' ? '#fff' : 'var(--t1)',
                }}
              >
                {msg.role === 'user' ? (
                  <p className="text-[.8rem] leading-relaxed">{msg.content}</p>
                ) : (
                  <div className="text-[.8rem] leading-relaxed" dangerouslySetInnerHTML={{ __html: renderMarkdown(msg.content) }} />
                )}

                {/* Sources */}
                {msg.sources && msg.sources.length > 0 && (
                  <div className="mt-3 pt-3" style={{ borderTop: '1px solid var(--bd)' }}>
                    <div className="flex items-center gap-1.5 mb-2">
                      <FileText size={12} style={{ color: 'var(--t4)' }} />
                      <span className="text-[.66rem] font-semibold" style={{ color: 'var(--t4)' }}>
                        {t('ec.sources')} ({msg.sources.length} documentos{msg.totalSources ? `, ${msg.totalSources} total` : ''})
                      </span>
                    </div>
                    <div className="flex flex-col gap-1">
                      {msg.sources.map((src, j) => (
                        <div key={j} className="flex items-center gap-2 px-2 py-1 rounded" style={{ background: 'var(--bg)' }}>
                          <Hash size={10} style={{ color: 'var(--t4)' }} />
                          <span className="text-[.66rem] font-semibold" style={{ color: 'var(--bl)' }}>{src.source}</span>
                          <span className="text-[.6rem]" style={{ color: 'var(--t4)' }}>
                            dist: {src.distance.toFixed(4)}
                          </span>
                        </div>
                      ))}
                    </div>
                  </div>
                )}
              </div>
              {msg.role === 'user' && (
                <div className="flex-shrink-0 w-7 h-7 rounded-lg flex items-center justify-center mt-0.5" style={{ background: 'color-mix(in srgb, var(--ac) 15%, transparent)' }}>
                  <User size={14} style={{ color: 'var(--ac)' }} />
                </div>
              )}
            </div>
          ))}

          {/* Loading indicator */}
          {loading && (
            <div className="flex gap-2.5 justify-start">
              <div className="flex-shrink-0 w-7 h-7 rounded-lg flex items-center justify-center mt-0.5" style={{ background: 'color-mix(in srgb, var(--bl) 12%, transparent)' }}>
                <Bot size={14} style={{ color: 'var(--bl)' }} />
              </div>
              <div className="rounded-xl px-4 py-3 flex items-center gap-2" style={{ background: 'var(--bg2)' }}>
                <Loader2 size={14} className="animate-spin" style={{ color: 'var(--bl)' }} />
                <span className="text-[.76rem]" style={{ color: 'var(--t3)' }}>{t('ec.searching')}</span>
              </div>
            </div>
          )}
        </div>

        {/* Input bar */}
        <div className="flex gap-2.5 flex-shrink-0">
          <input
            ref={inputRef}
            type="text"
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            onKeyDown={handleKeyDown}
            placeholder={t('ec.placeholder')}
            disabled={loading}
            className="flex-1 px-4 py-2.5 rounded-xl text-[.82rem] outline-none transition-colors focus:ring-1 disabled:opacity-60"
            style={{ background: 'var(--bg1)', border: '1.5px solid var(--bd)', color: 'var(--t1)' }}
          />
          <button
            onClick={handleSubmit}
            disabled={loading || !query.trim()}
            className="btn"
            style={{ background: 'var(--bl)', color: '#fff', borderColor: 'var(--bl)', borderRadius: '12px' }}
          >
            {loading ? <Loader2 size={16} className="animate-spin" /> : <Send size={16} />}
            {t('ec.submit')}
          </button>
        </div>

      </div>
    </div>
  );
}
