// [REQ F6]  Zarządzanie rezerwacjami – lista rezerwacji użytkownika, zmiana terminu, anulowanie
// [REQ F10] Powiadomienia – toast na potwierdzenie akcji (zmiana, anulowanie)
// [REQ T1]  Podstawowe hooki – useState, useEffect, useRef
// [REQ T3]  React Router – useSearchParams do filtrowania listy po statusie z URL
import { useState, useEffect, useRef } from 'react';
import { Link, useSearchParams, useNavigate } from 'react-router-dom';
import {
  BookOpen, ChevronLeft, ChevronDown, ChevronUp,
  XCircle, AlertTriangle, CalendarDays, Clock,
  CreditCard, Hash, FileText, Tag, RefreshCw, ExternalLink, RotateCcw,
} from 'lucide-react';
import { useAuth } from '../context/AuthContext';
import { useUserReservations } from '../hooks/useUserReservations';
import { useUpdateReservation } from '../hooks/useUpdateReservation';
import { useServices } from '../hooks/useServices';
import ThemeToggle from '../components/ThemeToggle';
import StatusBadge from '../components/StatusBadge';
import ReviewsSection from '../components/ReviewsSection';
import RescheduleModal from '../components/RescheduleModal';
import styles from './ReservationsPage.module.scss';

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

const FILTERS = ['all', 'upcoming', 'past', 'cancelled'];
const FILTER_LABELS = { all: 'All', upcoming: 'Upcoming', past: 'Past', cancelled: 'Cancelled' };

const ReservationCard = ({ reservation: r, service, onCancel, cancelPending, highlighted, user, onRebook }) => {
  const [open, setOpen] = useState(highlighted);
  const [confirmCancel, setConfirmCancel] = useState(false);
  const [rescheduleOpen, setRescheduleOpen] = useState(false);
  const cardRef = useRef(null);

  useEffect(() => {
    if (highlighted && cardRef.current) {
      cardRef.current.scrollIntoView({ behavior: 'smooth', block: 'center' });
    }
  }, [highlighted]);

  const isUpcoming = r.date >= todayISO() && r.status !== 'cancelled';
  const isPast = r.date < todayISO() && r.status !== 'cancelled';
  const canCancel = r.status === 'pending' || r.status === 'confirmed';
  //  gcUrl to zmienna, która przechowuje link do dodania rezerwacji do Google Calendar, jeśli rezerwacja jest nadchodząca, jeśli rezerwacja jest przeszła to gcUrl jest null
  const gcUrl = (() => {
    if (!isUpcoming) return null;
    const [year, month, day] = r.date.split('-');
    const [h, m] = (r.time ?? '09:00').split(':');
    const pad = (n) => String(n).padStart(2, '0');
    const start = `${year}${month}${day}T${pad(h)}${pad(m)}00`;
    const end   = `${year}${month}${day}T${pad((+h + 1) % 24)}${pad(m)}00`;
    return `https://calendar.google.com/calendar/r/eventedit?text=${encodeURIComponent(service?.name ?? 'Reservation')}&dates=${start}/${end}&details=${encodeURIComponent(`Reservation #${r.id}`)}`;
  })();

  return (
    <div
      ref={cardRef}
      className={[
        styles['res-card'],
        r.status === 'cancelled' ? styles['res-card--cancelled'] : '',
        isUpcoming ? styles['res-card--upcoming'] : '',
        highlighted ? styles['res-card--highlighted'] : '',
      ].join(' ')}
    >
      <button
        className={styles['res-card__toggle']}
        onClick={() => { setOpen((v) => !v); setConfirmCancel(false); }}
        aria-expanded={open}
      >
        <div className={styles['res-card__summary']}>
          <span className={styles['res-card__name']}>{service?.name ?? r.serviceId}</span>
          <div className={styles['res-card__meta']}>
            <span className={styles['res-card__meta-item']}><CalendarDays size={12} /> {r.date}</span>
            <span className={styles['res-card__meta-item']}><Clock size={12} /> {r.time}</span>
          </div>
        </div>
        <div className={styles['res-card__right']}>
          <StatusBadge status={r.status} size="sm" />
          {open ? <ChevronUp size={16} /> : <ChevronDown size={16} />}
        </div>
      </button>

      {open && (
        <div className={styles['res-card__body']}>
          <dl className={styles['res-card__dl']}>
            <div className={styles['res-card__dl-row']}><dt><Hash size={12} /> Reference</dt><dd>#{r.id}</dd></div>
            <div className={styles['res-card__dl-row']}><dt><Tag size={12} /> Service</dt><dd>{service?.name ?? r.serviceId}</dd></div>
            {service && (
              <div className={styles['res-card__dl-row']}><dt><CreditCard size={12} /> Price</dt><dd>${service.price} ({service.duration} min)</dd></div>
            )}
            <div className={styles['res-card__dl-row']}><dt><CalendarDays size={12} /> Date</dt><dd>{r.date} · {r.time}</dd></div>
            {r.depositPaid != null && (
              <div className={styles['res-card__dl-row']}><dt><CreditCard size={12} /> Deposit paid</dt><dd>${Number(r.depositPaid).toFixed(2)}</dd></div>
            )}
            {r.transactionId && (
              <div className={styles['res-card__dl-row']}><dt><Hash size={12} /> Transaction</dt><dd className={styles['res-card__mono']}>{r.transactionId}</dd></div>
            )}
            {r.specialRequirements && (
              <div className={styles['res-card__dl-row']}><dt><FileText size={12} /> Notes</dt><dd>{r.specialRequirements}</dd></div>
            )}
          </dl>

          <div className={styles['res-card__actions']}>
            {gcUrl && (
              <a href={gcUrl} target="_blank" rel="noopener noreferrer" className={styles['res-card__cal-btn']}>
                <ExternalLink size={13} /> Add to Google Calendar
              </a>
            )}
            {canCancel && (
              <button className={styles['res-card__reschedule-btn']} onClick={() => setRescheduleOpen(true)}>
                <RefreshCw size={14} /> Reschedule
              </button>
            )}
            {(isPast || r.status === 'cancelled') && (
              <button className={styles['res-card__rebook-btn']} onClick={() => onRebook(r)}>
                <RotateCcw size={14} /> Book again
              </button>
            )}
            {canCancel && !confirmCancel && (
              <button className={styles['res-card__cancel-trigger']} onClick={() => setConfirmCancel(true)}>
                <XCircle size={14} /> Cancel reservation
              </button>
            )}
          </div>

          {confirmCancel && (
            <div className={styles['res-card__confirm']}>
              <AlertTriangle size={16} className={styles['res-card__confirm-icon']} />
              <p className={styles['res-card__confirm-text']}>Are you sure you want to cancel this reservation?</p>
              <div className={styles['res-card__confirm-btns']}>
                <button className={styles['res-card__confirm-yes']} onClick={() => { onCancel(r.id); setConfirmCancel(false); }} disabled={cancelPending}>
                  {cancelPending ? 'Cancelling…' : 'Yes, cancel it'}
                </button>
                <button className={styles['res-card__confirm-no']} onClick={() => setConfirmCancel(false)}>Keep it</button>
              </div>
            </div>
          )}

          {isPast && r.serviceId && (
            <div className={styles['res-card__reviews']}>
              <ReviewsSection serviceId={r.serviceId} reservationId={r.id} userId={user?.id ?? ''} userName={user?.name ?? user?.email ?? ''} />
            </div>
          )}
        </div>
      )}

      <RescheduleModal isOpen={rescheduleOpen} onClose={() => setRescheduleOpen(false)} reservation={r} serviceName={service?.name} />
    </div>
  );
};

