import { useState, useEffect, useCallback, useRef } from 'react';
import { useAppStore } from '@/stores/app';
import { useI18n } from '@/i18n';
import { genaiApi, type GenAiConfigFull, type GenAiConfigPayload } from '@/api/endpoints/genai';
import {
  Brain, Plus, Pencil, Trash2, FlaskConical, Check, X, Loader2,
  ChevronRight, Star, Link as LinkIcon,
} 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 GenAiConfigPage() {
  const { ociCfg, models, regions } = useAppStore();
  const { t } = useI18n();

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

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

  // Form fields
  const [name, setName] = useState('');
  const [ociConfigId, setOciConfigId] = useState('');
  const [modelId, setModelId] = useState('openai.gpt-4.1');
  const [modelOcid, setModelOcid] = useState('');
  const [compartmentId, setCompartmentId] = useState('');
  const [genaiRegion, setGenaiRegion] = useState('us-ashburn-1');
  const [isDefault, setIsDefault] = 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 [testing, setTesting] = useState<Record<string, boolean>>({});
  const [confirmDelete, setConfirmDelete] = useState<string | null>(null);

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

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

  const resetForm = () => {
    setEditing(null);
    setFormOpen(false);
    setName('');
    setOciConfigId('');
    setModelId('openai.gpt-4.1');
    setModelOcid('');
    setCompartmentId('');
    setGenaiRegion('us-ashburn-1');
    setIsDefault(false);
    setFormMsg(null);
    setSaving(false);
  };

  const startEdit = (cfg: GenAiConfigFull) => {
    setEditing(cfg);
    setName(cfg.name || '');
    setOciConfigId(cfg.oci_config_id || '');
    setModelId(cfg.model_ocid ? '_custom' : (cfg.model_id || 'openai.gpt-4.1'));
    setModelOcid(cfg.model_ocid || '');
    setCompartmentId(cfg.compartment_id || '');
    setGenaiRegion(cfg.genai_region || 'us-ashburn-1');
    setIsDefault(!!cfg.is_default);
    setFormOpen(true);
    setFormMsg(null);
    setTimeout(() => formRef.current?.scrollIntoView({ behavior: 'smooth', block: 'start' }), 100);
  };

  const fillFromOci = (ociId: string) => {
    setOciConfigId(ociId);
    const cfg = ociCfg.find((c) => c.id === ociId);
    if (!cfg) return;
    setGenaiRegion(cfg.region);
    if (cfg.compartment_id) setCompartmentId(cfg.compartment_id);
    setFormMsg({ type: 'i', text: `Regiao e Compartment preenchidos de <strong>${cfg.tenancy_name}</strong>` });
    setTimeout(() => setFormMsg(null), 3000);
  };

  const handleSave = async () => {
    if (!name.trim()) { setFormMsg({ type: 'e', text: t('genai.fillName') }); return; }
    if (!ociConfigId) { setFormMsg({ type: 'e', text: t('genai.selectOci') }); return; }
    if (modelId === '_custom' && !modelOcid) { setFormMsg({ type: 'e', text: t('genai.fillOcid') }); return; }

    const body: GenAiConfigPayload = {
      name: name.trim(),
      oci_config_id: ociConfigId,
      model_id: modelId === '_custom' ? 'custom' : modelId,
      model_ocid: modelOcid || null,
      compartment_id: compartmentId,
      genai_region: genaiRegion,
      endpoint: null,
      serving_type: 'ON_DEMAND',
      dedicated_endpoint_id: null,
      is_default: editing ? !!editing.is_default : configs.length === 0,
    };
    if (isDefault) body.is_default = true;

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

    try {
      if (editing) {
        await genaiApi.update(editing.id, body);
      } else {
        await genaiApi.create(body);
      }
      setFormMsg({ type: 's', text: `Modelo ${editing ? 'atualizado' : 'salvo'} com sucesso!` });
      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('genai.deleting') });
    try {
      await genaiApi.remove(id);
      await fetchConfigs();
      useAppStore.getState().loadData();
      setTableMsg({ type: 's', text: 'Modelo excluido 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) => {
    setTesting((p) => ({ ...p, [id]: true }));
    setTestResults((p) => { const n = { ...p }; delete n[id]; return n; });
    try {
      const res = await genaiApi.test(id);
      setTestResults((p) => ({
        ...p,
        [id]: {
          type: res.status === 'success' ? 's' : 'e',
          text: res.message + (res.response ? ` — ${res.response}` : ''),
        },
      }));
    } catch (err) {
      setTestResults((p) => ({ ...p, [id]: { type: 'e', text: err instanceof Error ? err.message : 'Erro' } }));
    } finally {
      setTesting((p) => ({ ...p, [id]: false }));
    }
  };

  // Group models by provider
  const groupedModels = Object.entries(models).reduce<Record<string, { key: string; name: string }[]>>((acc, [key, m]) => {
    const provider = m.provider || 'Other';
    if (!acc[provider]) acc[provider] = [];
    acc[provider].push({ key, name: m.name });
    return acc;
  }, {});

  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(--ppl)' }}>
            <Brain size={24} style={{ color: 'var(--pp)' }} />
          </div>
          <div>
            <h1>{t('genai.title')}</h1>
            <div className="subtitle">{t('genai.subtitle')}</div>
          </div>
          <div className="spacer" />
          <span className="count">
            {configs.length} {configs.length === 1 ? t('genai.model') : t('genai.models')}
          </span>
        </div>

        {/* Table */}
        <div className="card">
          <div className="card-header">
            <div className="icon" style={{ background: 'var(--ppl)' }}>
              <Brain size={16} style={{ color: 'var(--pp)' }} />
            </div>
            <h2>{t('genai.configured')}</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">
              <Brain size={28} style={{ color: 'var(--t4)', margin: '0 auto 8px' }} />
              <p className="text-xs" style={{ color: 'var(--t4)' }}>{t('genai.noModels')}</p>
            </div>
          ) : (
            <div className="overflow-x-auto">
              <table className="data-table">
                <thead>
                  <tr>
                    {['Config', 'Modelo', 'OCI Config', 'Regiao', 'Acoes'].map((h) => (
                      <th key={h}>{h}</th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  {configs.map((c) => {
                    const mi = models[c.model_id];
                    const oci = ociCfg.find((o) => o.id === c.oci_config_id);
                    return (
                      <tr
                        key={c.id}
                        className="transition-colors"
                        style={{
                          borderBottom: '1px solid var(--bd)',
                          background: editing?.id === c.id ? 'color-mix(in srgb, var(--pp) 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">
                          <div className="flex items-center gap-2">
                            <span className="text-xs font-semibold" style={{ color: 'var(--t1)' }}>{c.name || '\u2014'}</span>
                            {c.is_default && (
                              <span className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[.58rem] font-semibold"
                                style={{ background: 'color-mix(in srgb, #f39c12 15%, transparent)', color: '#f39c12' }}>
                                <Star size={8} /> {t('genai.default')}
                              </span>
                            )}
                          </div>
                        </td>
                        <td className="px-4 py-3">
                          <div className="text-xs" style={{ color: 'var(--t1)' }}>
                            {mi?.name || (c.model_ocid ? 'OCID Personalizado' : c.model_id)}
                          </div>
                          <span className="inline-block mt-0.5 px-1.5 py-0.5 rounded text-[.58rem] font-semibold"
                            style={{ background: 'var(--bg2)', color: 'var(--t4)' }}>
                            {mi?.provider || (c.model_ocid ? 'custom' : '?')}
                          </span>
                        </td>
                        <td className="px-4 py-3">
                          <span className="text-[.7rem]" style={{ color: 'var(--t2)' }}>
                            {oci?.tenancy_name || '\u2014'}
                          </span>
                        </td>
                        <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)', fontFamily: 'var(--fm)' }}>
                            {c.genai_region}
                          </span>
                        </td>
                        <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('common.yes')}
                                  </button>
                                  <button onClick={() => setConfirmDelete(null)} className="btn btn-secondary btn-sm">
                                    {t('common.no')}
                                  </button>
                                </div>
                              ) : (
                                <button onClick={() => setConfirmDelete(c.id)} className="btn btn-danger btn-sm">
                                  <Trash2 size={10} /> {t('oci.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} />}
                                <span className="truncate max-w-xs">{testResults[c.id].text}</span>
                              </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(--pp)' }} /> : <Plus size={14} style={{ color: 'var(--pp)' }} />}
              <span className="text-[.76rem] font-semibold" style={{ color: 'var(--t2)' }}>
                {editing ? `${t('genai.editModel')} — ${editing.name}` : t('genai.newModel')}
              </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.name}</strong></>
                  : t('genai.addDesc')}
              </p>

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

              {/* Row 1 */}
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div>
                  <label className={labelCls} style={labelStyle}>{t('genai.configName')}</label>
                  <input type="text" value={name} onChange={(e) => setName(e.target.value)} placeholder="Meu Modelo Custom" className={inputCls} style={inputStyle} />
                </div>
                <div>
                  <label className={labelCls} style={labelStyle}>{t('genai.ociCredential')}</label>
                  <select value={ociConfigId} onChange={(e) => fillFromOci(e.target.value)} className={inputCls} style={inputStyle}>
                    <option value="">{t('common.select')}</option>
                    {ociCfg.map((c) => (
                      <option key={c.id} value={c.id}>{c.tenancy_name} ({c.region})</option>
                    ))}
                  </select>
                </div>
                <div>
                  <label className={labelCls} style={labelStyle}>{t('genai.modelSelect')}</label>
                  <select value={modelId} onChange={(e) => setModelId(e.target.value)} className={inputCls} style={inputStyle}>
                    <option value="_custom"><LinkIcon size={10} className="inline" /> {t('genai.customOcid')}</option>
                    {Object.entries(groupedModels).map(([provider, items]) => (
                      <optgroup key={provider} label={provider}>
                        {items.map((m) => (
                          <option key={m.key} value={m.key}>{m.name} ({provider})</option>
                        ))}
                      </optgroup>
                    ))}
                  </select>
                </div>
              </div>

              {/* Row 2 */}
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div>
                  <label className={labelCls} style={labelStyle}>{t('genai.genaiRegion')}</label>
                  <select value={genaiRegion} onChange={(e) => setGenaiRegion(e.target.value)} className={inputCls} style={inputStyle}>
                    {regions.map((r) => (
                      <option key={r} value={r}>{r}</option>
                    ))}
                  </select>
                </div>
                <div>
                  <label className={labelCls} style={labelStyle}>{t('genai.compartment')}</label>
                  <input type="text" value={compartmentId} onChange={(e) => setCompartmentId(e.target.value)} placeholder="ocid1.compartment.oc1.." className={inputCls} style={inputStyle} />
                </div>
                <div>
                  <label className={labelCls} style={labelStyle}>{t('genai.modelOcid')}</label>
                  <p className={hintCls} style={{ ...hintStyle, marginBottom: 4 }}>{t('genai.modelOcidHint')}</p>
                  <input
                    type="text"
                    value={modelOcid}
                    onChange={(e) => setModelOcid(e.target.value)}
                    placeholder="ocid1.generativeaimodel.oc1.iad.amaaaaaa..."
                    className={inputCls}
                    style={{ ...inputStyle, borderColor: modelOcid ? 'var(--pp)' : undefined, fontFamily: 'var(--fm)', fontSize: '.72rem' }}
                  />
                </div>
              </div>

              {/* Default toggle */}
              <div className="flex items-center gap-3">
                <button
                  type="button"
                  onClick={() => setIsDefault(!isDefault)}
                  className="flex items-center gap-2 px-3 py-1.5 rounded-lg text-[.72rem] font-semibold transition-all"
                  style={{
                    background: isDefault ? 'color-mix(in srgb, #f39c12 15%, transparent)' : 'var(--bg2)',
                    color: isDefault ? '#f39c12' : 'var(--t4)',
                    border: `1.5px solid ${isDefault ? '#f39c12' : 'var(--bd)'}`,
                  }}
                >
                  <Star size={12} /> {isDefault ? t('genai.default') : t('genai.setDefault')}
                </button>
              </div>

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

    </div>
  );
}
