// [REQ F4]  Wieloetapowy kreator rezerwacji – wybór usługi, daty, godziny, płatność, potwierdzenie
// [REQ T1]  Podstawowe hooki – useState (activeStep, selections), useEffect (prefill slotu)
import { useState, useEffect } from 'react';
import { CheckCircle2, ChevronRight, ChevronLeft, Loader2 } from 'lucide-react';
import { useAuth } from '../context/AuthContext';
import { useServices } from '../hooks/useServices';
import { useSlotReservations } from '../hooks/useSlotReservations';
import { useCreateReservation } from '../hooks/useCreateReservation';
import PaymentModal from './PaymentModal';
import styles from './BookingWizard.module.scss';

const STEPS = ['Service', 'Date & Time', 'Requirements', 'Summary'];
const todayISO = () => new Date().toISOString().split('T')[0];

const BookingWizard = ({ prefillSlot, onPrefillUsed }) => {
  const { user } = useAuth();
  const [step, setStep] = useState(1);
  const [data, setData] = useState({ serviceId: '', date: '', time: '', specialRequirements: '' });
  const [fieldErrors, setFieldErrors] = useState({});
  const [paymentOpen, setPaymentOpen] = useState(false);
  const [done, setDone] = useState(false);
  const [receipt, setReceipt] = useState(null);

  const { data: services = [], isLoading: svcLoading } = useServices();
  const { data: slotRes = [] } = useSlotReservations(data.serviceId, data.date);
  const bookedTimes = slotRes.filter((r) => r.status !== 'cancelled').map((r) => r.time);

  const { mutate: createReservation, isPending } = useCreateReservation({
    onSuccess: (newRes) => {
      setReceipt(newRes);
      setDone(true);
      setPaymentOpen(false);
    },
  });

  useEffect(() => {
    if (prefillSlot) {
      setData((prev) => ({ ...prev, ...prefillSlot }));
      setStep(3);
      onPrefillUsed?.();
    }
  }, [prefillSlot]);

  const set = (key, value) => setData((prev) => ({ ...prev, [key]: value }));

  const validate = () => {
    const errs = {};
    if (step === 1 && !data.serviceId)
      errs.serviceId = 'Please select a service.';
    if (step === 2) {
      if (!data.date) errs.date = 'Date is required.';
      else if (data.date < todayISO()) errs.date = 'Date cannot be in the past.';
      if (!data.time) errs.time = 'Time is required.';
      else if (bookedTimes.includes(data.time)) errs.time = `${data.time} is already booked.`;
    }
    setFieldErrors(errs);
    return Object.keys(errs).length === 0;
  };

  const next = () => { if (validate()) setStep((s) => s + 1); };
  const back = () => { setFieldErrors({}); setStep((s) => s - 1); };

  const handlePaymentSuccess = (paymentData) => {
    createReservation({
      userId: user.id,
      serviceId: data.serviceId,
      date: data.date,
      time: data.time,
      specialRequirements: data.specialRequirements.trim() || null,
      status: 'pending',
      depositPaid: paymentData.amount,
      transactionId: paymentData.transactionId,
    });
  };

  const resetWizard = () => {
    setStep(1);
    setData({ serviceId: '', date: '', time: '', specialRequirements: '' });
    setFieldErrors({});
    setDone(false);
    setReceipt(null);
  };

  const selectedService = services.find((s) => s.id === data.serviceId);

  if (done) {
    return (
      <div className={styles['wizard']}>
        <div className={styles['wizard__success']}>
          <CheckCircle2 size={52} className={styles['wizard__success-icon']} />
          <h2 className={styles['wizard__success-title']}>Booking Confirmed!</h2>
          <p className={styles['wizard__success-sub']}>
            Your reservation is pending confirmation by our team.
          </p>
          {receipt && (
            <dl className={styles['wizard__receipt']}>
              <dt>Reference</dt>   <dd>#{receipt.id}</dd>
              <dt>Service</dt>     <dd>{selectedService?.name}</dd>
              <dt>Date</dt>        <dd>{receipt.date} · {receipt.time}</dd>
              <dt>Deposit Paid</dt><dd>${Number(receipt.depositPaid ?? 0).toFixed(2)}</dd>
              <dt>Transaction</dt> <dd>{receipt.transactionId ?? '—'}</dd>
            </dl>
          )}
          <div className={styles['wizard__receipt-actions']}>
            <button className={styles['wizard__btn-primary']} onClick={resetWizard}>
              Book Another
            </button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <>
      <div className={styles['wizard']}>
        {/* ── Progress indicator ─────────────────────────────────────────── */}
        <div className={styles['wizard__progress']}>
          <div className={styles['wizard__progress-track']}>
            <div
              className={styles['wizard__progress-fill']}
              style={{ width: `${((step - 1) / (STEPS.length - 1)) * 100}%` }}
            />
          </div>
          {STEPS.map((label, i) => (
            <div
              key={label}
              className={[
                styles['wizard__step'],
                step === i + 1 ? styles['wizard__step--active']  : '',
                step > i + 1  ? styles['wizard__step--done']    : '',
              ].join(' ')}
            >
              <div className={styles['wizard__step-dot']}>
                {step > i + 1 ? <CheckCircle2 size={13} /> : i + 1}
              </div>
              <span className={styles['wizard__step-label']}>{label}</span>
            </div>
          ))}
        </div>

        {/* ── Step 1: Service ───────────────────────────────────────────── */}
        {step === 1 && (
          <div className={styles['wizard__body']}>
            <h3 className={styles['wizard__step-title']}>Select a Service</h3>
            {svcLoading ? (
              <p className={styles['wizard__msg']}>Loading services…</p>
            ) : (
              <div className={styles['wizard__service-grid']}>
                {services.map((s) => (
                  <label
                    key={s.id}
                    className={[
                      styles['wizard__service-card'],
                      data.serviceId === s.id ? styles['wizard__service-card--selected'] : '',
                    ].join(' ')}
                  >
                    <input
                      type="radio"
                      name="serviceId"
                      value={s.id}
                      checked={data.serviceId === s.id}
                      onChange={() => { set('serviceId', s.id); setFieldErrors({}); }}
                      className={styles['wizard__radio']}
                    />
                    <span className={styles['wizard__service-name']}>{s.name}</span>
                    <span className={styles['wizard__service-desc']}>{s.description}</span>
                    <div className={styles['wizard__service-meta']}>
                      <span className={styles['wizard__service-price']}>${s.price}</span>
                      <span className={styles['wizard__service-duration']}>{s.duration} min</span>
                    </div>
                  </label>
                ))}
              </div>
            )}
            {fieldErrors.serviceId && (
              <p className={styles['wizard__error']}>{fieldErrors.serviceId}</p>
            )}
          </div>
        )}

        {/* ── Step 2: Date & Time ───────────────────────────────────────── */}
        {step === 2 && (
          <div className={styles['wizard__body']}>
            <h3 className={styles['wizard__step-title']}>Choose Date & Time</h3>
            {selectedService && (
              <div className={styles['wizard__service-pill']}>
                {selectedService.name} — ${selectedService.price} / {selectedService.duration} min
              </div>
            )}
            <div className={styles['wizard__row']}>
              <div className={styles['wizard__field']}>
                <label className={styles['wizard__label']}>Date *</label>
                <input
                  type="date"
                  className={[
                    styles['wizard__input'],
                    fieldErrors.date ? styles['wizard__input--error'] : '',
                  ].join(' ')}
                  min={todayISO()}
                  value={data.date}
                  onChange={(e) => { set('date', e.target.value); setFieldErrors({}); }}
                />
                {fieldErrors.date && <p className={styles['wizard__error']}>{fieldErrors.date}</p>}
              </div>
              <div className={styles['wizard__field']}>
                <label className={styles['wizard__label']}>Time *</label>
                <input
                  type="time"
                  className={[
                    styles['wizard__input'],
                    fieldErrors.time ? styles['wizard__input--error'] : '',
                  ].join(' ')}
                  value={data.time}
                  onChange={(e) => { set('time', e.target.value); setFieldErrors({}); }}
                />
                {fieldErrors.time && (
                  <p className={styles['wizard__error']}>{fieldErrors.time}</p>
                )}
                {bookedTimes.length > 0 && !fieldErrors.time && (
                  <p className={styles['wizard__hint']}>Occupied: {bookedTimes.join(', ')}</p>
                )}
              </div>
            </div>
          </div>
        )}

        {/* ── Step 3: Requirements ─────────────────────────────────────── */}
        {step === 3 && (
          <div className={styles['wizard__body']}>
            <h3 className={styles['wizard__step-title']}>Special Requirements</h3>
            <div className={styles['wizard__field']}>
              <label className={styles['wizard__label']}>
                Additional notes
                <span className={styles['wizard__optional']}>(optional)</span>
              </label>
              <textarea
                className={styles['wizard__textarea']}
                rows={5}
                maxLength={500}
                placeholder="Accessibility needs, preferences, or notes for the service provider…"
                value={data.specialRequirements}
                onChange={(e) => set('specialRequirements', e.target.value)}
              />
              <p className={styles['wizard__char-count']}>
                {data.specialRequirements.length} / 500
              </p>
            </div>
            <div className={styles['wizard__additional']}>
              <h4 className={styles['wizard__additional-title']}>Additional Services</h4>
              <p className={styles['wizard__additional-note']}>
                Extra add-ons can be requested in the notes above.
                Our team will confirm availability before your appointment.
              </p>
            </div>
          </div>
        )}

        {/* ── Step 4: Summary ──────────────────────────────────────────── */}
        {step === 4 && (
          <div className={styles['wizard__body']}>
            <h3 className={styles['wizard__step-title']}>Booking Summary</h3>
            <dl className={styles['wizard__summary']}>
              <div className={styles['wizard__summary-row']}>
                <dt>Service</dt>
                <dd>{selectedService?.name}</dd>
              </div>
              <div className={styles['wizard__summary-row']}>
                <dt>Duration</dt>
                <dd>{selectedService?.duration} min</dd>
              </div>
              <div className={styles['wizard__summary-row']}>
                <dt>Date</dt>
                <dd>{data.date}</dd>
              </div>
              <div className={styles['wizard__summary-row']}>
                <dt>Time</dt>
                <dd>{data.time}</dd>
              </div>
              <div className={styles['wizard__summary-row']}>
                <dt>Requirements</dt>
                <dd>{data.specialRequirements || '—'}</dd>
              </div>
              <div className={[
                styles['wizard__summary-row'],
                styles['wizard__summary-row--total'],
              ].join(' ')}>
                <dt>Total Price</dt>
                <dd>${selectedService?.price}</dd>
              </div>
              <div className={styles['wizard__summary-row']}>
                <dt>Deposit Due Now</dt>
                <dd className={styles['wizard__deposit']}>
                  ${(selectedService?.price * 0.5).toFixed(2)}
                </dd>
              </div>
            </dl>
            <p className={styles['wizard__summary-note']}>
              The remaining balance is collected at your appointment.
              Cancellations must be made at least 24 hours in advance.
            </p>
          </div>
        )}

        {/* ── Navigation ────────────────────────────────────────────────── */}
        <div className={styles['wizard__nav']}>
          {step > 1 ? (
            <button className={styles['wizard__btn-secondary']} onClick={back}>
              <ChevronLeft size={16} /> Back
            </button>
          ) : <span />}

          {step < 4 ? (
            <button className={styles['wizard__btn-primary']} onClick={next}>
              Next <ChevronRight size={16} />
            </button>
          ) : (
            <button
              className={styles['wizard__btn-primary']}
              onClick={() => setPaymentOpen(true)}
              disabled={isPending}
            >
              {isPending
                ? <><Loader2 size={16} className={styles['wizard__spinner']} /> Processing…</>
                : 'Confirm & Pay Deposit'
              }
            </button>
          )}
        </div>
      </div>

      <PaymentModal
        isOpen={paymentOpen}
        onClose={() => setPaymentOpen(false)}
        onSuccess={handlePaymentSuccess}
        service={selectedService}
        date={data.date}
        time={data.time}
      />
    </>
  );
};

export default BookingWizard;
