// Zakładka „Aktywni kierowcy" — kto się odbił danego dnia (na magazynie) vs nieodbity (poza magazynem).

function ActiveDriversTab() {
  const todayInput = (() => {
    const d = new Date();
    const p = (x) => String(x).padStart(2, '0');
    return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`;
  })();

  const [date,    setDate]    = React.useState(todayInput);
  const [drivers, setDrivers] = React.useState([]);
  const [starts,  setStarts]  = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [errMsg,  setErrMsg]  = React.useState(null);
  const [marks,   setMarks]   = React.useState({}); // userId -> 'wolne'

  const load = React.useCallback(async () => {
    setLoading(true);
    try {
      const [d, a, m] = await Promise.all([api.getDrivers(), api.getAttendance(date), api.getAttendanceMarks(date)]);
      setDrivers(d);
      setStarts(Array.isArray(a) ? a : []);
      const mm = {};
      (Array.isArray(m) ? m : []).forEach(x => { if (x.userId != null) mm[x.userId] = x.mark; });
      setMarks(mm);
      setErrMsg(null);
    } catch (e) {
      if (e.status === 401) { api.logout(); window.location.reload(); return; }
      setErrMsg(e.message);
    } finally {
      setLoading(false);
    }
  }, [date]);

  // Klik w status: „Poza magazynem" ⇄ „Wolne" (gdy „Na magazynie" — zablokowane)
  const toggleMark = async (row) => {
    if (row.checkedIn) return;
    const next = row.status === 'wolne' ? null : 'wolne';
    setMarks(prev => { const copy = { ...prev }; if (next) copy[row.id] = next; else delete copy[row.id]; return copy; });
    try {
      await api.setAttendanceMark(row.id, date, next);
    } catch (e) {
      setErrMsg(e.message);
      load(); // wycofaj optymistyczną zmianę
    }
  };

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

  // userId -> godzina odbicia (start pracy)
  const startMap = React.useMemo(() => {
    const m = {};
    starts.forEach(s => { if (s.userId != null && !m[s.userId]) m[s.userId] = s.startedAt; });
    return m;
  }, [starts]);

  // Pokazujemy aktywnych kierowców (rola kierowca, konto aktywne)
  const fleet = drivers.filter(d => d.role === 'kierowca' && d.active);
  const rows = fleet.map(d => {
    const checkedIn = !!startMap[d.id];
    const status = checkedIn ? 'na_magazynie' : (marks[d.id] === 'wolne' ? 'wolne' : 'poza');
    return { id: d.id, name: d.name, checkedIn, time: startMap[d.id] || null, status };
  });
  const { sorted, sortKey, sortDir, toggleSort } = useSort(rows, 'name');

  const naMagazynie   = rows.filter(r => r.checkedIn).length;
  const pozaMagazynem = rows.length - naMagazynie;

  return (
    <>
      <PageHeader
        title="Aktywni kierowcy"
        subtitle="Kto się odbił w wybranym dniu"
        action={<DatePicker value={date} onChange={setDate} />}
      />
      <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>
        )}

        {/* Kafelki podsumowania */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginBottom: 16 }}>
          <TotalCard label="Na magazynie (odbici)" value={naMagazynie} highlight />
          <TotalCard label="Poza magazynem (nieodbici)" value={pozaMagazynem} />
        </div>

        {/* Lista kierowców */}
        <div style={cardStyle}>
          <div style={{ padding: '14px 16px', borderBottom: '1px solid #f4f4f5', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <div style={{ fontSize: 14, fontWeight: 700, color: '#18181b' }}>Kierowcy ({rows.length})</div>
            <div style={{ fontSize: 12, color: '#71717a', fontFamily: 'JetBrains Mono, monospace' }}>{fmtDate(date + 'T00:00:00')}</div>
          </div>
          <table style={tableStyle}>
            <thead>
              <tr>
                <SortTh label="Kierowca" k="name"      cur={sortKey} dir={sortDir} onSort={toggleSort} />
                <SortTh label="Godzina"  k="time"      cur={sortKey} dir={sortDir} onSort={toggleSort} />
                <SortTh label="Status"   k="status"    cur={sortKey} dir={sortDir} onSort={toggleSort} />
              </tr>
            </thead>
            <tbody>
              {sorted.map(r => (
                <tr key={r.id} style={trStyle}>
                  <td style={tdStyle}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                      <Avatar name={r.name} size={30} />
                      <span style={{ fontWeight: 600 }}>{r.name}</span>
                    </div>
                  </td>
                  <td style={{ ...tdStyle, fontFamily: 'JetBrains Mono, monospace', fontSize: 13 }}>
                    {r.time ? fmtTime(r.time) : <span style={{ color: '#a1a1aa' }}>—</span>}
                  </td>
                  <td style={tdStyle}>
                    {r.status === 'na_magazynie' ? (
                      <span title="Kierowca się odbił — status zablokowany" style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '3px 9px 3px 7px', borderRadius: 999, background: '#dcfce7', color: '#166534', fontSize: 12, fontWeight: 600 }}>
                        <span style={{ width: 6, height: 6, borderRadius: 3, background: '#22c55e' }} />Na magazynie
                      </span>
                    ) : r.status === 'wolne' ? (
                      <button type="button" onClick={() => toggleMark(r)} title="Kliknij, aby cofnąć na „Poza magazynem”"
                        style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '3px 9px 3px 7px', borderRadius: 999, background: '#dbeafe', color: '#1e40af', fontSize: 12, fontWeight: 600, border: 'none', cursor: 'pointer', fontFamily: 'inherit' }}>
                        <span style={{ width: 6, height: 6, borderRadius: 3, background: '#3b82f6' }} />Wolne
                      </button>
                    ) : (
                      <button type="button" onClick={() => toggleMark(r)} title="Kliknij, aby ustawić „Wolne”"
                        style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '3px 9px 3px 7px', borderRadius: 999, background: '#f4f4f5', color: '#52525b', fontSize: 12, fontWeight: 600, border: 'none', cursor: 'pointer', fontFamily: 'inherit' }}>
                        <span style={{ width: 6, height: 6, borderRadius: 3, background: '#a1a1aa' }} />Poza magazynem
                      </button>
                    )}
                  </td>
                </tr>
              ))}
              {rows.length === 0 && (
                <tr><td colSpan={3} style={{ ...tdStyle, textAlign: 'center', color: '#a1a1aa', padding: 40 }}>{loading ? 'Ładowanie…' : 'Brak aktywnych kierowców'}</td></tr>
              )}
            </tbody>
          </table>
        </div>
      </div>
    </>
  );
}

Object.assign(window, { ActiveDriversTab });
