import { useState, useEffect, useRef, useCallback } from 'react';
import { useAppStore } from '@/stores/app';
import { useI18n } from '@/i18n';
import { ociApi, type OciConfigFull, type OciTestResult } from '@/api/endpoints/oci';
import {
  Cloud, ChevronRight, Key, Lock, Plus, Pencil,
  Trash2, FlaskConical, Building2, User, Package,
  Check, X, Loader2, Search,
} from 'lucide-react';

/* ── Static fallback OCI regions ── */
const FALLBACK_REGIONS: Record<string, string[]> = {
  'Americas': [
    'us-ashburn-1', 'us-phoenix-1', 'us-sanjose-1', 'us-chicago-1',
    'ca-toronto-1', 'ca-montreal-1', 'sa-saopaulo-1', 'sa-vinhedo-1',
    'sa-santiago-1', 'sa-bogota-1', 'mx-queretaro-1', 'mx-monterrey-1',
  ],
  'Europe': [
    'eu-frankfurt-1', 'eu-amsterdam-1', 'eu-zurich-1', 'eu-madrid-1',
    'eu-marseille-1', 'eu-milan-1', 'eu-stockholm-1', 'eu-paris-1',
    'uk-london-1', 'uk-cardiff-1', 'eu-jovanovac-1', 'eu-dcc-milan-1',
  ],
  'Asia Pacific': [
    'ap-tokyo-1', 'ap-osaka-1', 'ap-seoul-1', 'ap-sydney-1',
    'ap-melbourne-1', 'ap-mumbai-1', 'ap-hyderabad-1', 'ap-singapore-1',
    'ap-chuncheon-1', 'ap-singapore-2',
  ],
  'Middle East & Africa': [
    'me-jeddah-1', 'me-dubai-1', 'me-abudhabi-1',
    'af-johannesburg-1', 'il-jerusalem-1',
  ],
};

type AuthType = 'api_key' | 'session_token';

/* ── Msg component ── */
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>{text}</span>
    </div>
  );
}

/* ── Region Dropdown ── */
function RegionDropdown({
  value, onChange, regionsMap, t,
}: { value: string; onChange: (r: string) => void; regionsMap: Record<string, string[]>; t: (key: string) => string }) {
  const [open, setOpen] = useState(false);
  const [filter, setFilter] = useState('');
  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const handler = (e: MouseEvent) => {
      if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
    };
    document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, []);

  const f = filter.toLowerCase();

  return (
    <div ref={ref} className="relative">
      <div
        onClick={() => setOpen(!open)}
        className="flex items-center justify-between cursor-pointer px-3 py-2 rounded-lg text-[.78rem]"
        style={{ background: 'var(--bg2)', border: '1.5px solid var(--bd)', minHeight: 36 }}
      >
        <span style={{ color: value ? 'var(--t1)' : 'var(--t4)' }}>
          {value || t('oci.selectRegion')}
        </span>
        <span className="text-[.6rem]" style={{ color: 'var(--t4)' }}>&#9660;</span>
      </div>

      {open && (
        <div
          className="absolute top-full left-0 right-0 rounded-lg overflow-hidden z-50"
          style={{ background: 'var(--bg)', border: '1px solid var(--bd)', boxShadow: '0 4px 16px rgba(0,0,0,.25)', maxHeight: 280 }}
        >
          <div className="p-1.5" style={{ borderBottom: '1px solid var(--bd)' }}>
            <div className="flex items-center gap-1.5 px-2" style={{ background: 'var(--bg2)', borderRadius: 6 }}>
              <Search size={12} style={{ color: 'var(--t4)' }} />
              <input
                type="text"
                placeholder={t('oci.searchRegion')}
                value={filter}
                onChange={(e) => setFilter(e.target.value)}
                onClick={(e) => e.stopPropagation()}
                className="w-full border-none outline-none text-xs py-1.5"
                style={{ background: 'transparent', color: 'var(--t1)' }}
                autoFocus
              />
            </div>
          </div>
          <div className="overflow-y-auto" style={{ maxHeight: 230 }}>
            {Object.entries(regionsMap).map(([grp, regs]) => {
              const filtered = regs.filter((r) => !f || r.includes(f));
              if (!filtered.length) return null;
              return (
                <div key={grp}>
                  <div
                    className="px-3 py-1 text-[.62rem] font-semibold uppercase tracking-wider"
                    style={{ color: 'var(--t4)', background: 'var(--bg1)' }}
                  >
                    {grp}
                  </div>
                  {filtered.map((r) => (
                    <div
                      key={r}
                      onClick={() => { onChange(r); setOpen(false); setFilter(''); }}
                      className="px-3 py-1.5 text-xs cursor-pointer transition-colors"
                      style={{
                        color: value === r ? 'var(--ac)' : 'var(--t2)',
                        background: value === r ? 'color-mix(in srgb, var(--ac) 8%, transparent)' : undefined,
                      }}
                      onMouseEnter={(e) => { if (value !== r) (e.target as HTMLDivElement).style.background = 'var(--bg2)'; }}
                      onMouseLeave={(e) => { if (value !== r) (e.target as HTMLDivElement).style.background = ''; }}
                    >
                      {r}
                    </div>
                  ))}
                </div>
              );
            })}
            {Object.entries(regionsMap).every(([, regs]) => !regs.some((r) => !f || r.includes(f))) && (
              <div className="p-3 text-xs" style={{ color: 'var(--t4)' }}>{t('oci.noRegion')}</div>
            )}
          </div>
        </div>
      )}
    </div>
  );
}