const ReservationsPage = () => {
  const { user, logout } = useAuth();
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();
  const highlightId = searchParams.get('id');
  const { data: reservations = [], isLoading } = useUserReservations(user?.id);
  const { data: services = [] } = useServices();
  const { mutate: updateStatus, isPending: cancelPending } = useUpdateReservation();
  const [filter, setFilter] = useState('all');

  const getService = (id) => services.find((s) => s.id === id);

  const filtered = reservations.filter((r) => {
    if (filter === 'upcoming')  return r.date >= todayISO() && r.status !== 'cancelled';
    if (filter === 'past')      return r.date < todayISO()  && r.status !== 'cancelled';
    if (filter === 'cancelled') return r.status === 'cancelled';
    return true;
  });

  const sorted = [...filtered].sort((a, b) =>
    filter === 'past'
      ? (b.date + b.time).localeCompare(a.date + a.time)
      : (a.date + a.time).localeCompare(b.date + b.time)
  );

  const counts = {
    all:       reservations.length,
    upcoming:  reservations.filter((r) => r.date >= todayISO() && r.status !== 'cancelled').length,
    past:      reservations.filter((r) => r.date < todayISO()  && r.status !== 'cancelled').length,
    cancelled: reservations.filter((r) => r.status === 'cancelled').length,
  };

  return (
    <div className={styles['rp']}>
      <header className={styles['rp__header']}>
        <div className={styles['rp__header-inner']}>
          <div className={styles['rp__header-left']}>
            <Link to="/dashboard" className={styles['rp__back']}><ChevronLeft size={16} /> Dashboard</Link>
            <div>
              <h1 className={styles['rp__title']}><BookOpen size={20} /> My Reservations</h1>
              <p className={styles['rp__subtitle']}>{user?.email}</p>
            </div>
          </div>
          <div className={styles['rp__header-actions']}>
            <ThemeToggle />
            <button className={styles['rp__logout']} onClick={logout}>Sign out</button>
          </div>
        </div>
      </header>

      <main className={styles['rp__main']}>
        <div className={styles['rp__tabs']}>
          {FILTERS.map((f) => (
            <button key={f} className={[styles['rp__tab'], filter === f ? styles['rp__tab--active'] : ''].join(' ')} onClick={() => setFilter(f)}>
              {FILTER_LABELS[f]}
              {counts[f] > 0 && <span className={styles['rp__tab-count']}>{counts[f]}</span>}
            </button>
          ))}
        </div>

        {isLoading ? (
          <p className={styles['rp__msg']}>Loading reservations…</p>
        ) : sorted.length === 0 ? (
          <p className={styles['rp__msg']}>
            {filter === 'all' ? 'You have no reservations yet.' : `No ${FILTER_LABELS[filter].toLowerCase()} reservations.`}
          </p>
        ) : (
          <div className={styles['rp__list']}>
            {sorted.map((r) => (
              <ReservationCard
                key={r.id}
                reservation={r}
                service={getService(r.serviceId)}
                onCancel={(id) => updateStatus({ id, patch: { status: 'cancelled' } })}
                cancelPending={cancelPending}
                highlighted={r.id === highlightId}
                user={user}
                onRebook={(r) => navigate('/dashboard', { state: { rebookServiceId: r.serviceId } })}
              />
            ))}
          </div>
        )}
      </main>
    </div>
  );
};

export default ReservationsPage;
