// Panel de administración. Solo accesible para usuarios con isAdmin=true.
// Lista todos los feedbacks recibidos con filtros y acciones de status.

function AdminPanel({ backend, token, isMobile, onBack, onCountChange }) {
  const [data, setData] = React.useState({ feedback: [], counts: {} });
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState('');
  const [statusFilter, setStatusFilter] = React.useState('all');
  const [categoryFilter, setCategoryFilter] = React.useState('all');
  const [busyId, setBusyId] = React.useState(null);
  // Feedback que el admin está por eliminar — null cuando el modal está cerrado.
  // Guardamos el objeto entero para poder mostrar un preview en el modal.
  const [confirmDelete, setConfirmDelete] = React.useState(null);

  const fetchData = React.useCallback(() => {
    setLoading(true);
    const params = new URLSearchParams();
    if (statusFilter !== 'all') params.set('status', statusFilter);
    if (categoryFilter !== 'all') params.set('category', categoryFilter);
    fetch(`${backend}/api/admin/feedback?${params}`, {
      headers: { Authorization: `Bearer ${token}` },
    })
      .then(r => r.ok ? r.json() : Promise.reject(new Error('Error al cargar')))
      .then(d => { setData(d); setError(''); })
      .catch(e => setError(e.message))
      .finally(() => setLoading(false));
  }, [backend, token, statusFilter, categoryFilter]);

  React.useEffect(() => { fetchData(); }, [fetchData]);

  const updateStatus = async (id, status) => {
    setBusyId(id);
    try {
      const r = await fetch(`${backend}/api/admin/feedback/${id}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
        body: JSON.stringify({ status }),
      });
      if (!r.ok) throw new Error('Error');
      fetchData();
      onCountChange?.(); // refresh el badge del sidebar al instante
    } catch {
      setError('No se pudo actualizar');
    } finally {
      setBusyId(null);
    }
  };

  // Reemplazamos el window.confirm() nativo (que se ve fuera de lugar respecto a la
  // estética de la app) por un modal custom: setea el feedback a confirmar y se
  // dibuja al final del componente. La eliminación real ocurre en doRemove abajo.
  const removeItem = (feedback) => setConfirmDelete(feedback);

  const doRemove = async () => {
    if (!confirmDelete) return;
    const id = confirmDelete.id;
    setConfirmDelete(null);
    setBusyId(id);
    try {
      const r = await fetch(`${backend}/api/admin/feedback/${id}`, {
        method: 'DELETE',
        headers: { Authorization: `Bearer ${token}` },
      });
      if (!r.ok) throw new Error('Error');
      fetchData();
      onCountChange?.();
    } catch {
      setError('No se pudo eliminar');
    } finally {
      setBusyId(null);
    }
  };

  const STATUS_LABELS = { new: 'Nuevo', reviewed: 'Revisado', resolved: 'Resuelto' };
  const STATUS_COLORS = {
    new:      { bg: 'rgba(245, 158, 11, 0.14)', fg: '#f59e0b' },
    reviewed: { bg: 'rgba(6, 182, 212, 0.14)',  fg: '#06b6d4' },
    resolved: { bg: 'rgba(0, 194, 117, 0.14)',  fg: '#00c275' },
  };
  const CATEGORY_LABELS = {
    bug: '🐛 Bug', sugerencia: '💡 Sugerencia', pregunta: '❓ Pregunta', otro: '✍️ Otro',
  };

  const filterTabs = [
    { id: 'all', label: 'Todo', count: data.counts.total ?? 0 },
    { id: 'new', label: 'Nuevos', count: data.counts.new ?? 0 },
    { id: 'reviewed', label: 'Revisados', count: data.counts.reviewed ?? 0 },
    { id: 'resolved', label: 'Resueltos', count: data.counts.resolved ?? 0 },
  ];

  const fmtDate = (s) => {
    const d = new Date(s + 'Z'); // SQLite stores in UTC without TZ
    return d.toLocaleString('es-AR', {
      day: '2-digit', month: '2-digit', year: 'numeric',
      hour: '2-digit', minute: '2-digit',
    });
  };

  return (
    <div className="layout" data-screen-label="Admin">
      <main className="main-pane" style={{ paddingTop: isMobile ? 68 : 22 }}>
        {/* Header */}
        <div style={{ marginBottom: 18 }}>
          <button
            type="button"
            onClick={onBack}
            style={{
              display: 'inline-flex', alignItems: 'center', gap: 6,
              padding: '4px 0', marginBottom: 6,
              fontSize: 12.5, fontWeight: 500, color: 'var(--text-dim)',
              background: 'transparent', border: 'none',
            }}
            onMouseEnter={e => e.currentTarget.style.color = 'var(--text)'}
            onMouseLeave={e => e.currentTarget.style.color = 'var(--text-dim)'}
          >
            <svg width="14" height="14" viewBox="0 0 16 16" fill="none">
              <path d="M10 3 L5 8 L10 13" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" />
            </svg>
            Volver al dashboard
          </button>
          <h1 style={{
            fontFamily: 'Space Grotesk, Inter, sans-serif',
            fontSize: 28, fontWeight: 700, letterSpacing: -0.6,
            margin: 0,
          }}>
            Panel de admin
          </h1>
          <div style={{ fontSize: 13, color: 'var(--text-dim)', marginTop: 4 }}>
            Feedback recibido de los usuarios. {data.counts.total ?? 0} total.
          </div>
        </div>

        {/* Filtros de status */}
        <div style={{
          display: 'flex', gap: 6, marginBottom: 12, flexWrap: 'wrap',
          borderBottom: '1px solid var(--border)',
        }}>
          {filterTabs.map(t => {
            const active = t.id === statusFilter;
            return (
              <button
                key={t.id}
                onClick={() => setStatusFilter(t.id)}
                style={{
                  padding: '8px 14px', fontSize: 13, fontWeight: 500,
                  color: active ? 'var(--accent)' : 'var(--text-dim)',
                  borderBottom: `2px solid ${active ? 'var(--accent)' : 'transparent'}`,
                  marginBottom: -1,
                  display: 'flex', alignItems: 'center', gap: 6,
                }}>
                {t.label}
                <span style={{
                  background: active ? 'var(--accent)' : 'var(--panel-2)',
                  color: active ? '#fff' : 'var(--text-dim)',
                  fontSize: 10, fontWeight: 600,
                  padding: '1px 7px', borderRadius: 999,
                }}>{t.count}</span>
              </button>
            );
          })}
        </div>

        {/* Filtro de categoría */}
        <div style={{ display: 'flex', gap: 6, marginBottom: 18, flexWrap: 'wrap' }}>
          {[
            { id: 'all', label: 'Todas' },
            { id: 'sugerencia', label: '💡 Sugerencias' },
            { id: 'bug', label: '🐛 Bugs' },
            { id: 'pregunta', label: '❓ Preguntas' },
            { id: 'otro', label: '✍️ Otros' },
          ].map(c => {
            const active = c.id === categoryFilter;
            return (
              <button key={c.id} onClick={() => setCategoryFilter(c.id)}
                style={{
                  padding: '5px 11px', fontSize: 11.5, fontWeight: 500,
                  borderRadius: 7,
                  background: active ? 'var(--panel-2)' : 'transparent',
                  color: active ? 'var(--text)' : 'var(--text-dim)',
                  border: `1px solid ${active ? 'var(--border-strong)' : 'transparent'}`,
                }}>
                {c.label}
              </button>
            );
          })}
        </div>

        {/* Lista de feedbacks */}
        {loading ? (
          <div style={{ padding: '60px 0', textAlign: 'center', color: 'var(--text-dim)', fontSize: 13 }}>
            Cargando feedback…
          </div>
        ) : error ? (
          <div style={{ padding: 20, color: 'var(--red)', fontSize: 13 }}>{error}</div>
        ) : data.feedback.length === 0 ? (
          <div style={{
            padding: '60px 24px', textAlign: 'center', color: 'var(--text-dim)',
            background: 'var(--panel)', border: '1px solid var(--border)',
            borderRadius: 'var(--radius)', fontSize: 13,
          }}>
            No hay feedback con estos filtros.
          </div>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {data.feedback.map(f => {
              const sCol = STATUS_COLORS[f.status] || STATUS_COLORS.new;
              return (
                <div key={f.id} style={{
                  background: 'var(--panel)', border: '1px solid var(--border)',
                  borderRadius: 12, padding: 16,
                }}>
                  {/* Header de la card */}
                  <div style={{ display: 'flex', alignItems: 'center', flexWrap: 'wrap', gap: 8, marginBottom: 8 }}>
                    <span style={{
                      background: sCol.bg, color: sCol.fg,
                      fontSize: 10.5, fontWeight: 700, letterSpacing: 0.4,
                      padding: '3px 9px', borderRadius: 6, textTransform: 'uppercase',
                    }}>{STATUS_LABELS[f.status] || f.status}</span>
                    <span style={{ fontSize: 11.5, color: 'var(--text-dim)' }}>
                      {CATEGORY_LABELS[f.category] || f.category}
                    </span>
                    <span style={{ fontSize: 11, color: 'var(--text-faint)', marginLeft: 'auto' }}>
                      {fmtDate(f.created_at)}
                    </span>
                  </div>

                  {/* Mensaje */}
                  <div style={{
                    fontSize: 14, lineHeight: 1.5, marginBottom: 10,
                    whiteSpace: 'pre-wrap', wordBreak: 'break-word',
                  }}>
                    {f.message}
                  </div>

                  {/* Metadata */}
                  <div style={{
                    fontSize: 11, color: 'var(--text-faint)',
                    display: 'flex', gap: 12, flexWrap: 'wrap',
                    paddingBottom: 10, borderBottom: '1px solid var(--border)',
                    marginBottom: 10,
                  }}>
                    <span><strong style={{ color: 'var(--text-dim)' }}>de:</strong> {f.user_email || '—'}</span>
                    {f.url && <span><strong style={{ color: 'var(--text-dim)' }}>desde:</strong> {f.url}</span>}
                  </div>

                  {/* Acciones */}
                  <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                    {f.status !== 'reviewed' && (
                      <button
                        onClick={() => updateStatus(f.id, 'reviewed')}
                        disabled={busyId === f.id}
                        style={actionBtnStyle('#06b6d4')}>
                        Marcar revisado
                      </button>
                    )}
                    {f.status !== 'resolved' && (
                      <button
                        onClick={() => updateStatus(f.id, 'resolved')}
                        disabled={busyId === f.id}
                        style={actionBtnStyle('var(--accent)')}>
                        ✓ Resolver
                      </button>
                    )}
                    {f.status !== 'new' && (
                      <button
                        onClick={() => updateStatus(f.id, 'new')}
                        disabled={busyId === f.id}
                        style={actionBtnStyle('var(--text-dim)', true)}>
                        Reabrir
                      </button>
                    )}
                    <button
                      onClick={() => removeItem(f)}
                      disabled={busyId === f.id}
                      style={{ ...actionBtnStyle('var(--red)', true), marginLeft: 'auto' }}>
                      Eliminar
                    </button>
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </main>

      {/* Modal de confirmación al eliminar feedback. Reemplaza el window.confirm
          nativo del browser para que matchee la estética del resto de la app. */}
      {confirmDelete && (
        <div
          onClick={() => setConfirmDelete(null)}
          style={{
            position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.6)',
            display: 'grid', placeItems: 'center', zIndex: 60, padding: 16,
            animation: 'feedbackSlideIn 0.18s ease-out',
          }}>
          <div
            onClick={e => e.stopPropagation()}
            style={{
              width: 380, maxWidth: 'calc(100% - 32px)',
              background: 'var(--panel)', border: '1px solid var(--border)',
              borderRadius: 18, padding: '28px 24px 22px',
              boxShadow: '0 28px 70px rgba(0,0,0,0.55)',
              display: 'flex', flexDirection: 'column', alignItems: 'center',
              gap: 8, textAlign: 'center', boxSizing: 'border-box',
            }}>
            <div style={{
              width: 52, height: 52, borderRadius: '50%',
              background: 'rgba(239,104,104,0.12)',
              border: '1px solid rgba(239,104,104,0.25)',
              display: 'grid', placeItems: 'center', marginBottom: 4,
            }}>
              <svg width="22" height="22" viewBox="0 0 24 24" fill="none">
                <path d="M4 7h16M6 7l1 13h10L18 7M9 7V4.5h6V7" stroke="var(--red)"
                      strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
            </div>
            <div style={{ fontSize: 17, fontWeight: 700, letterSpacing: -0.3 }}>
              Eliminar feedback
            </div>
            <div style={{ fontSize: 13.5, color: 'var(--text-dim)', lineHeight: 1.5 }}>
              ¿Seguro que querés eliminar este feedback? Esta acción no se puede deshacer.
            </div>
            {confirmDelete.message && (
              <div style={{
                width: '100%', marginTop: 8, padding: '10px 12px',
                background: 'var(--panel-2)', border: '1px solid var(--border)',
                borderRadius: 10, fontSize: 12.5, color: 'var(--text-dim)',
                textAlign: 'left', lineHeight: 1.45,
                maxHeight: 80, overflow: 'hidden',
                display: '-webkit-box', WebkitLineClamp: 3, WebkitBoxOrient: 'vertical',
              }}>
                <span style={{ color: 'var(--text-faint)', fontWeight: 600 }}>
                  {CATEGORY_LABELS[confirmDelete.category] || confirmDelete.category || ''}
                </span>
                {confirmDelete.category ? ' — ' : ''}
                {confirmDelete.message}
              </div>
            )}
            <div style={{ display: 'flex', gap: 10, marginTop: 14, width: '100%' }}>
              <button
                onClick={() => setConfirmDelete(null)}
                style={{
                  flex: 1, padding: '11px 0', borderRadius: 11,
                  fontWeight: 600, fontSize: 14,
                  background: 'var(--panel-2)', border: '1px solid var(--border)',
                  color: 'var(--text)', cursor: 'pointer',
                }}>
                Cancelar
              </button>
              <button
                onClick={doRemove}
                style={{
                  flex: 1, padding: '11px 0', borderRadius: 11,
                  fontWeight: 700, fontSize: 14,
                  background: 'var(--red)', color: '#fff', border: 'none',
                  cursor: 'pointer',
                }}>
                Eliminar
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

function actionBtnStyle(color, ghost = false) {
  return {
    padding: '6px 12px', borderRadius: 8, fontSize: 12, fontWeight: 600,
    color: ghost ? color : '#fff',
    background: ghost ? 'transparent' : color,
    border: ghost ? `1px solid ${color}` : 'none',
    cursor: 'pointer',
    transition: 'opacity 0.15s',
  };
}

Object.assign(window, { AdminPanel });