/* ── Auth Type Tag ── */
function AuthTag({ type }: { type: string }) {
  const isToken = type === 'session_token';
  return (
    <span
      className="inline-flex items-center gap-1 px-2 py-0.5 rounded-md text-[.62rem] font-semibold"
      style={{
        background: isToken ? 'rgba(230,126,34,0.12)' : 'var(--gnl)',
        color: isToken ? '#e67e22' : 'var(--gn)',
      }}
    >
      {isToken ? <Lock size={10} /> : <Key size={10} />}
      {isToken ? 'Session Token' : 'API Key'}
    </span>
  );
}

/* ── Main Page ── */
export default function OciConfigPage() {
  const ociRegions = useAppStore((s) => s.ociRegions);
  const { t } = useI18n();

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

  // Form state
  const [formOpen, setFormOpen] = useState(false);
  const [editing, setEditing] = useState<OciConfigFull | null>(null);
  const [authType, setAuthType] = useState<AuthType>('api_key');
  const [region, setRegion] = useState('');
  const [saving, setSaving] = useState(false);
  const [formMsg, setFormMsg] = useState<{ type: 's' | 'e' | 'i'; text: string } | null>(null);

  // Table msg
  const [tableMsg, setTableMsg] = useState<{ type: 's' | 'e' | 'i'; text: string } | null>(null);

  // Test results per config
  const [testResults, setTestResults] = useState<Record<string, OciTestResult>>({});
  const [testing, setTesting] = useState<Record<string, boolean>>({});

  // Delete confirm
  const [confirmDelete, setConfirmDelete] = useState<string | null>(null);

  // Form refs
  const formRef = useRef<HTMLDivElement>(null);
  const tnRef = useRef<HTMLInputElement>(null);
  const toRef = useRef<HTMLInputElement>(null);
  const uoRef = useRef<HTMLInputElement>(null);
  const fpRef = useRef<HTMLInputElement>(null);
  const cpRef = useRef<HTMLInputElement>(null);
  const kpRef = useRef<HTMLInputElement>(null);
  const skRef = useRef<HTMLInputElement>(null);
  const pkRef = useRef<HTMLInputElement>(null);
  const stkRef = useRef<HTMLTextAreaElement>(null);
  const sshRef = useRef<HTMLTextAreaElement>(null);

  // Build regions map
  const regionsMap: Record<string, string[]> = (() => {
    if (ociRegions && typeof ociRegions === 'object') {
      const entries = Object.entries(ociRegions);
      if (entries.length > 0) {
        // ociRegions can be { group: string[] } or { group: string }
        // From the store it's Record<string,string>, but the backend returns Record<string,string[]>
        const first = entries[0][1];
        if (Array.isArray(first)) return ociRegions as unknown as Record<string, string[]>;
        // If it's flat, return as single-group
        const flat = entries.map(([, v]) => v as unknown as string);
        if (flat.length > 0) return { 'Regioes': flat };
      }
    }
    return FALLBACK_REGIONS;
  })();

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

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

  const resetForm = () => {
    setEditing(null);
    setFormOpen(false);
    setAuthType('api_key');
    setRegion('');
    setFormMsg(null);
    setSaving(false);
    // Clear file inputs
    if (skRef.current) skRef.current.value = '';
    if (pkRef.current) pkRef.current.value = '';
  };

  const startEdit = (cfg: OciConfigFull) => {
    setEditing(cfg);
    setAuthType(cfg.auth_type || 'api_key');
    setRegion(cfg.region);
    setFormOpen(true);
    setFormMsg(null);
    setTimeout(() => formRef.current?.scrollIntoView({ behavior: 'smooth', block: 'start' }), 100);
  };

  const handleSave = async () => {
    const tenancyName = tnRef.current?.value?.trim() || '';
    if (!tenancyName) { setFormMsg({ type: 'e', text: `${t('oci.fillField')} Tenancy Name` }); return; }

    const isEdit = !!editing;
    const at = isEdit ? (editing!.auth_type || 'api_key') : authType;
    const isToken = at === 'session_token';

    const tenancyOcid = toRef.current?.value?.trim() || '';
    const userOcid = uoRef.current?.value?.trim() || '';
    const fingerprint = fpRef.current?.value?.trim() || '';
    const compartmentId = cpRef.current?.value?.trim() || '';
    const keyPassphrase = kpRef.current?.value?.trim() || '';
    const securityToken = stkRef.current?.value?.trim() || '';
    const sshPubKey = sshRef.current?.value?.trim() || '';
    const privateKeyFile = skRef.current?.files?.[0];
    const publicKeyFile = pkRef.current?.files?.[0];

    // Validations for new config
    if (!isEdit) {
      if (!tenancyOcid) { setFormMsg({ type: 'e', text: t('oci.fillOcidTenancy') }); return; }
      if (!isToken && (!userOcid || !fingerprint)) { setFormMsg({ type: 'e', text: t('oci.fillUserAndFP') }); return; }
      if (isToken && !securityToken) { setFormMsg({ type: 'e', text: t('oci.pasteToken') }); return; }
      if (!privateKeyFile) { setFormMsg({ type: 'e', text: isToken ? t('oci.selectSessionKey') : t('oci.selectKey') }); return; }
    }

    const fd = new FormData();
    fd.append('tenancy_name', tenancyName);
    fd.append('tenancy_ocid', tenancyOcid);
    fd.append('user_ocid', userOcid);
    fd.append('fingerprint', fingerprint);
    fd.append('region', region);
    fd.append('compartment_id', compartmentId);
    fd.append('key_passphrase', keyPassphrase);
    fd.append('ssh_public_key', sshPubKey);
    fd.append('auth_type', at);
    fd.append('security_token', securityToken);
    if (privateKeyFile) fd.append('private_key', privateKeyFile);
    if (publicKeyFile) fd.append('public_key', publicKeyFile);

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

    try {
      if (isEdit) {
        await ociApi.update(editing!.id, fd);
      } else {
        await ociApi.create(fd);
      }
      setFormMsg({ type: 's', text: isEdit ? t('oci.updated') : t('oci.saved') });
      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('oci.deleting') });
    try {
      await ociApi.remove(id);
      await fetchConfigs();
      useAppStore.getState().loadData();
      setTableMsg({ type: 's', text: t('oci.deleted') });
      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) => {
    setTesting((p) => ({ ...p, [id]: true }));
    setTestResults((p) => { const n = { ...p }; delete n[id]; return n; });
    try {
      const res = await ociApi.test(id);
      setTestResults((p) => ({ ...p, [id]: res }));
    } catch (err) {
      setTestResults((p) => ({ ...p, [id]: { status: 'error', message: err instanceof Error ? err.message : 'Erro' } }));
    } finally {
      setTesting((p) => ({ ...p, [id]: false }));
    }
  };

  const isFormVisible = formOpen || !!editing;
  const currentAuthType = editing ? (editing.auth_type || 'api_key') : authType;
  const isToken = currentAuthType === 'session_token';

  /* ── Input helper ── */
  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(--acl)' }}>
            <Cloud size={24} style={{ color: 'var(--ac)' }} />
          </div>
          <div>
            <h1>{t('oci.title')}</h1>
            <div className="subtitle">{t('oci.subtitle')}</div>
          </div>
          <div className="spacer" />
          <span className="count">
            {configs.length} {configs.length === 1 ? t('oci.credential') : t('oci.credentials')}
          </span>
        </div>

        {/* ── Table ── */}
        <div className="card">
          <div className="card-header">
            <div className="icon" style={{ background: 'var(--acl)' }}>
              <Cloud size={16} style={{ color: 'var(--ac)' }} />
            </div>
            <h2>{t('oci.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">
              <Cloud size={28} style={{ color: 'var(--t4)', margin: '0 auto 8px' }} />
              <p className="text-xs" style={{ color: 'var(--t4)' }}>{t('oci.noCredentials')}</p>
            </div>
          ) : (
            <div className="overflow-x-auto">
              <table className="data-table">
                <thead>
                  <tr>
                    {['Tenancy', 'Tipo', 'Region', 'Detalhes', 'Acoes'].map((h) => (
                      <th key={h}>{h}</th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  {configs.map((c) => (
                    <tr
                      key={c.id}
                      className="transition-colors"
                      style={{
                        borderBottom: '1px solid var(--bd)',
                        background: editing?.id === c.id ? 'color-mix(in srgb, var(--ac) 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 = ''); }}
                    >
                      {/* Tenancy */}
                      <td className="px-4 py-3">
                        <div className="text-xs font-semibold" style={{ color: 'var(--t1)' }}>{c.tenancy_name}</div>
                        <div className="text-[.6rem] mt-0.5" style={{ color: 'var(--t4)' }}>{c.created_at}</div>
                      </td>
                      {/* Auth Type */}
                      <td className="px-4 py-3"><AuthTag type={c.auth_type} /></td>
                      {/* Region */}
                      <td className="px-4 py-3">
                        <span className="px-2 py-0.5 rounded text-[.64rem] font-medium" style={{ background: 'var(--bg2)', color: 'var(--t2)' }}>
                          {c.region}
                        </span>
                      </td>
                      {/* Details */}
                      <td className="px-4 py-3">
                        <div className="flex flex-col gap-0.5 text-[.62rem] leading-relaxed" style={{ color: 'var(--t4)', fontFamily: 'var(--fm)' }}>
                          {(c.auth_type || 'api_key') === 'session_token' ? (
                            <>
                              <span className="flex items-center gap-1" title="Tenancy OCID"><Building2 size={10} /> {c.tenancy_ocid}</span>
                              <span className="flex items-center gap-1" title="Auth"><Lock size={10} /> Session Token</span>
                            </>
                          ) : (
                            <>
                              <span className="flex items-center gap-1" title="Fingerprint"><Key size={10} /> {'*'.repeat(20)}</span>
                              <span className="flex items-center gap-1" title="Tenancy OCID"><Building2 size={10} /> {c.tenancy_ocid}</span>
                              <span className="flex items-center gap-1" title="User OCID"><User size={10} /> {c.user_ocid}</span>
                            </>
                          )}
                          <span className="flex items-center gap-1" title="Compartment"><Package size={10} /> {c.compartment_id || '\u2014'}</span>
                          <span className="flex items-center gap-1" title="SSH Public Key"><Key size={10} /> SSH: {c.ssh_public_key_preview || <em>{t('oci.sshNotConfigured')}</em>}</span>
                        </div>
                      </td>
                      {/* Actions */}
                      <td className="px-4 py-3">
                        <div className="flex flex-col gap-1.5">
                          <div className="flex gap-1.5">
                            <button
                              onClick={() => startEdit(c)}
                              className="btn btn-secondary btn-sm"
                            >
                              <Pencil size={10} /> {t('oci.edit')}
                            </button>
                            <button
                              onClick={() => handleTest(c.id)}
                              disabled={testing[c.id]}
                              className="btn btn-secondary btn-sm"
                            >
                              {testing[c.id] ? <Loader2 size={10} className="animate-spin" /> : <FlaskConical size={10} />} {t('oci.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('oci.yes')}
                                </button>
                                <button
                                  onClick={() => setConfirmDelete(null)}
                                  className="btn btn-secondary btn-sm"
                                >
                                  {t('oci.no')}
                                </button>
                              </div>
                            ) : (
                              <button
                                onClick={() => setConfirmDelete(c.id)}
                                className="btn btn-danger btn-sm"
                              >
                                <Trash2 size={10} /> {t('oci.delete')}
                              </button>
                            )}
                          </div>
                          {/* Test result inline */}
                          {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].status === 'success' ? 'var(--gnl)' : 'var(--rdl)',
                                color: testResults[c.id].status === 'success' ? 'var(--gn)' : 'var(--rd)',
                              }}
                            >
                              {testResults[c.id].status === 'success' ? <Check size={10} /> : <X size={10} />}
                              {testResults[c.id].message}
                            </div>
                          )}
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>

        {/* ── Form Card ── */}
        <div ref={formRef} className="card" style={{ overflow: 'hidden' }}>
          {/* Collapsible header */}
          <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(--ac)' }} /> : <Plus size={14} style={{ color: 'var(--ac)' }} />}
              <span className="text-[.76rem] font-semibold" style={{ color: 'var(--t2)' }}>
                {editing ? t('oci.editCredential') : t('oci.newCredential')}
              </span>
            </div>
          </div>

          {isFormVisible && (
            <div className="px-5 pb-5 flex flex-col gap-4" style={{ borderTop: '1px solid var(--bd)' }}>

              {/* Description */}
              <p className="text-[.7rem] pt-3" style={{ color: 'var(--t4)' }}>
                {editing
                  ? <>{t('oci.editing')} <strong style={{ color: 'var(--t2)' }}>{editing.tenancy_name}</strong></>
                  : t('oci.addDesc')}
              </p>

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

              {/* Auth type toggle */}
              <div className="flex items-center gap-2">
                <button
                  onClick={() => { if (!editing) setAuthType('api_key'); }}
                  disabled={!!editing}
                  className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-[.72rem] font-semibold transition-all disabled:opacity-70"
                  style={{
                    background: !isToken ? 'color-mix(in srgb, var(--ac) 15%, transparent)' : 'var(--bg2)',
                    color: !isToken ? 'var(--ac)' : 'var(--t4)',
                    border: `1.5px solid ${!isToken ? 'var(--ac)' : 'var(--bd)'}`,
                  }}
                >
                  <Key size={12} /> API Key
                </button>
                <button
                  onClick={() => { if (!editing) setAuthType('session_token'); }}
                  disabled={!!editing}
                  className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-[.72rem] font-semibold transition-all disabled:opacity-70"
                  style={{
                    background: isToken ? 'color-mix(in srgb, #e67e22 15%, transparent)' : 'var(--bg2)',
                    color: isToken ? '#e67e22' : 'var(--t4)',
                    border: `1.5px solid ${isToken ? '#e67e22' : 'var(--bd)'}`,
                  }}
                >
                  <Lock size={12} /> Session Token
                </button>
                {editing && (
                  <span className="text-[.6rem]" style={{ color: 'var(--t4)' }}>{t('oci.typeCannotChange')}</span>
                )}
              </div>

              {/* Row 1: Tenancy Name + OCID Tenancy */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className={labelCls} style={labelStyle}>{t('oci.tenancyName')}</label>
                  <input
                    ref={tnRef}
                    type="text"
                    placeholder="minha-empresa"
                    defaultValue={editing?.tenancy_name || ''}
                    className={inputCls}
                    style={inputStyle}
                  />
                </div>
                <div>
                  <label className={labelCls} style={labelStyle}>{t('oci.ocidTenancy')}</label>
                  <input
                    ref={toRef}
                    type="password"
                    placeholder="ocid1.tenancy.oc1.."
                    autoComplete="off"
                    className={inputCls}
                    style={inputStyle}
                  />
                  {editing && (
                    <p className={hintCls} style={hintStyle}>{t('oci.changeHint')} <code style={{ color: 'var(--t3)' }}>{editing.tenancy_ocid}</code></p>
                  )}
                </div>
              </div>

              {/* Row 2: Region + Compartment */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className={labelCls} style={labelStyle}>{t('oci.region')}</label>
                  <RegionDropdown value={region} onChange={setRegion} regionsMap={regionsMap} t={t} />
                </div>
                <div>
                  <label className={labelCls} style={labelStyle}>{t('oci.compartment')}</label>
                  <input
                    ref={cpRef}
                    type="password"
                    placeholder="ocid1.compartment.oc1.."
                    autoComplete="off"
                    className={inputCls}
                    style={inputStyle}
                  />
                  {editing && (
                    <p className={hintCls} style={hintStyle}>{t('oci.changeHint')} <code style={{ color: 'var(--t3)' }}>{editing.compartment_id || '\u2014'}</code></p>
                  )}
                </div>
              </div>

              {/* API Key fields: User OCID + Fingerprint */}
              {!isToken && (
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div>
                    <label className={labelCls} style={labelStyle}>{t('oci.ocidUser')}</label>
                    <input
                      ref={uoRef}
                      type="password"
                      placeholder="ocid1.user.oc1.."
                      autoComplete="off"
                      className={inputCls}
                      style={inputStyle}
                    />
                    {editing && (
                      <p className={hintCls} style={hintStyle}>{t('oci.changeHint')} <code style={{ color: 'var(--t3)' }}>{editing.user_ocid}</code></p>
                    )}
                  </div>
                  <div>
                    <label className={labelCls} style={labelStyle}>{t('oci.fingerprint')}</label>
                    <input
                      ref={fpRef}
                      type="password"
                      placeholder="aa:bb:cc:dd:..."
                      autoComplete="off"
                      className={inputCls}
                      style={inputStyle}
                    />
                    {editing && (
                      <p className={hintCls} style={hintStyle}>{t('oci.changeHint')} <code style={{ color: 'var(--t3)' }}>{editing.fingerprint}</code></p>
                    )}
                  </div>
                </div>
              )}

              {/* Session Token fields */}
              {isToken && (
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div>
                    <label className={labelCls} style={labelStyle}>{t('oci.sessionToken')}</label>
                    <p className={hintCls} style={{ ...hintStyle, marginBottom: 4 }}>
                      {t('oci.sessionTokenHint')} <code style={{ color: 'var(--t3)' }}>oci session authenticate</code>
                    </p>
                    <textarea
                      ref={stkRef}
                      rows={3}
                      placeholder="Conteudo do arquivo ~/.oci/sessions/DEFAULT/token"
                      className={inputCls}
                      style={{ ...inputStyle, resize: 'vertical', fontFamily: 'var(--fm)', fontSize: '.68rem' }}
                    />
                  </div>
                  <div>
                    <label className={labelCls} style={labelStyle}>
                      {t('oci.ocidUser')} <span style={{ fontSize: '.6rem', color: 'var(--t4)' }}>(opcional)</span>
                    </label>
                    <input
                      ref={uoRef}
                      type="password"
                      placeholder="ocid1.user.oc1.. (preenchido automaticamente)"
                      autoComplete="off"
                      className={inputCls}
                      style={inputStyle}
                    />
                    <p className={hintCls} style={hintStyle}>O SDK pode resolver o user a partir do token. Deixe vazio se preferir.</p>
                  </div>
                </div>
              )}

              {/* Keys row */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className={labelCls} style={labelStyle}>
                    {isToken ? t('oci.sessionKeyLabel') : t('oci.privateKey')}
                  </label>
                  {editing && <p className={hintCls} style={{ ...hintStyle, marginBottom: 4 }}>{t('oci.keepKey')}</p>}
                  <p className={hintCls} style={{ ...hintStyle, marginBottom: 4 }}>
                    {isToken
                      ? <span>Arquivo <code style={{ color: 'var(--t3)' }}>oci_api_key.pem</code> da pasta de sessao</span>
                      : 'Chave privada da API Key OCI'}
                  </p>
                  <input
                    ref={skRef}
                    type="file"
                    accept=".pem"
                    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>
                {!isToken ? (
                  <div>
                    <label className={labelCls} style={labelStyle}>{t('oci.publicKey')}</label>
                    <input
                      ref={pkRef}
                      type="file"
                      accept=".pem"
                      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>

              {/* Passphrase + SSH */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                {!isToken ? (
                  <div>
                    <label className={labelCls} style={labelStyle}>{t('oci.keyPassphrase')}</label>
                    <p className={hintCls} style={{ ...hintStyle, marginBottom: 4 }}>{t('oci.keyPassphraseHint')}</p>
                    <input
                      ref={kpRef}
                      type="password"
                      placeholder="(opcional)"
                      className={inputCls}
                      style={inputStyle}
                    />
                  </div>
                ) : <div />}
                <div>
                  <label className={labelCls} style={labelStyle}>{t('oci.sshPublicKey')}</label>
                  <p className={hintCls} style={{ ...hintStyle, marginBottom: 4 }}>{t('oci.sshPublicKeyHint')}</p>
                  <textarea
                    ref={sshRef}
                    rows={2}
                    placeholder="ssh-rsa AAAAB3NzaC1yc2E... (opcional)"
                    defaultValue={editing?.ssh_public_key || ''}
                    className={inputCls}
                    style={{ ...inputStyle, resize: 'vertical', fontFamily: 'var(--fm)', fontSize: '.72rem' }}
                  />
                  {editing?.ssh_public_key_preview && (
                    <p className={hintCls} style={hintStyle}>Atual: <code style={{ color: 'var(--t3)' }}>{editing.ssh_public_key_preview}</code></p>
                  )}
                </div>
              </div>

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

    </div>
  );
}
