/* ============================================================
   admin-broadcast.jsx — Рассылка + Видео статистика
   ============================================================ */

const { useState, useEffect } = React;

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

  const tabs = [
    { id: 'broadcast', label: '📢 Рассылка' },
    { id: 'videos',    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 === 'broadcast' && <BroadcastPanel API_BASE={API_BASE} toast={toast} />}
      {tab === 'videos'    && <AdminVideos    API_BASE={API_BASE} toast={toast} />}
    </div>
  );
}

/* ─── Broadcast ─── */
function BroadcastPanel({ API_BASE, toast }) {
  const [text, setText] = useState('');
  const [imageUrl, setImageUrl] = useState('');
  const [segment, setSegment] = useState('all');
  const [sending, setSending] = useState(false);
  const [history, setHistory] = useState([]);
  const [loadingHist, setLoadingHist] = useState(true);
  const [countPreview, setCountPreview] = useState(null);

  async function loadHistory() {
    setLoadingHist(true);
    try {
      const r = await fetch(`${API_BASE}/api/tg/admin/broadcast`, { credentials: 'include' });
      if (r.ok) { const d = await r.json(); setHistory(d.broadcasts || []); }
    } catch {} finally { setLoadingHist(false); }
  }

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

  async function getCount() {
    try {
      const r = await fetch(`${API_BASE}/api/tg/admin/broadcast?segment=${segment}&count=1`, { credentials: 'include' });
      if (r.ok) { const d = await r.json(); setCountPreview(d.count); }
    } catch {}
  }

  async function send() {
    if (!text.trim()) { toast('Введи текст', 'warn'); return; }
    if (!confirm(`Разослать ${countPreview ?? '?'} пользователям сегмента "${segment}"?`)) return;
    setSending(true);
    try {
      const r = await fetch(`${API_BASE}/api/tg/admin/broadcast`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ text, imageUrl: imageUrl || undefined, segment }),
        credentials: 'include',
      });
      if (r.ok) {
        toast('Рассылка запущена', 'ok');
        setText(''); setImageUrl(''); setCountPreview(null);
        loadHistory();
      } else {
        const d = await r.json();
        toast(d.error || 'Ошибка', 'warn');
      }
    } catch { toast('Ошибка', 'warn'); } finally { setSending(false); }
  }

  const SEGMENTS = ['all', 'free', 'pro', 'business'];

  function fmtDate(d) {
    return new Date(d).toLocaleDateString('ru', { day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit' });
  }

  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1.3fr', gap: 24, alignItems: 'start' }}>
      {/* Форма */}
      <div className="glass" style={{ padding: 24 }}>
        <div className="block-title" style={{ marginBottom: 18 }}>Новая рассылка</div>

        <div className="field" style={{ marginBottom: 14 }}>
          <div className="field-label">Сегмент</div>
          <div className="seg" style={{ flexWrap: 'wrap' }}>
            {SEGMENTS.map(s => (
              <button key={s} className={`seg-btn${segment === s ? ' on' : ''}`} onClick={() => { setSegment(s); setCountPreview(null); }}>
                {s}
              </button>
            ))}
          </div>
          <button className="btn btn-ghost btn-sm" style={{ marginTop: 8 }} onClick={getCount}>
            Посчитать получателей
          </button>
          {countPreview != null && <div className="muted" style={{ marginTop: 6, fontSize: 13 }}>👥 {countPreview} пользователей</div>}
        </div>

        <div className="field" style={{ marginBottom: 14 }}>
          <label className="field-label">Текст сообщения</label>
          <textarea className="prompt-area" rows={6} value={text} onChange={e => setText(e.target.value)} placeholder="HTML или plain text..." />
        </div>

        <div className="field" style={{ marginBottom: 18 }}>
          <label className="field-label">URL картинки (необязательно)</label>
          <input className="field-input" value={imageUrl} onChange={e => setImageUrl(e.target.value)} placeholder="https://..." />
        </div>

        <button className="btn btn-accent btn-block" onClick={send} disabled={sending || !text.trim()}>
          {sending ? <><Spinner sm /> Отправляю...</> : '📢 Разослать'}
        </button>
      </div>

      {/* История */}
      <div>
        <div className="block-title" style={{ marginBottom: 14 }}>История рассылок</div>
        {loadingHist ? <div style={{ textAlign: 'center', padding: 30 }}><Spinner /></div> : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {history.map(b => (
              <div key={b.id} className="glass" style={{ padding: '14px 18px' }}>
                <div className="muted" style={{ fontSize: 12, marginBottom: 6 }}>
                  {fmtDate(b.createdAt)} · Сегмент: {b.segment}
                </div>
                <p style={{ fontSize: 14, marginBottom: 6 }}>{b.text?.slice(0, 80)}{b.text?.length > 80 ? '...' : ''}</p>
                <div style={{ display: 'flex', gap: 12, fontSize: 12 }}>
                  <span style={{ color: '#34d399' }}>✓ {b.sentCount || 0}</span>
                  <span className="muted">/ {b.totalCount || 0} всего</span>
                  <span className={`pill${b.status === 'done' ? ' pill-free' : ''}`} style={{ fontSize: 10 }}>{b.status}</span>
                </div>
              </div>
            ))}
            {history.length === 0 && <EmptyState icon="📢" title="Нет рассылок" />}
          </div>
        )}
      </div>
    </div>
  );
}

