/* Ecrã admin: lista e gestão de tickets de bug report / feedback */

const SistemaTickets = () => {
  const [tickets, setTickets]   = React.useState([]);
  const [loading, setLoading]   = React.useState(true);
  const [filterStatus, setFS]   = React.useState('all');
  const [filterSev, setFSev]    = React.useState('all');
  const [expanded, setExpanded] = React.useState(null);
  const [updating, setUpdating] = React.useState(null);

  const load = () => {
    setLoading(true);
    fetch('/api/tickets?limit=200', { credentials: 'include' })
      .then(r => r.ok ? r.json() : [])
      .then(d => { setTickets(d); setLoading(false); })
      .catch(() => setLoading(false));
  };

  React.useEffect(load, []);

  const updateStatus = async (id, status) => {
    setUpdating(id);
    await fetch(`/api/tickets/${id}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ status }), credentials: 'include' }).catch(() => {});
    setTickets(ts => ts.map(t => t.id === id ? { ...t, status, updated_at: new Date().toISOString() } : t));
    setUpdating(null);
  };

  const filtered = tickets.filter(t =>
    (filterStatus === 'all' || t.status === filterStatus) &&
    (filterSev    === 'all' || t.severity === filterSev)
  );

  const counts = { total: tickets.length, open: tickets.filter(t => t.status === 'open').length, in_progress: tickets.filter(t => t.status === 'in_progress').length, resolved: tickets.filter(t => t.status === 'resolved').length };

  const sevBadge = (s) => ({ low: { bg: '#dcfce7', color: '#166534', label: 'Baixa' }, medium: { bg: '#fef9c3', color: '#854d0e', label: 'Média' }, high: { bg: '#fee2e2', color: '#991b1b', label: 'Alta' } }[s] || { bg: '#f1f5f9', color: '#64748b', label: s });

  const statusOpts = [
    { value: 'open',        label: 'Aberto' },
    { value: 'in_progress', label: 'Em análise' },
    { value: 'resolved',    label: 'Resolvido' },
  ];

  const thS = { padding: '8px 12px', textAlign: 'left', fontSize: 10.5, fontFamily: 'var(--dgd-font-mono, monospace)', color: 'var(--dgd-fg-3, #94a3b8)', letterSpacing: '0.06em', textTransform: 'uppercase', background: 'var(--dgd-bg-surface, #f8fafc)', borderBottom: '1px solid var(--dgd-border-1, #e2e8f0)', fontWeight: 600 };
  const tdS = { padding: '10px 12px', fontSize: 12.5, borderBottom: '1px solid var(--dgd-border-1, #e2e8f0)', verticalAlign: 'top' };

  return (
    <div style={{ padding: '24px 28px', maxWidth: 1100, margin: '0 auto' }}>
      {/* Header */}
      <div style={{ marginBottom: 20 }}>
        <div style={{ fontSize: 10, fontFamily: 'var(--dgd-font-mono, monospace)', color: 'var(--dgd-fg-3, #94a3b8)', letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 4 }}>SISTEMA · TICKETS</div>
        <h1 style={{ margin: 0, fontSize: 22, fontWeight: 700, color: 'var(--dgd-fg-1, #1e293b)' }}>Bug Reports &amp; Feedback</h1>
      </div>

      {/* Contadores */}
      <div style={{ display: 'flex', gap: 12, marginBottom: 20, flexWrap: 'wrap' }}>
        {[
          { label: 'Total', value: counts.total, color: '#1e293b' },
          { label: 'Abertos', value: counts.open, color: '#dc2626' },
          { label: 'Em análise', value: counts.in_progress, color: '#d97706' },
          { label: 'Resolvidos', value: counts.resolved, color: '#16a34a' },
        ].map(c => (
          <div key={c.label} style={{ background: 'var(--dgd-bg-surface, #f8fafc)', border: '1px solid var(--dgd-border-1, #e2e8f0)', borderRadius: 8, padding: '12px 18px', minWidth: 90 }}>
            <div style={{ fontSize: 22, fontWeight: 700, color: c.color, fontFamily: 'var(--dgd-font-mono, monospace)' }}>{c.value}</div>
            <div style={{ fontSize: 11, color: 'var(--dgd-fg-3, #94a3b8)', marginTop: 2 }}>{c.label}</div>
          </div>
        ))}
        <button onClick={load} style={{ marginLeft: 'auto', padding: '8px 14px', borderRadius: 6, border: '1px solid var(--dgd-border-1, #e2e8f0)', background: 'transparent', fontSize: 12, cursor: 'pointer', color: 'var(--dgd-fg-2, #64748b)' }}>Actualizar</button>
      </div>

      {/* Filtros */}
      <div style={{ display: 'flex', gap: 8, marginBottom: 16, flexWrap: 'wrap' }}>
        {['all','open','in_progress','resolved'].map(s => (
          <button key={s} onClick={() => setFS(s)} style={{ padding: '4px 12px', borderRadius: 99, border: '1px solid', fontSize: 12, cursor: 'pointer', fontWeight: filterStatus === s ? 700 : 400, background: filterStatus === s ? '#112954' : 'transparent', color: filterStatus === s ? '#fff' : 'var(--dgd-fg-2, #64748b)', borderColor: filterStatus === s ? '#112954' : 'var(--dgd-border-1, #e2e8f0)' }}>
            {s === 'all' ? 'Todos' : s === 'open' ? 'Abertos' : s === 'in_progress' ? 'Em análise' : 'Resolvidos'}
          </button>
        ))}
        <div style={{ width: 1, background: 'var(--dgd-border-1, #e2e8f0)', margin: '0 4px' }} />
        {['all','low','medium','high'].map(s => (
          <button key={s} onClick={() => setFSev(s)} style={{ padding: '4px 12px', borderRadius: 99, border: '1px solid', fontSize: 12, cursor: 'pointer', fontWeight: filterSev === s ? 700 : 400, background: filterSev === s ? '#334155' : 'transparent', color: filterSev === s ? '#fff' : 'var(--dgd-fg-2, #64748b)', borderColor: filterSev === s ? '#334155' : 'var(--dgd-border-1, #e2e8f0)' }}>
            {s === 'all' ? 'Todas' : s === 'low' ? 'Baixa' : s === 'medium' ? 'Média' : 'Alta'}
          </button>
        ))}
      </div>

      {/* Tabela */}
      {loading ? (
        <div style={{ padding: 40, textAlign: 'center', color: 'var(--dgd-fg-3, #94a3b8)', fontSize: 13 }}>A carregar...</div>
      ) : filtered.length === 0 ? (
        <div style={{ padding: 40, textAlign: 'center', color: 'var(--dgd-fg-3, #94a3b8)', fontSize: 13 }}>Sem tickets para os filtros seleccionados.</div>
      ) : (
        <div style={{ border: '1px solid var(--dgd-border-1, #e2e8f0)', borderRadius: 8, overflow: 'hidden' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead>
              <tr>
                <th style={thS}>Data</th>
                <th style={thS}>Utilizador</th>
                <th style={thS}>Ecrã</th>
                <th style={thS}>Título</th>
                <th style={thS}>Sev.</th>
                <th style={thS}>Status</th>
              </tr>
            </thead>
            <tbody>
              {filtered.map(t => {
                const sev = sevBadge(t.severity);
                const isExp = expanded === t.id;
                return (
                  <React.Fragment key={t.id}>
                    <tr
                      onClick={() => setExpanded(isExp ? null : t.id)}
                      style={{ cursor: 'pointer', background: isExp ? 'color-mix(in oklch,#112954 4%,transparent)' : 'transparent' }}
                      onMouseEnter={e => { if (!isExp) e.currentTarget.style.background = 'var(--dgd-bg-surface, #f8fafc)'; }}
                      onMouseLeave={e => { if (!isExp) e.currentTarget.style.background = 'transparent'; }}
                    >
                      <td style={{ ...tdS, whiteSpace: 'nowrap', color: 'var(--dgd-fg-3, #94a3b8)', fontFamily: 'var(--dgd-font-mono, monospace)', fontSize: 11.5 }}>
                        {new Date(t.created_at).toLocaleDateString('pt-PT', { day: '2-digit', month: '2-digit' })}<br/>
                        {new Date(t.created_at).toLocaleTimeString('pt-PT', { hour: '2-digit', minute: '2-digit' })}
                      </td>
                      <td style={tdS}>
                        <div style={{ fontWeight: 500, fontSize: 12.5 }}>{t.user_name}</div>
                        <div style={{ fontSize: 11, color: 'var(--dgd-fg-3, #94a3b8)' }}>{t.user_email}</div>
                      </td>
                      <td style={{ ...tdS, fontSize: 11, fontFamily: 'var(--dgd-font-mono, monospace)', color: 'var(--dgd-fg-3, #94a3b8)', maxWidth: 120, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{(t.screen || '—').replace('#screen=', '')}</td>
                      <td style={{ ...tdS, maxWidth: 280 }}>
                        <div style={{ fontWeight: 500, fontSize: 12.5, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{t.title || '—'}</div>
                      </td>
                      <td style={tdS}>
                        <span style={{ display: 'inline-block', padding: '2px 8px', borderRadius: 99, fontSize: 11, fontWeight: 600, background: sev.bg, color: sev.color }}>{sev.label}</span>
                      </td>
                      <td style={tdS} onClick={e => e.stopPropagation()}>
                        <select
                          value={t.status}
                          disabled={updating === t.id}
                          onChange={e => updateStatus(t.id, e.target.value)}
                          style={{ fontSize: 12, padding: '3px 6px', border: '1px solid var(--dgd-border-1, #e2e8f0)', borderRadius: 4, background: 'transparent', cursor: 'pointer', color: 'var(--dgd-fg-1, #1e293b)' }}
                        >
                          {statusOpts.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
                        </select>
                      </td>
                    </tr>
                    {isExp && (
                      <tr style={{ background: 'color-mix(in oklch,#112954 3%,transparent)' }}>
                        <td colSpan={6} style={{ padding: '12px 16px', borderBottom: '1px solid var(--dgd-border-1, #e2e8f0)' }}>
                          {t.description && t.description !== t.raw_text_preview && (
                            <div style={{ marginBottom: 10 }}>
                              <div style={{ fontSize: 10.5, fontFamily: 'var(--dgd-font-mono, monospace)', color: 'var(--dgd-fg-3, #94a3b8)', textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 4 }}>Interpretação Claude</div>
                              <div style={{ fontSize: 13, color: 'var(--dgd-fg-1, #1e293b)', lineHeight: 1.5 }}>{t.description}</div>
                            </div>
                          )}
                          <div>
                            <div style={{ fontSize: 10.5, fontFamily: 'var(--dgd-font-mono, monospace)', color: 'var(--dgd-fg-3, #94a3b8)', textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 4 }}>Texto original</div>
                            <div style={{ fontSize: 13, color: 'var(--dgd-fg-2, #64748b)', lineHeight: 1.5, whiteSpace: 'pre-wrap' }}>{t.raw_text_preview}</div>
                          </div>
                        </td>
                      </tr>
                    )}
                  </React.Fragment>
                );
              })}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
};

window.SistemaTickets = SistemaTickets;
