// [REQ F3]  Wyszukiwanie dostępności – inteligentny ranking slotów (scoreSlot, findSlots)
// [REQ D7]  React Query – useQuery do pobierania wszystkich rezerwacji
// [REQ T6]  Optymalizacja – useMemo dla maxScore paska wynikowego
import { useState, useMemo } from 'react';
import { useQuery } from '@tanstack/react-query';
import { Search, Calendar, Clock, Zap, ChevronRight } from 'lucide-react';
import { useServices } from '../hooks/useServices';
import { API_URL } from '../config';
import styles from './SlotFinder.module.scss';

const todayISO = () => new Date().toISOString().split('T')[0];
const plusDays = (n) => new Date(Date.now() + n * 864e5).toISOString().split('T')[0];

const TIME_SLOTS = [
  '09:00','09:30','10:00','10:30','11:00','11:30',
  '12:00','12:30','13:00','13:30','14:00','14:30',
  '15:00','15:30','16:00','16:30','17:00',
];

function scoreSlot(dateStr, time, preferredTime, daysFromNow) {
  let score = 100;
  const hour = parseInt(time);
  if (preferredTime === 'morning'   && hour >= 9  && hour < 12) score += 30;
  if (preferredTime === 'afternoon' && hour >= 12 && hour < 15) score += 30;
  if (preferredTime === 'late'      && hour >= 15)               score += 30;
  score -= daysFromNow * 2;
  const day = new Date(dateStr).getDay();
  if (day === 0 || day === 6) score -= 20;
  if (hour === 10 || hour === 14) score += 10;
  return Math.max(score, 0);
}

function findSlots(allReservations, { serviceId, dateFrom, dateTo, preferredTime, maxResults }) {
  const booked = new Set(
    allReservations
      .filter((r) => r.serviceId === serviceId && r.status !== 'cancelled')
      .map((r) => `${r.date}|${r.time}`)
  );

  const results = [];
  const today = new Date();
  const cur = new Date(dateFrom);
  const end = new Date(dateTo);

  while (cur <= end) {
    const dateStr = cur.toISOString().split('T')[0];
    const daysFromNow = Math.round((cur - today) / 864e5);
    const dow = cur.toLocaleDateString('en-US', { weekday: 'long' });

    for (const time of TIME_SLOTS) {
      if (!booked.has(`${dateStr}|${time}`)) {
        const hour = parseInt(time);
        const tag = hour < 12 ? 'Morning' : hour < 15 ? 'Afternoon' : 'Evening';
        results.push({ date: dateStr, time, score: scoreSlot(dateStr, time, preferredTime, daysFromNow), dayOfWeek: dow, daysFromNow, tag });
      }
    }
    cur.setDate(cur.getDate() + 1);
  }

  return results.sort((a, b) => b.score - a.score).slice(0, maxResults);
}

