// Zakładka Zgłoszenia — tylko admin

function ReportsTab() {
  const [reports,    setReports]    = React.useState([]);
  const [loading,    setLoading]    = React.useState(true);
  const [typeFilter, setTypeFilter] = React.useState('all');
  const [statusFilter, setStatusFilter] = React.useState('all');
  const [selected,   setSelected]   = React.useState(null); // szczegóły
  const { sorted, sortKey, sortDir, toggleSort } = useSort(reports, 'datetime', 'desc');

  const loadReports = React.useCallback(async () => {
    setLoading(true);
    try {
      const params = {};
      if (typeFilter   !== 'all') params.type   = typeFilter;
      if (statusFilter !== 'all') params.status = statusFilter;
      const data = await api.getReports(params);
      setReports(data);
    } catch (e) { if (e.status === 401) { api.logout(); window.location.reload(); } }
    finally { setLoading(false); }
  }, [typeFilter, statusFilter]);

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

  const changeStatus = async (id, status) => {
    await api.updateReport(id, { status });
    await loadReports();
  };

  const deleteReport = async (id) => {
    if (!confirm('Usunąć zgłoszenie?')) return;
    await api.deleteReport(id);
    setSelected(null);
    await loadReports();
  };

  const TYPE_COLORS = {
    usterka:     { bg: '#fee2e2', fg: '#991b1b', dot: '#ef4444' },
    magazyn_in:  { bg: '#dbeafe', fg: '#1e40af', dot: '#3b82f6' },
    magazyn_out: { bg: '#dcfce7', fg: '#166534', dot: '#22c55e' },
  };
  const STATUS_COLORS = {
    nowe:        { bg: '#fef3c7', fg: '#854d0e' },
    w_trakcie:   { bg: '#dbeafe', fg: '#1e40af' },
    'zamknięte': { bg: '#f4f4f5', fg: '#71717a' },
  };

  const TypePill = ({ type, label }) => {
    const c = TYPE_COLORS[type] || { bg: '#f4f4f5', fg: '#52525b', dot: '#a1a1aa' };
    return (
      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, padding: '3px 9px 3px 7px', borderRadius: 999, background: c.bg, color: c.fg, fontSize: 12, fontWeight: 600 }}>
        <span style={{ width: 6, height: 6, borderRadius: 3, background: c.dot, flexShrink: 0 }} />
        {label}
      </span>
    );
  };

  const StatusBadge = ({ status }) => {
    const c = STATUS_COLORS[status] || STATUS_COLORS.nowe;
    const labels = { nowe: 'Nowe', w_trakcie: 'W trakcie', 'zamknięte': 'Zamknięte' };
    return <span style={{ padding: '3px 10px', borderRadius: 999, background: c.bg, color: c.fg, fontSize: 12, fontWeight: 700 }}>{labels[status] || status}</span>;
  };

  const filtered = sorted;

  return (
    <>
      <PageHeader
        title="Zgłoszenia"
        subtitle={`${reports.length} zgłoszeń łącznie`}
        action={
          <button onClick={loadReports} style={{ ...btnGhostStyle }}>
            <Icon name="history" size={15} /> Odśwież
          </button>
        }
      />
      <div style={{ padding: 32, overflow: 'auto', flex: 1 }}>
        {/* Filtry */}
        <div style={{ display: 'flex', gap: 12, marginBottom: 16 }}>
          <div style={{ width: 180 }}>
            <Select value={typeFilter} onChange={e => setTypeFilter(e.target.value)}>
              <option value="all">Wszystkie typy</option>
              <option value="usterka">Usterka</option>
              <option value="magazyn_in">Oddanie do magazynu</option>
              <option value="magazyn_out">Pobranie z magazynu</option>
            </Select>
          </div>
          <div style={{ width: 160 }}>
            <Select value={statusFilter} onChange={e => setStatusFilter(e.target.value)}>
              <option value="all">Wszystkie statusy</option>
              <option value="nowe">Nowe</option>
              <option value="w_trakcie">W trakcie</option>
              <option value="zamknięte">Zamknięte</option>
            </Select>
          </div>
          <div style={{ marginLeft: 'auto', fontSize: 12, color: '#71717a', fontFamily: 'JetBrains Mono, monospace', display: 'flex', alignItems: 'center' }}>
            {filtered.length} wyników
          </div>
        </div>

        {/* Tabela */}
        <div style={cardStyle}>
          <table style={tableStyle}>
            <thead>
              <tr>
                <SortTh label="Data / Godz."  k="datetime"    cur={sortKey} dir={sortDir} onSort={toggleSort} />
                <SortTh label="Typ"           k="typeLabel"   cur={sortKey} dir={sortDir} onSort={toggleSort} />
                <SortTh label="Kierowca"      k="driverName"  cur={sortKey} dir={sortDir} onSort={toggleSort} />
                <SortTh label="Pojazd"        k="vehiclePlate" cur={sortKey} dir={sortDir} onSort={toggleSort} />
                <SortTh label="Status"        k="status"      cur={sortKey} dir={sortDir} onSort={toggleSort} />
                <th style={{ ...thStyle, textAlign: 'right' }}>Akcje</th>
              </tr>
            </thead>
            <tbody>
              {loading && (
                <tr><td colSpan={6} style={{ ...tdStyle, textAlign: 'center', color: '#a1a1aa', padding: 40 }}>Ładowanie…</td></tr>
              )}
              {!loading && filtered.length === 0 && (
                <tr><td colSpan={6} style={{ ...tdStyle, textAlign: 'center', color: '#a1a1aa', padding: 40 }}>Brak zgłoszeń</td></tr>
              )}
              {!loading && filtered.map((r) => (
                <tr key={r.id} style={{ ...trStyle, cursor: 'pointer' }}
                  onClick={() => setSelected(r)}
                  onMouseEnter={e => e.currentTarget.style.background = '#fafaf9'}
                  onMouseLeave={e => e.currentTarget.style.background = ''}>
                  <td style={{ ...tdStyle, fontFamily: 'JetBrains Mono, monospace', fontSize: 12 }}>
                    <div>{fmtDate(r.datetime)}</div>
                    <div style={{ color: '#71717a' }}>{fmtTime(r.datetime)}</div>
                  </td>
                  <td style={tdStyle}><TypePill type={r.type} label={r.typeLabel} /></td>
                  <td style={tdStyle}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                      <Avatar name={r.driverName} size={28} />
                      <span style={{ fontSize: 13, fontWeight: 600 }}>{r.driverName}</span>
                    </div>
                  </td>
                  <td style={tdStyle}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                      <Plate size="sm">{r.vehiclePlate}</Plate>
                      <span style={{ fontSize: 12, color: '#71717a' }}>{r.vehicleBrand} {r.vehicleModel}</span>
                    </div>
                  </td>
                  <td style={tdStyle}><StatusBadge status={r.status} /></td>
                  <td style={{ ...tdStyle, textAlign: 'right' }}>
                    <div style={{ display: 'inline-flex', gap: 4 }} onClick={e => e.stopPropagation()}>
                      <Btn variant="ghost" onClick={() => setSelected(r)}>Szczegóły</Btn>
                      <Btn variant="ghost" icon="trash" onClick={() => deleteReport(r.id)} style={{ color: '#dc2626' }} />
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* Modal szczegółów */}
      {selected && (
        <ReportDetail
          report={selected}
          onClose={() => setSelected(null)}
          onStatusChange={changeStatus}
          onDelete={deleteReport}
        />
      )}
    </>
  );
}


function PhotoThumb({ src }) {
  const [loaded, setLoaded] = React.useState(false);
  const [error,  setError]  = React.useState(false);
  return (
    <a href={src} target="_blank" rel="noopener noreferrer" style={{ display: 'block', aspectRatio: '1', borderRadius: 6, overflow: 'hidden', border: '1px solid #e7e5e4', background: '#f4f4f5', position: 'relative' }}>
      {!loaded && !error && (
        <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', background: '#f4f4f5' }}>
          <div style={{ width: 24, height: 24, border: '3px solid #e7e5e4', borderTopColor: '#f59e0b', borderRadius: '50%', animation: 'tf-spin 0.7s linear infinite' }} />
        </div>
      )}
      {error && (
        <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', background: '#fafaf9', color: '#a1a1aa', fontSize: 11 }}>Błąd</div>
      )}
      <img
        src={src}
        alt="Zdjęcie zgłoszenia"
        onLoad={() => setLoaded(true)}
        onError={() => setError(true)}
        style={{ width: '100%', height: '100%', objectFit: 'cover', cursor: 'pointer', opacity: loaded ? 1 : 0, transition: 'opacity .2s' }}
      />
    </a>
  );
}

function ReportDetail({ report: r, onClose, onStatusChange, onDelete }) {
  const TYPE_LABELS = { usterka: 'Usterka', magazyn_in: 'Oddanie do magazynu', magazyn_out: 'Pobranie z magazynu' };
  const photos = Array.isArray(r.photoKeys) ? r.photoKeys : JSON.parse(r.photoKeys || '[]');
  const API_URL = 'https://tankfood-api.taxifoodpoznan.workers.dev';

  return (
    <div onClick={onClose} style={{ position: 'absolute', inset: 0, background: 'rgba(12,10,9,0.45)', backdropFilter: 'blur(2px)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 50, padding: 24 }}>
      <div onClick={e => e.stopPropagation()} style={{ background: '#fff', borderRadius: 8, width: 560, maxHeight: '90%', overflow: 'auto', boxShadow: '0 24px 64px rgba(0,0,0,0.2)' }}>
        {/* Header */}
        <div style={{ padding: '20px 24px 16px', borderBottom: '1px solid #f1f0ee', display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between' }}>
          <div>
            <div style={{ fontSize: 17, fontWeight: 700, color: '#18181b' }}>Zgłoszenie #{r.id}</div>
            <div style={{ fontSize: 13, color: '#71717a', marginTop: 2 }}>{TYPE_LABELS[r.type]} • {fmtDateTime(r.datetime)}</div>
          </div>
          <button onClick={onClose} style={{ ...btnGhostStyle, padding: 6 }}><Icon name="x" size={18} /></button>
        </div>

        <div style={{ padding: 24, display: 'flex', flexDirection: 'column', gap: 20 }}>
          {/* Kierowca + pojazd */}
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            <div style={{ padding: 14, background: '#fafaf9', borderRadius: 8, border: '1px solid #e7e5e4' }}>
              <div style={{ fontSize: 11, fontWeight: 700, color: '#71717a', textTransform: 'uppercase', letterSpacing: 0.8, marginBottom: 8 }}>Kierowca</div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <Avatar name={r.driverName} size={32} />
                <span style={{ fontWeight: 600, fontSize: 14 }}>{r.driverName}</span>
              </div>
            </div>
            <div style={{ padding: 14, background: '#fafaf9', borderRadius: 8, border: '1px solid #e7e5e4' }}>
              <div style={{ fontSize: 11, fontWeight: 700, color: '#71717a', textTransform: 'uppercase', letterSpacing: 0.8, marginBottom: 8 }}>Pojazd</div>
              <Plate>{r.vehiclePlate}</Plate>
              <div style={{ fontSize: 12, color: '#71717a', marginTop: 4 }}>{r.vehicleBrand} {r.vehicleModel}</div>
            </div>
          </div>

          {/* Opis */}
          {r.description && (
            <div>
              <div style={{ fontSize: 11, fontWeight: 700, color: '#71717a', textTransform: 'uppercase', letterSpacing: 0.8, marginBottom: 8 }}>Opis</div>
              <div style={{ padding: 14, background: '#fafaf9', borderRadius: 8, border: '1px solid #e7e5e4', fontSize: 14, color: '#18181b', lineHeight: 1.6 }}>
                {r.description || <span style={{ color: '#a1a1aa', fontStyle: 'italic' }}>Brak opisu</span>}
              </div>
            </div>
          )}

          {/* Zdjęcia */}
          {photos.length > 0 && (
            <div>
              <div style={{ fontSize: 11, fontWeight: 700, color: '#71717a', textTransform: 'uppercase', letterSpacing: 0.8, marginBottom: 8 }}>
                Zdjęcia ({photos.length})
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8 }}>
                {photos.map((key, i) => (
                  <PhotoThumb key={i} src={`${API_URL}/api/reports/photo/${key}`} />
                ))}
              </div>
            </div>
          )}

          {/* Status */}
          <div>
            <div style={{ fontSize: 11, fontWeight: 700, color: '#71717a', textTransform: 'uppercase', letterSpacing: 0.8, marginBottom: 8 }}>Zmień status</div>
            <div style={{ display: 'flex', gap: 8 }}>
              {['nowe','w_trakcie','zamknięte'].map(s => {
                const labels = { nowe: 'Nowe', w_trakcie: 'W trakcie', 'zamknięte': 'Zamknięte' };
                return (
                  <button key={s} onClick={() => onStatusChange(r.id, s)}
                    style={{ ...btnSecondaryStyle, background: r.status === s ? '#18181b' : '#fff', color: r.status === s ? '#fafaf9' : '#18181b', fontSize: 13 }}>
                    {labels[s]}
                  </button>
                );
              })}
            </div>
          </div>
        </div>

        {/* Footer */}
        <div style={{ padding: '14px 24px', borderTop: '1px solid #f1f0ee', display: 'flex', justifyContent: 'space-between' }}>
          <Btn variant="danger" icon="trash" onClick={() => onDelete(r.id)}>Usuń zgłoszenie</Btn>
          <Btn variant="secondary" onClick={onClose}>Zamknij</Btn>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ReportsTab, ReportDetail });