/* ─── Videos stats ─── */
function AdminVideos({ API_BASE }) {
  const [videos, setVideos] = useState([]);
  const [loading, setLoading] = useState(true);
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(0);
  const [statusFilter, setStatusFilter] = useState('all');

  async function load(p, s) {
    setLoading(true);
    try {
      const r = await fetch(`${API_BASE}/api/tg/admin/videos?page=${p}&status=${s}`, { credentials: 'include' });
      if (r.ok) { const d = await r.json(); setVideos(d.videos || []); setTotal(d.totalFiltered ?? d.stats?.total ?? 0); }
    } catch {} finally { setLoading(false); }
  }

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

  const STATUS_FILTERS = [
    { value: 'all', label: 'Все' },
    { value: 'processing', label: '⏳ В процессе' },
    { value: 'pending', label: '⏸ Ожидание' },
    { value: 'done', label: '✓ Готово' },
    { value: 'error', label: '✗ Ошибка' },
  ];

  function fmtDate(d) {
    return new Date(d).toLocaleDateString('ru', { day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit' });
  }

  const totalPages = Math.ceil(total / 20);

  return (
    <div>
      <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 16 }}>
        {STATUS_FILTERS.map(f => (
          <button key={f.value} className={`seg-btn${statusFilter === f.value ? ' on' : ''}`}
            onClick={() => { setStatusFilter(f.value); setPage(1); }}>
            {f.label}
          </button>
        ))}
      </div>

      <div className="muted" style={{ fontSize: 13, marginBottom: 14 }}>Всего: {total}</div>

      {loading ? <div style={{ textAlign: 'center', padding: 40 }}><Spinner /></div> : (
        <div className="hist-list">
          {videos.map(v => (
            <div key={v.id} className="glass hist-row">
              {v.videoUrl
                ? <video src={v.videoUrl} style={{ width: 90, height: 56, flexShrink: 0, borderRadius: 6, objectFit: 'cover' }} />
                : <PlaceholderArt type="vid" style={{ width: 90, height: 56, flexShrink: 0, borderRadius: 6 }} />}
              <div className="hist-row-body">
                <div className="hist-row-head">
                  <span className="hist-model">{v.prompt?.slice(0, 36) || '—'}</span>
                  <span style={{ fontSize: 12, color: v.status === 'done' ? '#34d399' : v.status === 'error' ? '#fca5a5' : 'var(--text-muted)' }}>
                    {v.status}
                  </span>
                </div>
                <div className="hist-sub muted">{v.durationSeconds}с · {v.costRub ? `${v.costRub}₽` : '—'} · tg:{v.tgId} · {fmtDate(v.createdAt)}</div>
              </div>
              {v.videoUrl && <a href={v.videoUrl} target="_blank" rel="noreferrer" className="btn btn-ghost btn-sm">▶</a>}
            </div>
          ))}
          {videos.length === 0 && <EmptyState icon="🎬" title="Нет видео" />}
        </div>
      )}

      {totalPages > 1 && (
        <div style={{ display: 'flex', gap: 8, justifyContent: 'center', marginTop: 20 }}>
          <button className="btn btn-ghost btn-sm" disabled={page <= 1} onClick={() => setPage(p => p - 1)}>← Пред.</button>
          <span className="muted" style={{ padding: '8px 14px' }}>{page} / {totalPages}</span>
          <button className="btn btn-ghost btn-sm" disabled={page >= totalPages} onClick={() => setPage(p => p + 1)}>След. →</button>
        </div>
      )}
    </div>
  );
}
