import { useState, useEffect, useCallback, useRef } from 'react';
import { useAppStore } from '@/stores/app';
import { useI18n } from '@/i18n';
import { adbApi, type AdbConfigFull } from '@/api/endpoints/adb';
import {
  Database, Plus, Pencil, Trash2, FlaskConical, Check, X, Loader2,
  ChevronRight, Upload, Shield, Table2, ChevronDown, ChevronUp, Search,
} from 'lucide-react';

/* ── Msg ── */
function Msg({ type, text }: { type: 's' | 'e' | 'i'; text: string }) {
  const bg = type === 's' ? 'var(--gnl)' : type === 'e' ? 'var(--rdl)' : 'var(--bg2)';
  const fg = type === 's' ? 'var(--gn)' : type === 'e' ? 'var(--rd)' : 'var(--t2)';
  return (
    <div className="flex items-center gap-2 px-3 py-2 rounded-lg text-xs" style={{ background: bg, color: fg }}>
      {type === 's' && <Check size={14} />}
      {type === 'e' && <X size={14} />}
      {type === 'i' && <Loader2 size={14} className="animate-spin" />}
      <span dangerouslySetInnerHTML={{ __html: text }} />
    </div>
  );
}

/* ── Main ── */
export default function AdbConfigPage() {
  const { genaiCfg, embModels } = useAppStore();
  const { t } = useI18n();

  const [configs, setConfigs] = useState<AdbConfigFull[]>([]);
  const [loading, setLoading] = useState(true);

  // Form
  const [formOpen, setFormOpen] = useState(false);
  const [editing, setEditing] = useState<AdbConfigFull | null>(null);
  const [saving, setSaving] = useState(false);
  const [formMsg, setFormMsg] = useState<{ type: 's' | 'e' | 'i'; text: string } | null>(null);
  const formRef = useRef<HTMLDivElement>(null);
  const walletRef = useRef<HTMLInputElement>(null);

  // Form fields
  const [cfgName, setCfgName] = useState('');
  const [dsn, setDsn] = useState('');
  const [dsnOptions, setDsnOptions] = useState<string[]>([]);
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [walletPassword, setWalletPassword] = useState('');
  const [genaiConfigId, setGenaiConfigId] = useState('');
  const [embeddingModelId, setEmbeddingModelId] = useState('cohere.embed-v4.0');
  const [parsingWallet, setParsingWallet] = useState(false);

  // Table
  const [tableMsg, setTableMsg] = useState<{ type: 's' | 'e' | 'i'; text: string } | null>(null);
  const [testResults, setTestResults] = useState<Record<string, { type: 's' | 'e'; text: string }>>({});
  const [testingMap, setTestingMap] = useState<Record<string, boolean>>({});
  const [confirmDelete, setConfirmDelete] = useState<string | null>(null);
  const [expandedTables, setExpandedTables] = useState<Record<string, boolean>>({});

  // Wallet upload section
  const walletUploadRef = useRef<HTMLInputElement>(null);
  const [walletUploadId, setWalletUploadId] = useState('');
  const [uploadingWallet, setUploadingWallet] = useState(false);
  const [walletMsg, setWalletMsg] = useState<{ type: 's' | 'e' | 'i'; text: string } | null>(null);

  // New table form
  const [newTableName, setNewTableName] = useState('');
  const [newTableDesc, setNewTableDesc] = useState('');

  const fetchConfigs = useCallback(async () => {
    try {
      const data = await adbApi.list();
      setConfigs(data);
    } catch {} finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => { fetchConfigs(); }, [fetchConfigs]);

  const resetForm = () => {
    setEditing(null);
    setFormOpen(false);
    setCfgName('');
    setDsn('');
    setDsnOptions([]);
    setUsername('');
    setPassword('');
    setWalletPassword('');
    setGenaiConfigId('');
    setEmbeddingModelId('cohere.embed-v4.0');
    setFormMsg(null);
    setSaving(false);
    if (walletRef.current) walletRef.current.value = '';
  };

  const startEdit = (cfg: AdbConfigFull) => {
    setEditing(cfg);
    setCfgName(cfg.config_name);
    setDsn(cfg.dsn);
    setDsnOptions([]);
    setUsername(cfg.username);
    setPassword('');
    setWalletPassword('');
    setGenaiConfigId(cfg.genai_config_id || '');
    setEmbeddingModelId(cfg.embedding_model_id || 'cohere.embed-v4.0');
    setFormOpen(true);
    setFormMsg(null);
    setTimeout(() => formRef.current?.scrollIntoView({ behavior: 'smooth', block: 'start' }), 100);
  };

  const parseWallet = async () => {
    const file = walletRef.current?.files?.[0];
    if (!file) { setFormMsg({ type: 'e', text: t('adb.selectWallet') }); return; }
    setParsingWallet(true);
    try {
      const result = await adbApi.parseWallet(file);
      setDsnOptions(result.dsn_names);
      if (result.dsn_names.length > 0) setDsn(result.dsn_names[0]);
      setFormMsg({ type: 's', text: `Wallet analisado! ${result.dsn_names.length} DSN(s): <strong>${result.dsn_names.join(', ')}</strong>. Arquivos: ${result.files.join(', ')}` });
    } catch (err) {
      setFormMsg({ type: 'e', text: err instanceof Error ? err.message : 'Erro ao analisar wallet' });
    } finally {
      setParsingWallet(false);
    }
  };

  const handleSave = async () => {
    if (!cfgName.trim()) { setFormMsg({ type: 'e', text: t('adb.fillName') }); return; }
    if (!dsn.trim()) { setFormMsg({ type: 'e', text: t('adb.fillDsn') }); return; }
    if (!username.trim()) { setFormMsg({ type: 'e', text: t('adb.fillUsername') }); return; }
    if (!editing && !password) { setFormMsg({ type: 'e', text: t('adb.fillPassword') }); return; }

    const fd = new FormData();
    fd.append('config_name', cfgName.trim());
    fd.append('dsn', dsn.trim());
    fd.append('username', username.trim());
    fd.append('password', password);
    fd.append('wallet_password', walletPassword);
    fd.append('use_mtls', 'true');
    fd.append('genai_config_id', genaiConfigId);
    fd.append('embedding_model_id', embeddingModelId);
    const walletFile = walletRef.current?.files?.[0];
    if (walletFile) fd.append('wallet', walletFile);

    setSaving(true);
    setFormMsg({ type: 'i', text: t('adb.saving') });

    try {
      if (editing) {
        await adbApi.update(editing.id, fd);
      } else {
        await adbApi.create(fd);
      }
      setFormMsg({ type: 's', text: `Conexao ${editing ? 'atualizada' : 'salva'}!${walletFile ? ' Wallet incluido.' : ''}` });
      await fetchConfigs();
      useAppStore.getState().loadData();
      setTimeout(resetForm, 1200);
    } catch (err) {
      setFormMsg({ type: 'e', text: err instanceof Error ? err.message : 'Erro ao salvar' });
      setSaving(false);
    }
  };

  const handleDelete = async (id: string) => {
    setConfirmDelete(null);
    setTableMsg({ type: 'i', text: t('adb.deleting') });
    try {
      await adbApi.remove(id);
      await fetchConfigs();
      useAppStore.getState().loadData();
      setTableMsg({ type: 's', text: 'Conexao excluida com sucesso!' });
      if (editing?.id === id) resetForm();
      setTimeout(() => setTableMsg(null), 3000);
    } catch (err) {
      setTableMsg({ type: 'e', text: err instanceof Error ? err.message : 'Erro ao excluir' });
    }
  };

  const handleTest = async (id: string) => {
    setTestingMap((p) => ({ ...p, [id]: true }));
    setTestResults((p) => { const n = { ...p }; delete n[id]; return n; });
    try {
      const res = await adbApi.test(id);
      setTestResults((p) => ({
        ...p,
        [id]: { type: res.status === 'success' ? 's' : 'e', text: res.message },
      }));
    } catch (err) {
      setTestResults((p) => ({ ...p, [id]: { type: 'e', text: err instanceof Error ? err.message : 'Erro' } }));
    } finally {
      setTestingMap((p) => ({ ...p, [id]: false }));
    }
  };

  const handleWalletUpload = async () => {
    const file = walletUploadRef.current?.files?.[0];
    if (!file) { setWalletMsg({ type: 'e', text: t('adb.selectWallet') }); return; }
    if (!walletUploadId) { setWalletMsg({ type: 'e', text: t('adb.selectConnection') }); return; }
    setUploadingWallet(true);
    setWalletMsg({ type: 'i', text: 'Enviando wallet...' });
    try {
      const res = await adbApi.uploadWallet(walletUploadId, file);
      await fetchConfigs();
      useAppStore.getState().loadData();
      setWalletMsg({ type: 's', text: `Wallet enviada! Arquivos: ${res.files.join(', ')}` });
      if (walletUploadRef.current) walletUploadRef.current.value = '';
    } catch (err) {
      setWalletMsg({ type: 'e', text: err instanceof Error ? err.message : 'Erro ao enviar wallet' });
    } finally {
      setUploadingWallet(false);
    }
  };

  const handleAddTable = async (vid: string) => {
    if (!newTableName.trim()) { setTableMsg({ type: 'e', text: 'Digite o nome da tabela.' }); return; }
    try {
      await adbApi.addTable(vid, newTableName.trim(), newTableDesc.trim());
      await fetchConfigs();
      useAppStore.getState().loadData();
      setTableMsg({ type: 's', text: `Tabela ${newTableName.trim()} registrada!` });
      setNewTableName('');
      setNewTableDesc('');
      setTimeout(() => setTableMsg(null), 3000);
    } catch (err) {
      setTableMsg({ type: 'e', text: err instanceof Error ? err.message : 'Erro' });
    }
  };

  const handleToggleTable = async (vid: string, tid: string, currentActive: boolean) => {
    try {
      await adbApi.updateTable(vid, tid, { is_active: !currentActive });
      await fetchConfigs();
      useAppStore.getState().loadData();
    } catch (err) {
      setTableMsg({ type: 'e', text: err instanceof Error ? err.message : 'Erro' });
    }
  };

  const handleRemoveTable = async (vid: string, tid: string) => {
    if (!confirm('Excluir esta tabela do registro?')) return;
    try {
      await adbApi.removeTable(vid, tid);
      await fetchConfigs();
      useAppStore.getState().loadData();
      setTableMsg({ type: 's', text: 'Tabela removida.' });
      setTimeout(() => setTableMsg(null), 3000);
    } catch (err) {
      setTableMsg({ type: 'e', text: err instanceof Error ? err.message : 'Erro' });
    }
  };

  const isFormVisible = formOpen || !!editing;
  const inputCls = "w-full px-3 py-2 rounded-lg text-[.78rem] outline-none transition-colors focus:ring-1";
  const inputStyle = { background: 'var(--bg2)', border: '1.5px solid var(--bd)', color: 'var(--t1)' };
  const labelCls = "block";
  const labelStyle = {};
  const hintCls = "text-[.64rem] mt-0.5";
  const hintStyle = { color: 'var(--t4)' };

  return (
    <div className="page">

        {/* Header */}
        <div className="page-header">
          <div className="icon" style={{ background: 'var(--bll)' }}>
            <Database size={24} style={{ color: 'var(--bl)' }} />
          </div>
          <div>
            <h1>{t('adb.title')}</h1>
            <div className="subtitle">{t('adb.subtitle')}</div>
          </div>
          <div className="spacer" />
          <span className="count">
            {configs.length} {configs.length === 1 ? t('adb.connection') : t('adb.connections')}
          </span>
        </div>

        {/* Table */}
        <div className="card">
          <div className="card-header">
            <div className="icon" style={{ background: 'var(--bll)' }}>
              <Database size={16} style={{ color: 'var(--bl)' }} />
            </div>
            <h2>{t('adb.registered')}</h2>
          </div>

          {tableMsg && <div className="px-5 py-2"><Msg type={tableMsg.type} text={tableMsg.text} /></div>}

          {loading ? (
            <div className="flex items-center justify-center py-12">
              <Loader2 size={20} className="animate-spin" style={{ color: 'var(--t4)' }} />
            </div>
          ) : configs.length === 0 ? (
            <div className="py-10 text-center">
              <Database size={28} style={{ color: 'var(--t4)', margin: '0 auto 8px' }} />
              <p className="text-xs" style={{ color: 'var(--t4)' }}>{t('adb.noConnections')}</p>
            </div>
          ) : (
            <div className="overflow-x-auto">
              <table className="data-table">
                <thead>
                  <tr>
                    {['Nome', 'DSN', 'User', 'Tabelas', 'mTLS', 'Wallet', 'Embed', 'Acoes'].map((h) => (
                      <th key={h}>{h}</th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  {configs.map((c) => {
                    const tables = c.tables || [];
                    const emb = c.embedding_model_id ? embModels[c.embedding_model_id] : null;
                    const isExpanded = expandedTables[c.id];
                    return (
                      <tr
                        key={c.id}
                        className="transition-colors align-top"
                        style={{
                          borderBottom: '1px solid var(--bd)',
                          background: editing?.id === c.id ? 'color-mix(in srgb, var(--bl) 5%, var(--bg1))' : undefined,
                        }}
                        onMouseEnter={(e) => { if (editing?.id !== c.id) e.currentTarget.style.background = 'var(--bg2)'; }}
                        onMouseLeave={(e) => { if (editing?.id !== c.id) e.currentTarget.style.background = ''; }}
                      >
                        <td className="px-4 py-3">
                          <strong className="text-xs" style={{ color: 'var(--t1)' }}>{c.config_name}</strong>
                        </td>
                        <td className="px-4 py-3">
                          <code className="text-[.68rem]" style={{ fontFamily: 'var(--fm)', color: 'var(--t4)' }}>{c.dsn}</code>
                        </td>
                        <td className="px-4 py-3">
                          <span className="text-[.72rem]" style={{ color: 'var(--t2)' }}>{c.username}</span>
                        </td>
                        <td className="px-4 py-3">
                          {tables.length > 0 ? (
                            <div className="flex items-center gap-1 flex-wrap">
                              <button
                                onClick={() => setExpandedTables((p) => ({ ...p, [c.id]: !p[c.id] }))}
                                className="flex items-center gap-1 text-[.62rem] font-semibold px-1.5 py-0.5 rounded"
                                style={{ background: 'var(--bg)', color: 'var(--t3)' }}
                              >
                                <Table2 size={10} /> {tables.length}
                                {isExpanded ? <ChevronUp size={8} /> : <ChevronDown size={8} />}
                              </button>
                              {!isExpanded && tables.slice(0, 3).map((tb) => (
                                <span key={tb.id} className="px-1.5 py-0.5 rounded text-[.58rem]" style={{ background: 'var(--bg)', color: 'var(--t4)' }}>{tb.table_name}</span>
                              ))}
                              {!isExpanded && tables.length > 3 && (
                                <span className="text-[.58rem]" style={{ color: 'var(--t4)' }}>+{tables.length - 3}</span>
                              )}
                            </div>
                          ) : (
                            <span className="text-[.72rem]" style={{ color: 'var(--t4)' }}>{'\u2014'}</span>
                          )}
                          {isExpanded && tables.length > 0 && (
                            <div className="mt-2">
                              <table className="w-full text-[.68rem]" style={{ borderCollapse: 'collapse' }}>
                                <thead>
                                  <tr>
                                    {['Tabela', 'Descrição', 'Ativa', 'Ações'].map((h) => (
                                      <th key={h} className="text-left px-2 py-1 text-[.6rem] font-semibold uppercase" style={{ color: 'var(--t4)', borderBottom: '1px solid var(--bd)' }}>{h}</th>
                                    ))}
                                  </tr>
                                </thead>
                                <tbody>
                                  {tables.map((tb) => (
                                    <tr key={tb.id} style={{ opacity: tb.is_active ? 1 : 0.55 }}>
                                      <td className="px-2 py-1.5">
                                        <span className="font-mono text-[.68rem]" style={{ color: 'var(--t1)' }}>{tb.table_name}</span>
                                      </td>
                                      <td className="px-2 py-1.5">
                                        <span className="text-[.66rem]" style={{ color: 'var(--t3)' }}>{tb.description || '—'}</span>
                                      </td>
                                      <td className="px-2 py-1.5">
                                        <button onClick={() => handleToggleTable(c.id, tb.id, tb.is_active)} className="text-[.6rem] px-1.5 py-0.5 rounded font-medium" style={{ background: tb.is_active ? 'var(--gnl)' : 'var(--bg)', color: tb.is_active ? 'var(--gn)' : 'var(--t4)' }}>
                                          {tb.is_active ? t('adb.yes') : t('adb.no')}
                                        </button>
                                      </td>
                                      <td className="px-2 py-1.5">
                                        <button onClick={() => handleRemoveTable(c.id, tb.id)} className="text-[.58rem] px-1.5 py-0.5 rounded" style={{ color: 'var(--rd)', background: 'var(--rdl)' }}>
                                          {t('adb.delete')}
                                        </button>
                                      </td>
                                    </tr>
                                  ))}
                                </tbody>
                              </table>
                              {/* Add table inline */}
                              {editing?.id === c.id && (
                                <div className="flex gap-1 items-end mt-1">
                                  <input type="text" value={newTableName} onChange={(e) => setNewTableName(e.target.value)} placeholder="Nome" className="px-2 py-1 rounded text-[.64rem] w-28" style={{ background: 'var(--bg)', border: '1px solid var(--bd)', color: 'var(--t1)' }} />
                                  <input type="text" value={newTableDesc} onChange={(e) => setNewTableDesc(e.target.value)} placeholder="Descricao" className="px-2 py-1 rounded text-[.64rem] w-32" style={{ background: 'var(--bg)', border: '1px solid var(--bd)', color: 'var(--t1)' }} />
                                  <button onClick={() => handleAddTable(c.id)} className="px-2 py-1 rounded text-[.62rem] font-semibold" style={{ background: 'var(--bl)', color: '#fff' }}>
                                    <Plus size={10} />
                                  </button>
                                </div>
                              )}
                            </div>
                          )}
                        </td>
                        <td className="px-4 py-3">
                          {c.use_mtls ? (
                            <Shield size={14} style={{ color: 'var(--gn)' }} />
                          ) : (
                            <span style={{ color: 'var(--t4)' }}>{'\u2014'}</span>
                          )}
                        </td>
                        <td className="px-4 py-3">
                          {c.wallet_dir ? (
                            <Check size={14} style={{ color: 'var(--gn)' }} />
                          ) : (
                            <X size={14} style={{ color: 'var(--rd)' }} />
                          )}
                        </td>
                        <td className="px-4 py-3">
                          {c.genai_config_id ? (
                            <span className="px-1.5 py-0.5 rounded text-[.6rem] font-semibold" style={{ background: 'var(--gnl)', color: 'var(--gn)' }}>
                              {emb?.name || c.embedding_model_id}
                            </span>
                          ) : (
                            <span style={{ color: 'var(--t4)' }}>{'\u2014'}</span>
                          )}
                        </td>
                        <td className="px-4 py-3">
                          <div className="flex flex-col gap-1.5">
                            <div className="flex gap-1.5 flex-wrap">
                              <button onClick={() => startEdit(c)} className="btn btn-secondary btn-sm">
                                <Pencil size={10} /> {t('adb.edit')}
                              </button>
                              <button onClick={() => handleTest(c.id)} disabled={testingMap[c.id]} className="btn btn-secondary btn-sm">
                                {testingMap[c.id] ? <Loader2 size={10} className="animate-spin" /> : <FlaskConical size={10} />} {t('adb.test')}
                              </button>
                              {confirmDelete === c.id ? (
                                <div className="flex gap-1">
                                  <button onClick={() => handleDelete(c.id)} className="btn btn-sm" style={{ background: 'var(--rd)', color: '#fff' }}>
                                    <Check size={10} /> {t('adb.yes')}
                                  </button>
                                  <button onClick={() => setConfirmDelete(null)} className="btn btn-secondary btn-sm">
                                    {t('adb.no')}
                                  </button>
                                </div>
                              ) : (
                                <button onClick={() => setConfirmDelete(c.id)} className="btn btn-danger btn-sm">
                                  <Trash2 size={10} /> {t('adb.delete')}
                                </button>
                              )}
                            </div>
                            {testResults[c.id] && (
                              <div className="flex items-center gap-1.5 px-2 py-1 rounded text-[.62rem] font-medium"
                                style={{
                                  background: testResults[c.id].type === 's' ? 'var(--gnl)' : 'var(--rdl)',
                                  color: testResults[c.id].type === 's' ? 'var(--gn)' : 'var(--rd)',
                                }}>
                                {testResults[c.id].type === 's' ? <Check size={10} /> : <X size={10} />}
                                {testResults[c.id].text}
                              </div>
                            )}
                          </div>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          )}
        </div>

        {/* Form */}
        <div ref={formRef} className="card" style={{ overflow: 'hidden' }}>
          <div className="flex items-center gap-2.5 px-5 py-3.5 cursor-pointer select-none" onClick={() => { if (!editing) setFormOpen(!formOpen); }}>
            <ChevronRight size={14} style={{ color: 'var(--t3)', transition: 'transform .2s', transform: isFormVisible ? 'rotate(90deg)' : 'rotate(0)' }} />
            <div className="flex items-center gap-2">
              {editing ? <Pencil size={14} style={{ color: 'var(--bl)' }} /> : <Plus size={14} style={{ color: 'var(--bl)' }} />}
              <span className="text-[.76rem] font-semibold" style={{ color: 'var(--t2)' }}>
                {editing ? `${t('adb.editConnection')} — ${editing.config_name}` : t('adb.newConnection')}
              </span>
            </div>
          </div>

          {isFormVisible && (
            <div className="px-5 pb-5 flex flex-col gap-4" style={{ borderTop: '1px solid var(--bd)' }}>
              <p className="text-[.7rem] pt-3" style={{ color: 'var(--t4)' }}>
                {editing
                  ? <>Editando: <strong style={{ color: 'var(--t2)' }}>{editing.config_name}</strong></>
                  : <>{t('adb.connDesc')}</>}
              </p>

              {formMsg && <Msg type={formMsg.type} text={formMsg.text} />}

              {/* Row 1 */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className={labelCls} style={labelStyle}>{t('adb.connName')}</label>
                  <input type="text" value={cfgName} onChange={(e) => setCfgName(e.target.value)} placeholder="Producao ADB" className={inputCls} style={inputStyle} />
                </div>
                <div>
                  <label className={labelCls} style={labelStyle}>{t('adb.walletZip')}</label>
                  <p className={hintCls} style={{ ...hintStyle, marginBottom: 4 }}>
                    {editing ? t('adb.walletEditHint') : t('adb.walletHint')}
                  </p>
                  <div className="flex gap-1.5 items-center">
                    <input
                      ref={walletRef}
                      type="file"
                      accept=".zip"
                      className="flex-1 text-[.72rem] file:mr-2 file:px-3 file:py-1.5 file:rounded-lg file:border-0 file:text-[.68rem] file:font-semibold file:cursor-pointer"
                      style={{ color: 'var(--t3)' }}
                    />
                    <button
                      onClick={parseWallet}
                      disabled={parsingWallet}
                      className="flex items-center gap-1 px-3 py-1.5 rounded-lg text-[.68rem] font-semibold disabled:opacity-50"
                      style={{ background: 'var(--bg2)', color: 'var(--t2)', border: '1px solid var(--bd)' }}
                    >
                      {parsingWallet ? <Loader2 size={12} className="animate-spin" /> : <Search size={12} />}
                      {t('adb.analyze')}
                    </button>
                  </div>
                </div>
              </div>

              {/* Row 2 */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className={labelCls} style={labelStyle}>{t('adb.dsn')}</label>
                  <p className={hintCls} style={{ ...hintStyle, marginBottom: 4 }}>{t('adb.dsnHint')}</p>
                  {dsnOptions.length > 0 ? (
                    <select value={dsn} onChange={(e) => setDsn(e.target.value)} className={inputCls} style={inputStyle}>
                      {dsnOptions.map((d) => (
                        <option key={d} value={d}>{d}</option>
                      ))}
                    </select>
                  ) : (
                    <input type="text" value={dsn} onChange={(e) => setDsn(e.target.value)} placeholder="myatp_high" className={inputCls} style={inputStyle} />
                  )}
                </div>
                <div>
                  <label className={labelCls} style={labelStyle}>{t('adb.username')}</label>
                  <input type="text" value={username} onChange={(e) => setUsername(e.target.value)} placeholder="ADMIN" className={inputCls} style={inputStyle} />
                </div>
              </div>

              {/* Row 3 */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className={labelCls} style={labelStyle}>{t('adb.password')}</label>
                  <input type="password" value={password} onChange={(e) => setPassword(e.target.value)} placeholder={editing ? '(manter atual)' : ''} className={inputCls} style={inputStyle} />
                </div>
                <div>
                  <label className={labelCls} style={labelStyle}>{t('adb.walletPassword')}</label>
                  <input type="password" value={walletPassword} onChange={(e) => setWalletPassword(e.target.value)} placeholder="(opcional)" className={inputCls} style={inputStyle} />
                </div>
              </div>

              {/* Row 4 - Embedding config */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className={labelCls} style={labelStyle}>{t('adb.genaiConfig')}</label>
                  <p className={hintCls} style={{ ...hintStyle, marginBottom: 4 }}>{t('adb.genaiConfigHint')}</p>
                  <select value={genaiConfigId} onChange={(e) => setGenaiConfigId(e.target.value)} className={inputCls} style={inputStyle}>
                    <option value="">{t('adb.noRag')}</option>
                    {genaiCfg.map((g) => (
                      <option key={g.id} value={g.id}>{g.name || g.model_id} {g.genai_region ? `- ${g.genai_region}` : ''}</option>
                    ))}
                  </select>
                </div>
                <div>
                  <label className={labelCls} style={labelStyle}>{t('adb.embeddingModel')}</label>
                  <p className={hintCls} style={{ ...hintStyle, marginBottom: 4 }}>{t('adb.embeddingModelHint')}</p>
                  <select value={embeddingModelId} onChange={(e) => setEmbeddingModelId(e.target.value)} className={inputCls} style={inputStyle}>
                    {Object.entries(embModels).map(([k, v]) => (
                      <option key={k} value={k}>{v.name} ({v.dims}d)</option>
                    ))}
                    {Object.keys(embModels).length === 0 && (
                      <option value="cohere.embed-v4.0">cohere.embed-v4.0</option>
                    )}
                  </select>
                </div>
              </div>

              {/* Buttons */}
              <div className="flex gap-2 pt-1">
                <button onClick={handleSave} disabled={saving} className="btn btn-primary" style={{ background: 'var(--bl)', borderColor: 'var(--bl)' }}>
                  {saving && <Loader2 size={14} className="animate-spin" />}
                  {editing ? t('adb.saveChanges') : t('adb.saveConnection')}
                </button>
                {editing && (
                  <button onClick={resetForm} className="btn btn-secondary">
                    {t('adb.cancel')}
                  </button>
                )}
              </div>
            </div>
          )}
        </div>

        {/* Wallet Upload card */}
        {configs.length > 0 && (
          <div className="card">
            <div className="card-header">
              <div className="icon" style={{ background: 'var(--bll)' }}>
                <Upload size={16} style={{ color: 'var(--bl)' }} />
              </div>
              <h2>{t('adb.updateWallet')}</h2>
            </div>
            <div className="px-5 py-4 flex flex-col gap-3">
              {walletMsg && <Msg type={walletMsg.type} text={walletMsg.text} />}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className={labelCls} style={labelStyle}>{t('adb.adbConnection')}</label>
                  <select value={walletUploadId} onChange={(e) => setWalletUploadId(e.target.value)} className={inputCls} style={inputStyle}>
                    <option value="">{t('common.select')}</option>
                    {configs.map((c) => (
                      <option key={c.id} value={c.id}>{c.config_name}</option>
                    ))}
                  </select>
                </div>
                <div>
                  <label className={labelCls} style={labelStyle}>{t('adb.walletZip')}</label>
                  <input
                    ref={walletUploadRef}
                    type="file"
                    accept=".zip"
                    className="text-[.72rem] file:mr-2 file:px-3 file:py-1.5 file:rounded-lg file:border-0 file:text-[.68rem] file:font-semibold file:cursor-pointer"
                    style={{ color: 'var(--t3)' }}
                  />
                </div>
              </div>
              <div>
                <button
                  onClick={handleWalletUpload}
                  disabled={uploadingWallet}
                  className="btn btn-secondary btn-sm"
                >
                  {uploadingWallet ? <Loader2 size={12} className="animate-spin" /> : <Upload size={12} />}
                  {t('adb.uploadWallet')}
                </button>
              </div>
            </div>
          </div>
        )}

    </div>
  );
}