const SlotFinder = ({ onSelectSlot }) => {
  const { data: services = [] } = useServices();
  const { data: allReservations = [] } = useQuery({
    queryKey: ['reservations'],
    queryFn: () => fetch(`${API_URL}/reservations`).then((r) => r.json()),
    staleTime: 30_000,
  });

  const [form, setForm] = useState({
    serviceId: '',
    dateFrom: todayISO(),
    dateTo: plusDays(14),
    preferredTime: 'any',
    maxResults: '8',
  });
  const [results, setResults] = useState(null);

  const set = (k, v) => setForm((f) => ({ ...f, [k]: v }));

  const handleSearch = () => {
    if (!form.serviceId) return;
    setResults(findSlots(allReservations, {
      serviceId: form.serviceId,
      dateFrom: form.dateFrom,
      dateTo: form.dateTo,
      preferredTime: form.preferredTime,
      maxResults: parseInt(form.maxResults, 10),
    }));
  };

  const maxScore = useMemo(
    () => (results?.length ? Math.max(...results.map((r) => r.score)) : 1),
    [results],
  );

  return (
    <div className={styles['sf']}>
      <div className={styles['sf__header']}>
        <Zap size={18} className={styles['sf__header-icon']} />
        <div>
          <h2 className={styles['sf__title']}>Smart Slot Finder</h2>
          <p className={styles['sf__subtitle']}>Ranks available slots across a date range by score</p>
        </div>
      </div>

      <div className={styles['sf__form']}>
        <div className={styles['sf__field']}>
          <label className={styles['sf__label']}>Service</label>
          <select className={styles['sf__select']} value={form.serviceId} onChange={(e) => set('serviceId', e.target.value)}>
            <option value="">— Pick a service —</option>
            {services.map((s) => <option key={s.id} value={s.id}>{s.name}</option>)}
          </select>
        </div>

        <div className={styles['sf__row']}>
          <div className={styles['sf__field']}>
            <label className={styles['sf__label']}>From</label>
            <input type="date" className={styles['sf__input']} value={form.dateFrom} min={todayISO()} onChange={(e) => set('dateFrom', e.target.value)} />
          </div>
          <div className={styles['sf__field']}>
            <label className={styles['sf__label']}>To</label>
            <input type="date" className={styles['sf__input']} value={form.dateTo} min={form.dateFrom} onChange={(e) => set('dateTo', e.target.value)} />
          </div>
          <div className={styles['sf__field']}>
            <label className={styles['sf__label']}>Preference</label>
            <select className={styles['sf__select']} value={form.preferredTime} onChange={(e) => set('preferredTime', e.target.value)}>
              <option value="any">Any time</option>
              <option value="morning">Morning (9–12)</option>
              <option value="afternoon">Afternoon (12–15)</option>
              <option value="late">Late (15–18)</option>
            </select>
          </div>
          <div className={styles['sf__field']}>
            <label className={styles['sf__label']}>Show top</label>
            <select className={styles['sf__select']} value={form.maxResults} onChange={(e) => set('maxResults', e.target.value)}>
              <option value="5">5 results</option>
              <option value="8">8 results</option>
              <option value="12">12 results</option>
            </select>
          </div>
        </div>

        <button className={styles['sf__btn']} onClick={handleSearch} disabled={!form.serviceId}>
          <Search size={15} /> Find best slots
        </button>
      </div>

      {results !== null && (
        <div className={styles['sf__results']}>
          {results.length === 0 ? (
            <p className={styles['sf__empty']}>No available slots in this date range.</p>
          ) : (
            <>
              <p className={styles['sf__count']}>{results.length} slot{results.length !== 1 ? 's' : ''} ranked by availability score</p>
              <div className={styles['sf__grid']}>
                {results.map((slot, idx) => (
                  <div key={`${slot.date}-${slot.time}`} className={[styles['sf__card'], idx === 0 ? styles['sf__card--best'] : ''].join(' ')}>
                    <span className={styles['sf__tag']}>{slot.tag}</span>
                    <div className={styles['sf__card-date']}><Calendar size={12} />{slot.date}<span className={styles['sf__dow']}>{slot.dayOfWeek.slice(0, 3)}</span></div>
                    <div className={styles['sf__card-time']}><Clock size={12} />{slot.time}</div>
                    <p className={styles['sf__days']}>
                      {slot.daysFromNow === 0 ? 'Today' : slot.daysFromNow === 1 ? 'Tomorrow' : `In ${slot.daysFromNow} days`}
                    </p>
                    <div className={styles['sf__bar']}>
                      <div className={styles['sf__bar-fill']} style={{ width: `${(slot.score / maxScore) * 100}%` }} />
                    </div>
                    {onSelectSlot && (
                      <button className={styles['sf__book']} onClick={() => onSelectSlot({ serviceId: form.serviceId, date: slot.date, time: slot.time })}>
                        Book <ChevronRight size={13} />
                      </button>
                    )}
                  </div>
                ))}
              </div>
            </>
          )}
        </div>
      )}
    </div>
  );
};

export default SlotFinder;
