// Zakładka „Uszkodzenia" — historia zgłoszeń z trasy (uszkodzenia / niezgodności).
// Adres + catering + zdjęcia + status wysyłki maila. Tylko admin.

const INC_EMAIL_BADGE = {
  sent:     { l: 'Wysłany',      bg: '#dcfce7', fg: '#166534' },
  failed:   { l: 'Błąd wysyłki', bg: '#fee2e2', fg: '#991b1b' },
  disabled: { l: 'Mail wyłączony', bg: '#f4f4f5', fg: '#52525b' },
  pending:  { l: 'W toku',       bg: '#fef3c7', fg: '#854d0e' },
};
const INC_STATUS = ['nowe', 'w_trakcie', 'zamknięte'];

function IncidentsTab() {
  const [rows,    setRows]    = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [errMsg,  setErrMsg]  = React.useState(null);
  const [preview, setPreview] = React.useState(null); // url podglądu zdjęcia

  const load = React.useCallback(async () => {
    setLoading(true);
    try {
      setRows(await api.getIncidents({ limit: 500 }));
      setErrMsg(null);
    } catch (e) {
      if (e.status === 401) { api.logout(); window.location.reload(); return; }
      setErrMsg(e.message);
    } finally { setLoading(false); }
  }, []);
  React.useEffect(() => { load(); }, [load]);

  const changeStatus = async (id, status) => {
    try { await api.updateIncident(id, status); await load(); }
    catch (e) { alert('Błąd: ' + e.message); }
  };
  const remove = async (r) => {
    if (!confirm(`Usunąć zgłoszenie: ${r.street} ${r.buildingNo}, ${r.city} (${r.catering})? Zdjęcia zostaną usunięte.`)) return;
    try { await api.deleteIncident(r.id); await load(); }
    catch (e) { alert('Błąd: ' + e.message); }
  };

  const pager = usePagination(rows); // domyślnie 40/stronę (40/100/250 do wyboru)

  return (
    <>
      <PageHeader title="Uszkodzenia" subtitle="Zgłoszenia z trasy: uszkodzenia i niezgodności" />
      <div style={{ padding: 32, overflow: 'auto', flex: 1 }}>
        {errMsg && (
          <div style={{ padding: '10px 16px', background: '#fee2e2', color: '#991b1b', fontSize: 13, borderRadius: 8, marginBottom: 16 }}>
            Błąd: {errMsg} — <button onClick={load} style={{ background: 'none', border: 'none', color: '#991b1b', cursor: 'pointer', textDecoration: 'underline', fontFamily: 'inherit' }}>Spróbuj ponownie</button>
          </div>
        )}

        <div style={cardStyle}>
          <div style={{ padding: '14px 16px', borderBottom: '1px solid #f4f4f5', fontSize: 14, fontWeight: 700 }}>Zgłoszenia ({rows.length})</div>
          <table style={tableStyle}>
            <thead>
              <tr>
                <th style={{ ...tdStyle, fontWeight: 700, color: '#71717a', fontSize: 12 }}>Data</th>
                <th style={{ ...tdStyle, fontWeight: 700, color: '#71717a', fontSize: 12 }}>Kurier</th>
                <th style={{ ...tdStyle, fontWeight: 700, color: '#71717a', fontSize: 12 }}>Adres</th>
                <th style={{ ...tdStyle, fontWeight: 700, color: '#71717a', fontSize: 12 }}>Catering</th>
                <th style={{ ...tdStyle, fontWeight: 700, color: '#71717a', fontSize: 12 }}>Zdjęcia</th>
                <th style={{ ...tdStyle, fontWeight: 700, color: '#71717a', fontSize: 12 }}>Mail</th>
                <th style={{ ...tdStyle, fontWeight: 700, color: '#71717a', fontSize: 12 }}>Status</th>
                <th style={{ ...tdStyle, fontWeight: 700, color: '#71717a', fontSize: 12, textAlign: 'right' }}></th>
              </tr>
            </thead>
            <tbody>
              {pager.pageItems.map(r => {
                const eb = INC_EMAIL_BADGE[r.emailStatus] || INC_EMAIL_BADGE.pending;
                return (
                  <tr key={r.id} style={trStyle}>
                    <td style={{ ...tdStyle, fontFamily: 'JetBrains Mono, monospace', fontSize: 13, whiteSpace: 'nowrap' }}>{fmtDateTime(r.datetime)}</td>
                    <td style={tdStyle}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                        <Avatar name={r.driverName} size={28} /><span style={{ fontWeight: 600 }}>{r.driverName}</span>
                      </div>
                    </td>
                    <td style={tdStyle}>{r.street} {r.buildingNo}<div style={{ fontSize: 12, color: '#71717a' }}>{r.city}</div></td>
                    <td style={{ ...tdStyle, fontWeight: 600 }}>{r.catering}</td>
                    <td style={tdStyle}>
                      <div style={{ display: 'flex', gap: 4 }}>
                        {r.photoKeys.map((k, i) => (
                          <img key={i} src={api.photoUrl(k)} onClick={() => setPreview(api.photoUrl(k))}
                            style={{ width: 38, height: 38, objectFit: 'cover', borderRadius: 6, border: '1px solid #e7e5e4', cursor: 'pointer' }} />
                        ))}
                        {r.photoKeys.length === 0 && <span style={{ color: '#a1a1aa', fontSize: 12 }}>—</span>}
                      </div>
                    </td>
                    <td style={tdStyle}>
                      <span title={r.emailError || ''} style={{ padding: '3px 9px', borderRadius: 999, background: eb.bg, color: eb.fg, fontSize: 12, fontWeight: 700, whiteSpace: 'nowrap' }}>{eb.l}</span>
                    </td>
                    <td style={tdStyle}>
                      <Select value={r.status} onChange={(e) => changeStatus(r.id, e.target.value)} style={{ fontSize: 13 }}>
                        {INC_STATUS.map(s => <option key={s} value={s}>{s.replace('_', ' ')}</option>)}
                      </Select>
                    </td>
                    <td style={{ ...tdStyle, textAlign: 'right' }}>
                      <Btn variant="ghost" icon="trash" onClick={() => remove(r)} style={{ color: '#dc2626' }}>Usuń</Btn>
                    </td>
                  </tr>
                );
              })}
              {rows.length === 0 && (
                <tr><td colSpan={8} style={{ ...tdStyle, textAlign: 'center', color: '#a1a1aa', padding: 40 }}>{loading ? 'Ładowanie…' : 'Brak zgłoszeń'}</td></tr>
              )}
            </tbody>
          </table>
          <PaginationBar
            total={rows.length}
            page={pager.page}
            pageSize={pager.pageSize}
            totalPages={pager.totalPages}
            onPage={pager.setPage}
            onPageSize={pager.setPageSize}
          />
        </div>
      </div>

      {preview && (
        <div onClick={() => setPreview(null)} style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.8)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 100, padding: 40 }}>
          <img src={preview} style={{ maxWidth: '90%', maxHeight: '90%', borderRadius: 10 }} />
        </div>
      )}
    </>
  );
}

Object.assign(window, { IncidentsTab });
