// AllBookings.jsx — full history view of every booking, with collapsible
// Year → Month → Day sidebar, full-text search, multi-day "Multiple" pill,
// and row-click → Modify dialog (reusing the one from Bookings.jsx).

function fmtAllDate(iso) {
  const d = new Date(iso + 'T00:00:00');
  return d.toLocaleDateString('en-GB', { day: '2-digit', month: 'short', weekday: 'short' });
}

function ymOf(iso) { return iso.slice(0, 7); }   // "2026-05"
function yOf(iso)  { return iso.slice(0, 4); }   // "2026"

function categoryIcon(cat) {
  if (cat === 'Mobile Crane')       return Crane;
  if (cat === 'Skylift')            return Truck;
  if (cat === 'Scissor Lift')       return Activity;
  if (cat === 'Lorry Crane')        return Truck;
  if (cat === 'Lorry')              return Truck;
  if (cat === 'Boom Lift')          return Activity;
  if (cat === 'Rough Terrain Crane')return Crane;
  if (cat === 'Cross Rent')         return Layers;
  return Briefcase;
}

function AllBookingsPage({ role, setPage }) {
  const [search, setSearch] = React.useState('');
  // sidebar selection: { kind: 'all' | 'year' | 'month' | 'day', value: '...' }
  const [sel, setSel] = React.useState({ kind: 'all' });
  // expansion state: which years/months are open in sidebar
  const [openYears, setOpenYears] = React.useState({ '2026': true });
  const [openMonths, setOpenMonths] = React.useState({ '2026-05': true });
  const [modifyTarget, setModifyTarget] = React.useState(null);
  const [, forceRender] = React.useReducer(x => x + 1, 0);

  const isAdmin = role === 'Admin';

  // ===== Build sidebar tree from a CONTINUOUS date range =====
  // Show every day from the earliest booking through today + 14 days, so
  // the sidebar shows every date in the calendar — even those without bookings.
  const bookingDates = BOOKINGS.map(b => b.date).filter(Boolean);
  const minDate = bookingDates.length ? bookingDates.reduce((a, b) => a < b ? a : b) : TODAY;
  // Forward window: today + 14 days, but never earlier than the latest booking.
  const maxBooking = bookingDates.length ? bookingDates.reduce((a, b) => a > b ? a : b) : TODAY;
  const todayPlus14 = (() => {
    const d = new Date(TODAY + 'T00:00:00'); d.setDate(d.getDate() + 14);
    return d.toISOString().slice(0, 10);
  })();
  const maxDate = maxBooking > todayPlus14 ? maxBooking : todayPlus14;

  // Generate every ISO date string between minDate and maxDate (inclusive).
  const allDates = (() => {
    const out = [];
    const cur = new Date(minDate + 'T00:00:00');
    const end = new Date(maxDate + 'T00:00:00');
    while (cur <= end) {
      const y = cur.getFullYear();
      const m = String(cur.getMonth() + 1).padStart(2, '0');
      const dd = String(cur.getDate()).padStart(2, '0');
      out.push(`${y}-${m}-${dd}`);
      cur.setDate(cur.getDate() + 1);
    }
    return out.reverse(); // newest first
  })();

  const tree = {}; // { year: { month: [days] } }
  allDates.forEach(d => {
    const y = yOf(d), mo = ymOf(d);
    if (!tree[y]) tree[y] = {};
    if (!tree[y][mo]) tree[y][mo] = [];
    tree[y][mo].push(d);
  });

  // ===== Apply filter by sidebar selection =====
  let filtered = BOOKINGS.slice();
  if (sel.kind === 'year')  filtered = filtered.filter(b => yOf(b.date) === sel.value);
  if (sel.kind === 'month') filtered = filtered.filter(b => ymOf(b.date) === sel.value);
  if (sel.kind === 'day')   filtered = filtered.filter(b => b.date === sel.value);

  // ===== Apply full-text search across all fields =====
  if (search.trim()) {
    const q = search.trim().toLowerCase();
    filtered = filtered.filter(b =>
      Object.values(b).some(v => String(v ?? '').toLowerCase().includes(q))
    );
  }

  // ===== Sort newest first by date =====
  filtered.sort((a, b) => (b.date || '').localeCompare(a.date || ''));

  // Selection label for header
  const selLabel =
    sel.kind === 'all'   ? 'All Bookings' :
    sel.kind === 'year'  ? sel.value :
    sel.kind === 'month' ? new Date(sel.value + '-01T00:00:00').toLocaleDateString('en-GB', {month: 'long', year: 'numeric'}) :
    sel.kind === 'day'   ? fmtAllDate(sel.value) :
    'All Bookings';

  const toggleYear  = (y)  => setOpenYears({ ...openYears,  [y]:  !openYears[y]  });
  const toggleMonth = (mo) => setOpenMonths({ ...openMonths, [mo]: !openMonths[mo] });

  return (
    <div className="page page--allbookings">
      {/* Search + actions bar */}
      <div className="page-actions" style={{marginBottom: 16, gap: 12}}>
        <div style={{position: 'relative', flex: 1, maxWidth: 480}}>
          <Search size={16} style={{position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)', color: 'var(--color-grey-500)'}}/>
          <input value={search} onChange={e => setSearch(e.target.value)}
            placeholder="Search All Bookings — customer, plate, operator, location..."
            className="input" style={{height: 42, paddingLeft: 38, width: '100%', fontSize: 14}}/>
        </div>
        <div style={{display: 'flex', gap: 8}}>
          {isAdmin ? (
            <button className="btn btn--primary" onClick={() => setPage('create')}>
              <Plus size={16}/> Add
            </button>
          ) : null}
        </div>
      </div>

      <div className="ab-layout">
        {/* Sidebar: All / Year ▸ Month ▸ Day */}
        <aside className="ab-sidebar">
          <button
            className={"ab-side-item " + (sel.kind === 'all' ? 'ab-side-item--active' : '')}
            onClick={() => setSel({ kind: 'all' })}>
            <span>All</span>
            <span className="ab-side-count">{BOOKINGS.length}</span>
          </button>
          {Object.entries(tree).sort((a, b) => b[0].localeCompare(a[0])).map(([y, months]) => (
            <div key={y}>
              <button
                className={"ab-side-item " + (sel.kind === 'year' && sel.value === y ? 'ab-side-item--active' : '')}
                onClick={() => { toggleYear(y); setSel({ kind: 'year', value: y }); }}>
                <ChevronRight size={12} style={{transition: 'transform 0.15s', transform: openYears[y] ? 'rotate(90deg)' : 'none'}}/>
                <span>{y}</span>
                <span className="ab-side-count">{Object.values(months).reduce((s, ds) => s + BOOKINGS.filter(b => b.date.startsWith(y) && new Set(ds).has(b.date)).length, 0)}</span>
              </button>
              {openYears[y] ? Object.entries(months).sort((a, b) => b[0].localeCompare(a[0])).map(([mo, days]) => (
                <div key={mo}>
                  <button
                    className={"ab-side-item ab-side-item--month " + (sel.kind === 'month' && sel.value === mo ? 'ab-side-item--active' : '')}
                    onClick={() => { toggleMonth(mo); setSel({ kind: 'month', value: mo }); }}>
                    <ChevronRight size={11} style={{transition: 'transform 0.15s', transform: openMonths[mo] ? 'rotate(90deg)' : 'none'}}/>
                    <span>{mo.replace('-', '/')}</span>
                    <span className="ab-side-count">{BOOKINGS.filter(b => ymOf(b.date) === mo).length}</span>
                  </button>
                  {openMonths[mo] ? days.sort().reverse().map(d => (
                    <button key={d}
                      className={"ab-side-item ab-side-item--day " + (sel.kind === 'day' && sel.value === d ? 'ab-side-item--active' : '')}
                      onClick={() => setSel({ kind: 'day', value: d })}>
                      <span style={{paddingLeft: 4}}>{d.slice(-2)}</span>
                      <span style={{fontSize: 11, color: 'var(--color-grey-500)'}}>{new Date(d + 'T00:00:00').toLocaleDateString('en-GB', {weekday: 'short'})}</span>
                      <span className="ab-side-count">{BOOKINGS.filter(b => b.date === d).length}</span>
                    </button>
                  )) : null}
                </div>
              )) : null}
            </div>
          ))}
        </aside>

        {/* Main table */}
        <div className="ab-main">
          <div className="ab-header">
            <div className="ab-header__title">{selLabel}</div>
            <div className="ab-header__sub">{filtered.length} {filtered.length === 1 ? 'booking' : 'bookings'}{search.trim() ? ` matching "${search}"` : ''}</div>
          </div>

          <div className="ab-table">
            <div className="ab-row ab-row--head">
              <div>Chat</div>
              <div>Shift_Start_Date</div>
              <div>Category</div>
              <div>Machine</div>
              <div>Company</div>
              <div>Location</div>
              <div>Shift</div>
            </div>
            {filtered.length === 0 ? (
              <div style={{padding: 60, textAlign: 'center', color: 'var(--color-grey-500)'}}>
                No bookings match the current filter.
              </div>
            ) : filtered.map(b => {
              const CatIcon = categoryIcon(b.category);
              const isMulti = b.multi === true;
              return (
                <div key={b.id + '-' + b.date}
                  className={"ab-row " + (isMulti ? "ab-row--multi" : "")}
                  onClick={() => {
                    // Open the full Create-Booking form in edit mode so the
                    // detail fields match the create page exactly.
                    const machineId = (b.machine || '').split(' ')[0];
                    const machine = MACHINES.find(m => m.id === machineId);
                    if (machine) {
                      window.__createPrefill = { editBooking: b };
                      setPage('create');
                    }
                  }}>
                  <div className="ab-row__chat" title="Send WhatsApp (coming soon)">
                    <MessageCircle size={16}/>
                  </div>
                  <div>
                    <div style={{fontWeight: 600, fontSize: 13}}>{fmtAllDate(b.date)}</div>
                    {isMulti ? <span className="status status--purple" style={{padding: '2px 8px', fontSize: 10, marginTop: 4, display: 'inline-block'}}>Multiple</span> : null}
                  </div>
                  <div className="ab-cat">
                    <CatIcon size={16} style={{color: 'var(--color-grey-600)', flexShrink: 0}}/>
                    <span>{b.category}</span>
                  </div>
                  <div className="ab-machine">
                    <span className={"ab-dot " + (isMulti ? 'ab-dot--multi' : '')}/>
                    <span className="ab-machine__stack">
                      {b.category === 'Cross Rent' ? (
                        <span style={{display: 'flex', alignItems: 'center', gap: 6}}>
                          <span className="ab-cr-icon">{(b.machine || '').match(/\d+$/)?.[0] || '#'}</span>
                          {b.machine ? b.machine.replace(/^[A-Z]+-\d+\s+/, '') : ''}
                        </span>
                      ) : (
                        <span>{bookingMachineLabel(b)}</span>
                      )}
                      <span className="ab-machine__op">{b.operator || '— no operator —'}</span>
                    </span>
                  </div>
                  <div style={{fontWeight: 600}}>{b.customer}</div>
                  <div style={{color: 'var(--color-grey-700)'}}>{b.location}</div>
                  <div>{b.shift === 'morning' ? 'Custom' : b.shift === 'afternoon' ? 'Custom' : 'Custom'}</div>
                </div>
              );
            })}
          </div>
        </div>
      </div>

      {/* Modify dialog (reused from Bookings.jsx) */}
      {modifyTarget ? (
        <ModifyDialog
          target={modifyTarget}
          role={role}
          applyModify={(machineId, bookingId, patch) => {
            if (patch.machineStatus) {
              const m = MACHINES.find(x => x.id === machineId);
              if (m) m.status = patch.machineStatus;
            }
            if (bookingId) {
              const bk = BOOKINGS.find(x => x.id === bookingId);
              if (bk) ['customer','contact','phone','location','start','end','shift'].forEach(k => {
                if (patch[k] !== undefined) bk[k] = patch[k];
              });
            }
            forceRender();
          }}
          applyDelete={(bookingId) => {
            const i = BOOKINGS.findIndex(x => x.id === bookingId);
            if (i >= 0) BOOKINGS.splice(i, 1);
            forceRender();
          }}
          onClose={() => setModifyTarget(null)}/>
      ) : null}
    </div>
  );
}

Object.assign(window, { AllBookingsPage });
