// [REQ F6]  Zarządzanie rezerwacjami – zmiana daty/godziny istniejącej rezerwacji
// [REQ D4]  React Portals – modal montowany w #portal-root
import { useState } from 'react';
import { createPortal } from 'react-dom';
import { X, CalendarDays, Clock, CheckCircle2, Loader2 } from 'lucide-react';
import { useUpdateReservation } from '../hooks/useUpdateReservation';
import styles from './RescheduleModal.module.scss';

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',
];

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

const RescheduleModal = ({ isOpen, onClose, reservation, serviceName }) => {
  const [date, setDate] = useState(reservation?.date ?? '');
  const [time, setTime] = useState(reservation?.time ?? '');
  const [done, setDone] = useState(false);

  const { mutate: updateStatus, isPending } = useUpdateReservation({
    onSuccess: () => setDone(true),
  });

  if (!isOpen) return null;

  const handleConfirm = () => {
    if (!date || !time) return;
    updateStatus({
      id: reservation.id,
      patch: { date, time },
    });
  };

  const handleClose = () => {
    setDone(false);
    onClose();
  };

  const portalRoot = document.getElementById('portal-root') ?? document.body;

  return createPortal(
    <div className={styles['rs']} role="dialog" aria-modal="true" aria-label="Reschedule reservation">
      <div className={styles['rs__overlay']} onClick={!isPending ? handleClose : undefined} />
      <div className={styles['rs__panel']}>
        <div className={styles['rs__header']}>
          <div className={styles['rs__header-left']}>
            <CalendarDays size={18} className={styles['rs__header-icon']} />
            <h2 className={styles['rs__title']}>Reschedule</h2>
          </div>
          {!isPending && (
            <button className={styles['rs__close']} onClick={handleClose} aria-label="Close">
              <X size={18} />
            </button>
          )}
        </div>

        {done ? (
          <div className={styles['rs__done']}>
            <CheckCircle2 size={40} className={styles['rs__done-icon']} />
            <p className={styles['rs__done-title']}>Reservation rescheduled!</p>
            <p className={styles['rs__done-sub']}>
              {serviceName} moved to {date} at {time}
            </p>
            <button className={styles['rs__confirm-btn']} onClick={handleClose}>
              Done
            </button>
          </div>
        ) : (
          <div className={styles['rs__body']}>
            <p className={styles['rs__service']}>
              {serviceName ?? reservation?.serviceId} &mdash; #{reservation?.id}
            </p>

            <div className={styles['rs__field']}>
              <label className={styles['rs__label']}>
                <CalendarDays size={13} /> New date
              </label>
              <input
                type="date"
                className={styles['rs__input']}
                value={date}
                min={todayISO()}
                onChange={(e) => setDate(e.target.value)}
                disabled={isPending}
              />
            </div>

            <div className={styles['rs__field']}>
              <label className={styles['rs__label']}>
                <Clock size={13} /> New time
              </label>
              <div className={styles['rs__slots']}>
                {TIME_SLOTS.map((t) => (
                  <button
                    key={t}
                    type="button"
                    className={[
                      styles['rs__slot'],
                      time === t ? styles['rs__slot--active'] : '',
                    ].join(' ')}
                    onClick={() => setTime(t)}
                    disabled={isPending}
                  >
                    {t}
                  </button>
                ))}
              </div>
            </div>

            <div className={styles['rs__footer']}>
              <button className={styles['rs__cancel-btn']} onClick={handleClose} disabled={isPending}>
                Cancel
              </button>
              <button
                className={styles['rs__confirm-btn']}
                onClick={handleConfirm}
                disabled={isPending || !date || !time}
              >
                {isPending
                  ? <><Loader2 size={14} className={styles['rs__spinner']} /> Saving…</>
                  : 'Confirm reschedule'}
              </button>
            </div>
          </div>
        )}
      </div>
    </div>,
    portalRoot
  );
};

export default RescheduleModal;
