// [REQ F7]  Panel admina – widok kalendarza rezerwacji (miesięczny), blokowanie terminów
import { useState } from 'react';
import { ChevronLeft, ChevronRight } from 'lucide-react';
import StatusBadge from './StatusBadge';
import styles from './AdminCalendar.module.scss';

const WEEKDAYS = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];

const toISO = (year, month, day) =>
  `${year}-${String(month + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`;

const AdminCalendar = ({ reservations = [] }) => {
  const now = new Date();
  const [cur, setCur] = useState({ year: now.getFullYear(), month: now.getMonth() });
  const [selectedDate, setSelectedDate] = useState(null);

  const { year, month } = cur;

  const prevMonth = () =>
    setCur(({ year, month }) =>
      month === 0 ? { year: year - 1, month: 11 } : { year, month: month - 1 }
    );

  const nextMonth = () =>
    setCur(({ year, month }) =>
      month === 11 ? { year: year + 1, month: 0 } : { year, month: month + 1 }
    );

  // (getDay() + 6) % 7 converts Sun=0 → Mon=0
  const startPad     = (new Date(year, month, 1).getDay() + 6) % 7;
  const daysInMonth  = new Date(year, month + 1, 0).getDate();
  const daysInPrev   = new Date(year, month, 0).getDate();

  const byDate = reservations.reduce((acc, r) => {
    if (!acc[r.date]) acc[r.date] = [];
    acc[r.date].push(r);
    return acc;
  }, {});

  const todayISO = now.toISOString().split('T')[0];
  const monthLabel = new Date(year, month, 1).toLocaleString('en-US', {
    month: 'long',
    year: 'numeric',
  });

  const cells = [];
  for (let i = 0; i < startPad; i++)
    cells.push({ day: daysInPrev - startPad + 1 + i, iso: null });
  for (let d = 1; d <= daysInMonth; d++)
    cells.push({ day: d, iso: toISO(year, month, d) });
  const tail = 7 - (cells.length % 7);
  if (tail < 7)
    for (let d = 1; d <= tail; d++) cells.push({ day: d, iso: null });

  const selectedRes = selectedDate ? (byDate[selectedDate] ?? []) : [];

  return (
    <div className={styles['cal']}>
      {/* Calendar grid */}
      <div className={styles['cal__grid-wrap']}>
        <div className={styles['cal__nav']}>
          <button className={styles['cal__nav-btn']} onClick={prevMonth} aria-label="Previous month">
            <ChevronLeft size={18} />
          </button>
          <h3 className={styles['cal__month']}>{monthLabel}</h3>
          <button className={styles['cal__nav-btn']} onClick={nextMonth} aria-label="Next month">
            <ChevronRight size={18} />
          </button>
        </div>

        <div className={styles['cal__weekdays']}>
          {WEEKDAYS.map((d) => (
            <div key={d} className={styles['cal__weekday']}>{d}</div>
          ))}
        </div>

        <div className={styles['cal__cells']}>
          {cells.map((cell, idx) => {
            if (!cell.iso) {
              return (
                <div key={`ov-${idx}`} className={styles['cal__cell-overflow']}>
                  <span className={styles['cal__day-num']}>{cell.day}</span>
                </div>
              );
            }
            const count      = byDate[cell.iso]?.length ?? 0;
            const isToday    = cell.iso === todayISO;
            const isSelected = cell.iso === selectedDate;
            return (
              <div
                key={cell.iso}
                className={[
                  styles['cal__cell'],
                  isSelected ? styles['cal__cell--selected'] : '',
                  count > 0  ? styles['cal__cell--busy']     : '',
                ].join(' ')}
                onClick={() => setSelectedDate((p) => p === cell.iso ? null : cell.iso)}
              >
                <span className={[
                  styles['cal__day-num'],
                  isToday ? styles['cal__day-num--today'] : '',
                ].join(' ')}>
                  {cell.day}
                </span>
                {count > 0 && (
                  <span className={[
                    styles['cal__badge'],
                    count >= 3 ? styles['cal__badge--high'] : '',
                  ].join(' ')}>
                    {count}
                  </span>
                )}
              </div>
            );
          })}
        </div>
      </div>

      {/* Side panel */}
      {selectedDate && (
        <div className={styles['cal__panel']}>
          <div className={styles['cal__panel-header']}>
            <span className={styles['cal__panel-date']}>{selectedDate}</span>
            <span className={styles['cal__panel-count']}>
              {selectedRes.length} reservation{selectedRes.length !== 1 ? 's' : ''}
            </span>
          </div>
          {selectedRes.length === 0 ? (
            <p className={styles['cal__panel-empty']}>No reservations on this day.</p>
          ) : (
            <ul className={styles['cal__panel-list']}>
              {selectedRes
                .slice()
                .sort((a, b) => a.time.localeCompare(b.time))
                .map((r) => (
                  <li key={r.id} className={styles['cal__panel-item']}>
                    <div className={styles['cal__panel-info']}>
                      <span className={styles['cal__panel-time']}>{r.time}</span>
                      <span className={styles['cal__panel-meta']}>
                        #{r.id} · {r.userId}
                      </span>
                      <span className={styles['cal__panel-svc']}>{r.serviceId}</span>
                    </div>
                    <StatusBadge status={r.status} size="sm" />
                  </li>
                ))}
            </ul>
          )}
        </div>
      )}
    </div>
  );
};

export default AdminCalendar;
