/* ============================================================
   admin-templates.jsx — Шаблоны + Категории
   Поля API — camelCase (Drizzle): imageUrl, isActive, isPro,
   section, type, model, sortOrder, category (строка-имя).
   ============================================================ */

const { useState, useEffect, useRef } = React;

/* Модели для дропдауна шаблона (как в Mini App admin) */
const TPL_MODEL_OPTIONS = [
  { value: '', label: 'Авто' },
  { value: 'gemini-2-5-flash', label: 'Nano Banana (Gemini Flash) · 2💎' },
  { value: 'gemini-3-1-flash', label: 'Nano Banana 2 (Gemini 3.1 Flash) · 3💎' },
  { value: 'gemini-3-pro', label: 'Nano Banana Pro (Gemini 3 Pro) · 3💎' },
  { value: 'imagen-4-ultra', label: 'Imagen 4 Ultra · 3💎' },
  { value: 'gpt-image-2', label: 'Дизайн (OpenAI) · 5💎' },
  { value: 'flux', label: 'Стиль (Flux) · 4💎' },
];

const TPL_EMPTY = {
  title: '', prompt: '', imageUrl: '', section: 'marketplace',
  type: 'photo', model: '', category: '', sortOrder: 0,
  isActive: true, isPro: false,
};

/* ─── Загрузка картинки в /api/tg/admin/upload ─── */
function AdminImageUpload({ API_BASE, value, onChange, toast }) {
  const [uploading, setUploading] = useState(false);
  const inputRef = useRef(null);

  async function pick(file) {
    if (!file) return;
    setUploading(true);
    try {
      const form = new FormData();
      form.append('file', file);
      const r = await fetch(`${API_BASE}/api/tg/admin/upload`, { method: 'POST', body: form, credentials: 'include' });
      const data = await r.json();
      if (data.url) { onChange(data.url); toast && toast('Картинка загружена', 'ok'); }
      else { toast && toast(data.error || 'Ошибка загрузки', 'warn'); }
    } catch { toast && toast('Ошибка загрузки', 'warn'); }
    finally { setUploading(false); }
  }

  return (
    <div>
      {value && (
        <img src={value} alt="" style={{ width: '100%', maxHeight: 180, objectFit: 'cover', borderRadius: 8, marginBottom: 8 }} />
      )}
      <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
        <input
          className="field-input"
          placeholder="URL или загрузи файл →"
          value={value || ''}
          onChange={e => onChange(e.target.value)}
          style={{ flex: 1 }}
        />
        <input ref={inputRef} type="file" accept="image/jpeg,image/png,image/webp" style={{ display: 'none' }}
          onChange={e => e.target.files[0] && pick(e.target.files[0])} />
        <button className="btn btn-ghost btn-sm" onClick={() => inputRef.current?.click()} disabled={uploading}>
          {uploading ? <Spinner sm /> : '📁 Загрузить'}
        </button>
        {value && <button className="btn btn-ghost btn-sm" onClick={() => onChange('')}>✕</button>}
      </div>
    </div>
  );
}

function AdminTemplates() {
  const { API_BASE } = useAuth();
  const toast = useToast();
  const [tab, setTab] = useState('templates');

  const tabs = [
    { id: 'templates', label: '🎨 Шаблоны' },
    { id: 'categories', label: '🏷 Категории' },
  ];

  return (
    <div>
      <div className="page-head">
        <div className="page-head-text">
          <h1 className="page-title h-display">🎨 Шаблоны</h1>
        </div>
      </div>
      <Tabs items={tabs} active={tab} onChange={setTab} />
      {tab === 'templates'  && <TemplatesList API_BASE={API_BASE} toast={toast} />}
      {tab === 'categories' && <CategoriesList API_BASE={API_BASE} toast={toast} />}
    </div>
  );
}

