// Zakładka „Urlopy" — kalendarz wniosków + zatwierdzanie (admin)

const LEAVE_STATUS = {
  pending:  { l: 'Oczekujący',   bg: '#fef3c7', fg: '#854d0e' },
  approved: { l: 'Zatwierdzony', bg: '#dcfce7', fg: '#166534' },
  rejected: { l: 'Odrzucony',    bg: '#fee2e2', fg: '#991b1b' },
};
const LEAVE_DOW = ['Pn', 'Wt', 'Śr', 'Cz', 'Pt', 'So', 'Nd'];
const LEAVE_MONTHS = ['Styczeń', 'Luty', 'Marzec', 'Kwiecień', 'Maj', 'Czerwiec', 'Lipiec', 'Sierpień', 'Wrzesień', 'Październik', 'Listopad', 'Grudzień'];
const lpad = (n) => String(n).padStart(2, '0');
const leaveYmd = (d) => `${d.getFullYear()}-${lpad(d.getMonth() + 1)}-${lpad(d.getDate())}`;
const leaveNavBtn = { width: 34, height: 34, border: '1px solid #e7e5e4', background: '#fff', borderRadius: 6, cursor: 'pointer', fontSize: 18, color: '#52525b', fontFamily: 'inherit' };

function LeaveTab() {
  const [view, setView] = React.useState('month'); // month | week | day
  const [anchor, setAnchor] = React.useState(() => leaveYmd(new Date()));
  const [rangeLeaves, setRangeLeaves] = React.useState([]);
  const [pending, setPending] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [errMsg, setErrMsg] = React.useState(null);

  const range = React.useMemo(() => {
    const a = new Date(anchor + 'T12:00:00');
    if (view === 'day') return { from: anchor, to: anchor };
    if (view === 'week') {
      const dow = (a.getDay() + 6) % 7;
      const mon = new Date(a); mon.setDate(a.getDate() - dow);
      const sun = new Date(mon); sun.setDate(mon.getDate() + 6);
      return { from: leaveYmd(mon), to: leaveYmd(sun) };
    }
    const first = new Date(a.getFullYear(), a.getMonth(), 1);
    const last = new Date(a.getFullYear(), a.getMonth() + 1, 0);
    return { from: leaveYmd(first), to: leaveYmd(last) };
  }, [anchor, view]);

  const load = React.useCallback(async () => {
    setLoading(true);
    try {
      const [rl, pl] = await Promise.all([
        api.getLeaves({ from: range.from, to: range.to }),
        api.getLeaves({ status: 'pending' }),
      ]);
      setRangeLeaves(Array.isArray(rl) ? rl : []);
      setPending(Array.isArray(pl) ? pl : []);
      setErrMsg(null);
    } catch (e) {
      if (e.status === 401) { api.logout(); window.location.reload(); return; }
      setErrMsg(e.message);
    } finally { setLoading(false); }
  }, [range.from, range.to]);
  React.useEffect(() => { load(); }, [load]);

  const decide = async (id, status) => {
    try { await api.updateLeave(id, status); await load(); }
    catch (e) { alert('Błąd: ' + e.message); }
  };

  const cancelLeave = async (l) => {
    const range = l.dateFrom === l.dateTo
      ? fmtDate(l.dateFrom + 'T00:00:00')
      : `${fmtDate(l.dateFrom + 'T00:00:00')} – ${fmtDate(l.dateTo + 'T00:00:00')}`;
    if (!confirm(`Anulować urlop: ${l.driverName} (${range})?`)) return;
    try { await api.deleteLeave(l.id); await load(); }
    catch (e) { alert('Błąd: ' + e.message); }
  };

  const leavesOn = (dayStr) => rangeLeaves.filter(l => l.dateFrom <= dayStr && l.dateTo >= dayStr);

  const shift = (dir) => {
    const a = new Date(anchor + 'T12:00:00');
    if (view === 'day') a.setDate(a.getDate() + dir);
    else if (view === 'week') a.setDate(a.getDate() + dir * 7);
    else a.setMonth(a.getMonth() + dir);
    setAnchor(leaveYmd(a));
  };

  const headerLabel = () => {
    const a = new Date(anchor + 'T12:00:00');
    if (view === 'day') return fmtDate(anchor + 'T00:00:00');
    if (view === 'week') return `${fmtDate(range.from + 'T00:00:00')} – ${fmtDate(range.to + 'T00:00:00')}`;
    return `${LEAVE_MONTHS[a.getMonth()]} ${a.getFullYear()}`;
  };

  const cells = (() => {
    if (view === 'day') return [anchor];
    const from = new Date(range.from + 'T12:00:00');
    const to = new Date(range.to + 'T12:00:00');
    const arr = [];
    if (view === 'month') { const lead = (from.getDay() + 6) % 7; for (let i = 0; i < lead; i++) arr.push(null); }
    const d = new Date(from);
    while (d <= to) { arr.push(leaveYmd(d)); d.setDate(d.getDate() + 1); }
    return arr;
  })();

  const todayStr = leaveYmd(new Date());

  return (
    <>
      <PageHeader title="Urlopy" subtitle="Wnioski urlopowe kurierów" />
      <div style={{ padding: 32, overflow: 'auto', flex: 1 }}>
        {errMsg && <div style={{ marginBottom: 16, padding: 12, background: '#fee2e2', color: '#991b1b', borderRadius: 8, fontSize: 13 }}>Błąd: {errMsg}</div>}

        {/* Nawigacja + przełącznik widoku */}
        <div style={{ ...cardStyle, padding: '14px 16px', marginBottom: 16, display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap' }}>
          <button onClick={() => shift(-1)} style={leaveNavBtn}>‹</button>
          <div style={{ fontSize: 15, fontWeight: 700, minWidth: 200, textAlign: 'center' }}>{headerLabel()}</div>
          <button onClick={() => shift(1)} style={leaveNavBtn}>›</button>
          <button onClick={() => setAnchor(todayStr)} style={{ ...btnGhostStyle, fontSize: 13 }}>Dziś</button>
          <div style={{ marginLeft: 'auto', display: 'flex', gap: 6 }}>
            {[['month', 'Miesiąc'], ['week', 'Tydzień'], ['day', 'Dzień']].map(([v, l]) => (
              <button key={v} onClick={() => setView(v)} style={{
                padding: '8px 14px', border: `1px solid ${view === v ? '#f59e0b' : '#e4e4e7'}`, background: view === v ? '#fef3c7' : '#fff',
                color: view === v ? '#854d0e' : '#52525b', fontWeight: view === v ? 700 : 500, fontSize: 13, borderRadius: 6, cursor: 'pointer', fontFamily: 'inherit',
              }}>{l}</button>
            ))}
          </div>
        </div>

        {/* Kalendarz */}
        <div style={{ ...cardStyle, marginBottom: 16, padding: 12 }}>
          {view !== 'day' && (
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 4, marginBottom: 6 }}>
              {LEAVE_DOW.map(w => <div key={w} style={{ textAlign: 'center', fontSize: 11, fontWeight: 700, color: '#a1a1aa' }}>{w}</div>)}
            </div>
          )}
          <div style={{ display: 'grid', gridTemplateColumns: view === 'day' ? '1fr' : 'repeat(7, 1fr)', gap: 4 }}>
            {cells.map((day, i) => {
              if (day === null) return <div key={`e${i}`} />;
              const items = leavesOn(day);
              const dd = new Date(day + 'T12:00:00');
              return (
                <div key={day} style={{ minHeight: view === 'day' ? 'auto' : 90, border: '1px solid #f4f4f5', borderRadius: 8, padding: 6, background: day === todayStr ? '#fffbeb' : '#fff' }}>
                  <div style={{ fontSize: 11, fontWeight: 700, color: '#71717a', marginBottom: 4, fontFamily: 'JetBrains Mono, monospace' }}>{view === 'day' ? fmtDate(day + 'T00:00:00') : dd.getDate()}</div>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
                    {items.map(l => {
                      const s = LEAVE_STATUS[l.status] || LEAVE_STATUS.pending;
                      return <button key={l.id} type="button" onClick={() => cancelLeave(l)} title={`${l.driverName} • ${s.l} — kliknij, aby anulować`} style={{ display: 'block', width: '100%', textAlign: 'left', fontSize: 11, fontWeight: 600, padding: '2px 6px', borderRadius: 4, border: 'none', cursor: 'pointer', background: s.bg, color: s.fg, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', fontFamily: 'inherit' }}>{l.driverName}</button>;
                    })}
                    {items.length === 0 && view === 'day' && <div style={{ fontSize: 12, color: '#a1a1aa' }}>Brak urlopów</div>}
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        {/* Oczekujące wnioski */}
        <div style={cardStyle}>
          <div style={{ padding: '14px 16px', borderBottom: '1px solid #f4f4f5', fontSize: 14, fontWeight: 700 }}>Oczekujące wnioski ({pending.length})</div>
          <div style={{ padding: 12 }}>
            {pending.length === 0 ? (
              <div style={{ padding: 24, textAlign: 'center', color: '#a1a1aa', fontSize: 13 }}>{loading ? 'Ładowanie…' : 'Brak oczekujących wniosków'}</div>
            ) : pending.map(l => (
              <div key={l.id} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 8px', borderBottom: '1px solid #f4f4f5' }}>
                <Avatar name={l.driverName} size={32} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 14, fontWeight: 600 }}>{l.driverName}</div>
                  <div style={{ fontSize: 12, color: '#71717a', fontFamily: 'JetBrains Mono, monospace' }}>
                    {l.dateFrom === l.dateTo ? fmtDate(l.dateFrom + 'T00:00:00') : `${fmtDate(l.dateFrom + 'T00:00:00')} – ${fmtDate(l.dateTo + 'T00:00:00')}`}
                  </div>
                </div>
                <Btn variant="ghost" icon="check" onClick={() => decide(l.id, 'approved')} style={{ color: '#166534' }}>Zatwierdź</Btn>
                <Btn variant="ghost" icon="x" onClick={() => decide(l.id, 'rejected')} style={{ color: '#dc2626' }}>Odrzuć</Btn>
              </div>
            ))}
          </div>
        </div>
      </div>
    </>
  );
}

Object.assign(window, { LeaveTab });
