// [REQ F3]  Wyszukiwanie dostępności – siatka slotów z synchronizacją parametrów URL
// [REQ T3]  React Router – useSearchParams do synchronizacji filtrów z URL
import { useSearchParams } from 'react-router-dom';
import { Search, CalendarDays, Tag } from 'lucide-react';
import { useServices } from '../hooks/useServices';
import { useSlotReservations } from '../hooks/useSlotReservations';
import styles from './AvailabilitySearch.module.scss';

const todayISO = () => new Date().toISOString().split('T')[0];

const TIME_SLOTS = Array.from({ length: 18 }, (_, i) => {
  const mins = 9 * 60 + i * 30;
  return `${String(Math.floor(mins / 60)).padStart(2, '0')}:${String(mins % 60).padStart(2, '0')}`;
});

const AvailabilitySearch = ({ onSelectSlot }) => {
  const [searchParams, setSearchParams] = useSearchParams();
  const filterDate    = searchParams.get('date')    || '';
  const filterService = searchParams.get('service') || '';

  const { data: services = [] } = useServices();
  const { data: slotRes = [], isFetching } = useSlotReservations(filterService, filterDate);

  const bookedTimes = slotRes.filter((r) => r.status !== 'cancelled').map((r) => r.time);
  const showSlots   = !!filterDate && !!filterService;

  const setParam = (key, value) =>
    setSearchParams((prev) => {
      if (value) prev.set(key, value);
      else prev.delete(key);
      return prev;
    });

  const selectedSvcName = services.find((s) => s.id === filterService)?.name;

  return (
    <div className={styles['avail']}>
      <div className={styles['avail__header']}>
        <Search size={18} className={styles['avail__header-icon']} />
        <h2 className={styles['avail__title']}>Check Availability</h2>
        <span className={styles['avail__header-sub']}>Select a date and service to see open slots</span>
      </div>

      <div className={styles['avail__filters']}>
        <div className={styles['avail__filter-group']}>
          <label className={styles['avail__label']}>
            <CalendarDays size={14} />
            Date
          </label>
          <input
            type="date"
            className={styles['avail__input']}
            min={todayISO()}
            value={filterDate}
            onChange={(e) => setParam('date', e.target.value)}
          />
        </div>
        <div className={styles['avail__filter-group']}>
          <label className={styles['avail__label']}>
            <Tag size={14} />
            Service
          </label>
          <select
            className={styles['avail__select']}
            value={filterService}
            onChange={(e) => setParam('service', e.target.value)}
          >
            <option value="">— Select a service —</option>
            {services.map((s) => (
              <option key={s.id} value={s.id}>{s.name}</option>
            ))}
          </select>
        </div>
      </div>

      {showSlots && (
        <div className={styles['avail__slots']}>
          {isFetching ? (
            <p className={styles['avail__msg']}>Loading slots…</p>
          ) : (
            <>
              <p className={styles['avail__slots-label']}>
                {selectedSvcName} · {filterDate}
                {bookedTimes.length > 0 && (
                  <span className={styles['avail__slots-hint']}>
                    — {bookedTimes.length} slot(s) occupied
                  </span>
                )}
              </p>
              <div className={styles['avail__grid']}>
                {TIME_SLOTS.map((t) => {
                  const taken = bookedTimes.includes(t);
                  return (
                    <button
                      key={t}
                      className={[
                        styles['avail__slot'],
                        taken ? styles['avail__slot--taken'] : styles['avail__slot--free'],
                      ].join(' ')}
                      disabled={taken}
                      onClick={() => onSelectSlot?.({ serviceId: filterService, date: filterDate, time: t })}
                      title={taken ? 'Already booked' : 'Click to pre-fill booking form'}
                    >
                      {t}
                    </button>
                  );
                })}
              </div>
              <div className={styles['avail__legend']}>
                <span className={styles['avail__legend-free']}>Available — click to book</span>
                <span className={styles['avail__legend-taken']}>Occupied</span>
              </div>
            </>
          )}
        </div>
      )}
    </div>
  );
};

export default AvailabilitySearch;