/* ─── Templates ─── */
function TemplatesList({ API_BASE, toast }) {
  const [items, setItems] = useState([]);
  const [categories, setCategories] = useState([]);
  const [loading, setLoading] = useState(true);
  const [form, setForm] = useState(null);
  const [saving, setSaving] = useState(false);
  const [search, setSearch] = useState('');
  const [sectionFilter, setSectionFilter] = useState('all');

  async function load() {
    setLoading(true);
    try {
      const [tr, cr] = await Promise.all([
        fetch(`${API_BASE}/api/tg/admin/templates`, { credentials: 'include' }),
        fetch(`${API_BASE}/api/tg/admin/categories`, { credentials: 'include' }),
      ]);
      if (tr.ok) setItems(await tr.json());
      if (cr.ok) setCategories(await cr.json());
    } catch {} finally { setLoading(false); }
  }

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

  async function save() {
    setSaving(true);
    try {
      const payload = {
        ...(form.id && { id: form.id }),
        title: form.title,
        prompt: form.prompt,
        imageUrl: form.imageUrl || null,
        section: form.section || 'marketplace',
        type: form.type || 'photo',
        model: form.model || null,
        category: form.category || null,
        sortOrder: Number(form.sortOrder) || 0,
        isActive: form.isActive ?? true,
        isPro: form.isPro ?? false,
      };
      const r = await fetch(`${API_BASE}/api/tg/admin/templates`, {
        method: form.id ? 'PUT' : 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload), credentials: 'include',
      });
      if (r.ok) { toast('Сохранено', 'ok'); setForm(null); load(); }
      else { const d = await r.json(); toast(d.error || 'Ошибка', 'warn'); }
    } catch { toast('Ошибка', 'warn'); } finally { setSaving(false); }
  }

  async function del(id) {
    if (!confirm('Удалить шаблон?')) return;
    await fetch(`${API_BASE}/api/tg/admin/templates?id=${id}`, { method: 'DELETE', credentials: 'include' });
    toast('Удалено', 'ok');
    load();
  }

  async function toggle(t) {
    await fetch(`${API_BASE}/api/tg/admin/templates`, {
      method: 'PUT', headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ id: t.id, isActive: !t.isActive }), credentials: 'include',
    });
    load();
  }

  const filtered = items.filter(t => {
    const secOk = sectionFilter === 'all' || t.section === sectionFilter;
    const srchOk = !search || t.title?.includes(search) || t.prompt?.includes(search);
    return secOk && srchOk;
  });

  if (form) return (
    <div style={{ maxWidth: 540 }}>
      <div className="page-head"><button className="btn btn-ghost back-btn" onClick={() => setForm(null)}>← Назад</button></div>
      <div className="glass" style={{ padding: 24 }}>
        <div className="block-title" style={{ marginBottom: 18 }}>{form.id ? 'Редактировать шаблон' : 'Новый шаблон'}</div>

        <div className="field" style={{ marginBottom: 14 }}>
          <label className="field-label">Название</label>
          <input className="field-input" value={form.title || ''} onChange={e => setForm(f => ({...f, title: e.target.value}))} />
        </div>

        <div className="field" style={{ marginBottom: 14 }}>
          <label className="field-label">Промпт</label>
          <textarea className="prompt-area" rows={4} value={form.prompt || ''} onChange={e => setForm(f => ({...f, prompt: e.target.value}))} />
        </div>

        <div className="field" style={{ marginBottom: 14 }}>
          <label className="field-label">Картинка</label>
          <AdminImageUpload API_BASE={API_BASE} value={form.imageUrl} onChange={v => setForm(f => ({...f, imageUrl: v}))} toast={toast} />
        </div>

        <div style={{ display: 'flex', gap: 12, marginBottom: 14 }}>
          <div className="field" style={{ flex: 1 }}>
            <label className="field-label">Раздел</label>
            <select className="field-input" value={form.section} onChange={e => setForm(f => ({...f, section: e.target.value}))}>
              <option value="marketplace">Маркетплейс</option>
              <option value="social">Соц. сети</option>
            </select>
          </div>
          <div className="field" style={{ flex: 1 }}>
            <label className="field-label">Тип</label>
            <select className="field-input" value={form.type} onChange={e => setForm(f => ({...f, type: e.target.value}))}>
              <option value="photo">Фото</option>
              <option value="video">Видео</option>
            </select>
          </div>
        </div>

        <div className="field" style={{ marginBottom: 14 }}>
          <label className="field-label">Модель</label>
          <select className="field-input" value={form.model || ''} onChange={e => setForm(f => ({...f, model: e.target.value}))}>
            {TPL_MODEL_OPTIONS.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
          </select>
        </div>

        <div style={{ display: 'flex', gap: 12, marginBottom: 14 }}>
          <div className="field" style={{ flex: 1 }}>
            <label className="field-label">Категория</label>
            <select className="field-input" value={form.category || ''} onChange={e => setForm(f => ({...f, category: e.target.value}))}>
              <option value="">— без категории —</option>
              {categories.map(c => <option key={c.id} value={c.name}>{c.name}</option>)}
            </select>
          </div>
          <div className="field" style={{ width: 120 }}>
            <label className="field-label">Порядок</label>
            <input className="field-input" type="number" value={form.sortOrder ?? 0} onChange={e => setForm(f => ({...f, sortOrder: e.target.value}))} />
          </div>
        </div>

        <div style={{ display: 'flex', gap: 16, marginBottom: 16 }}>
          <Toggle label="Активен" value={form.isActive ?? true} onChange={v => setForm(f => ({...f, isActive: v}))} />
          <Toggle label="🔒 PRO" value={form.isPro ?? false} onChange={v => setForm(f => ({...f, isPro: v}))} />
        </div>

        <div style={{ display: 'flex', gap: 10 }}>
          <button className="btn btn-accent" onClick={save} disabled={saving || !form.title || !form.prompt}>{saving ? <Spinner sm /> : 'Сохранить'}</button>
          <button className="btn btn-ghost" onClick={() => setForm(null)}>Отмена</button>
        </div>
      </div>
    </div>
  );

  return (
    <div>
      <div style={{ display: 'flex', gap: 10, marginBottom: 14 }}>
        <button className="btn btn-accent btn-sm" onClick={() => setForm({ ...TPL_EMPTY })}>+ Добавить</button>
        <input className="field-input" placeholder="Поиск..." value={search} onChange={e => setSearch(e.target.value)} style={{ flex: 1 }} />
      </div>
      <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 14 }}>
        {[['all', 'Все'], ['marketplace', '🛒 Маркетплейс'], ['social', '📱 Соц. сети']].map(([v, l]) => (
          <button key={v} className={`seg-btn${sectionFilter === v ? ' on' : ''}`} onClick={() => setSectionFilter(v)}>{l}</button>
        ))}
      </div>

      {loading ? <div style={{ textAlign: 'center', padding: 40 }}><Spinner /></div> : (
        <div className="hist-grid">
          {filtered.map(t => (
            <div key={t.id} className="glass" style={{ padding: 14 }}>
              {t.imageUrl && <img src={t.imageUrl} alt="" style={{ width: '100%', aspectRatio: '3/4', objectFit: 'cover', borderRadius: 8, marginBottom: 10 }} />}
              <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 4 }}>
                <span style={{ fontWeight: 700, flex: 1 }}>{t.title}</span>
                {t.isPro && <span className="pill pill-pro" style={{ fontSize: 9 }}>PRO</span>}
              </div>
              <div className="muted" style={{ fontSize: 11, marginBottom: 6 }}>
                {t.section === 'social' ? '📱 Соц.' : '🛒 Маркет'} · {t.type === 'video' ? '🎬' : '🖼'}{t.category ? ` · #${t.category}` : ''}
              </div>
              <p className="muted" style={{ fontSize: 12, marginBottom: 10 }}>{t.prompt?.slice(0, 60)}…</p>
              <div style={{ display: 'flex', gap: 6 }}>
                <button className="btn btn-ghost btn-sm" onClick={() => setForm({ ...TPL_EMPTY, ...t })}>✏️</button>
                <button className="btn btn-ghost btn-sm" onClick={() => toggle(t)}>
                  {t.isActive ? '✓' : '○'}
                </button>
                <button className="btn btn-sm" style={{ color: '#fca5a5' }} onClick={() => del(t.id)}>🗑</button>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

/* ─── Categories ─── */
function CategoriesList({ API_BASE, toast }) {
  const [items, setItems] = useState([]);
  const [loading, setLoading] = useState(true);
  const [form, setForm] = useState(null);
  const [saving, setSaving] = useState(false);

  async function load() {
    setLoading(true);
    try { const r = await fetch(`${API_BASE}/api/tg/admin/categories`, { credentials: 'include' }); if (r.ok) setItems(await r.json()); }
    catch {} finally { setLoading(false); }
  }

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

  async function save() {
    setSaving(true);
    try {
      const payload = {
        ...(form.id && { id: form.id }),
        name: form.name,
        section: form.section || 'all',
        type: form.type || 'all',
        sortOrder: Number(form.sortOrder) || 0,
        ...(form.id && { isActive: form.isActive ?? true }),
      };
      const r = await fetch(`${API_BASE}/api/tg/admin/categories`, {
        method: form.id ? 'PUT' : 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload), credentials: 'include',
      });
      if (r.ok) { toast('Сохранено', 'ok'); setForm(null); load(); }
      else { const d = await r.json(); toast(d.error || 'Ошибка', 'warn'); }
    } catch { toast('Ошибка', 'warn'); } finally { setSaving(false); }
  }

  async function del(id) {
    if (!confirm('Удалить?')) return;
    await fetch(`${API_BASE}/api/tg/admin/categories?id=${id}`, { method: 'DELETE', credentials: 'include' });
    toast('Удалено', 'ok'); load();
  }

  if (form) return (
    <div style={{ maxWidth: 440 }}>
      <div className="page-head"><button className="btn btn-ghost back-btn" onClick={() => setForm(null)}>← Назад</button></div>
      <div className="glass" style={{ padding: 24 }}>
        <div className="block-title" style={{ marginBottom: 18 }}>{form.id ? 'Редактировать категорию' : 'Новая категория'}</div>
        <div className="field" style={{ marginBottom: 12 }}>
          <label className="field-label">Название</label>
          <input className="field-input" value={form.name || ''} onChange={e => setForm(f => ({...f, name: e.target.value}))} />
        </div>
        <div style={{ display: 'flex', gap: 12, marginBottom: 12 }}>
          <div className="field" style={{ flex: 1 }}>
            <label className="field-label">Раздел</label>
            <select className="field-input" value={form.section || 'all'} onChange={e => setForm(f => ({...f, section: e.target.value}))}>
              <option value="all">Все разделы</option>
              <option value="marketplace">Маркетплейс</option>
              <option value="social">Соц. сети</option>
            </select>
          </div>
          <div className="field" style={{ flex: 1 }}>
            <label className="field-label">Тип</label>
            <select className="field-input" value={form.type || 'all'} onChange={e => setForm(f => ({...f, type: e.target.value}))}>
              <option value="all">Все типы</option>
              <option value="photo">Фото</option>
              <option value="video">Видео</option>
            </select>
          </div>
        </div>
        <div className="field" style={{ marginBottom: 14 }}>
          <label className="field-label">Порядок</label>
          <input className="field-input" type="number" value={form.sortOrder || 0} onChange={e => setForm(f => ({...f, sortOrder: Number(e.target.value)}))} />
        </div>
        {form.id && <Toggle label="Активна" value={form.isActive ?? true} onChange={v => setForm(f => ({...f, isActive: v}))} />}
        <div style={{ display: 'flex', gap: 10, marginTop: 16 }}>
          <button className="btn btn-accent" onClick={save} disabled={saving || !form.name}>{saving ? <Spinner sm /> : 'Сохранить'}</button>
          <button className="btn btn-ghost" onClick={() => setForm(null)}>Отмена</button>
        </div>
      </div>
    </div>
  );

  return (
    <div>
      <button className="btn btn-accent btn-sm" style={{ marginBottom: 16 }} onClick={() => setForm({ name: '', section: 'all', type: 'all', sortOrder: 0, isActive: true })}>+ Добавить</button>
      {loading ? <div style={{ textAlign: 'center', padding: 40 }}><Spinner /></div> : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {items.map(c => (
            <div key={c.id} className="glass" style={{ padding: '14px 18px', display: 'flex', gap: 14, alignItems: 'center' }}>
              <div style={{ flex: 1 }}>
                <div style={{ fontWeight: 700 }}>{c.name}</div>
                <div className="muted" style={{ fontSize: 12 }}>{c.section} · {c.type} · #{c.sortOrder}</div>
              </div>
              <span className={`pill${c.isActive ? ' pill-free' : ''}`}>{c.isActive ? 'Активна' : 'Откл.'}</span>
              <button className="btn btn-ghost btn-sm" onClick={() => setForm(c)}>✏️</button>
              <button className="btn btn-sm" style={{ color: '#fca5a5' }} onClick={() => del(c.id)}>🗑</button>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
