import React, { useState, useMemo } from 'react';
import type { ComponentConfig } from '@measured/puck';
import {
  Clock,
  DollarSign,
  Loader2,
  ChevronLeft,
  ChevronRight,
  Calendar as CalendarIcon,
  Check,
  User as UserIcon,
  Mail,
  Phone,
  ArrowRight,
  AlertCircle,
} from 'lucide-react';
import {
  usePublicServices,
  usePublicBusinessInfo,
  usePublicAvailability,
  usePublicBusinessHours,
  useCreateBooking,
  PublicService,
} from '../../../hooks/useBooking';
import { formatTimeForDisplay, getTimezoneAbbreviation, getUserTimezone } from '../../../utils/dateUtils';
import toast from 'react-hot-toast';
import {
  createDesignControlsFields,
  applyDesignControls,
  type DesignControlsProps,
} from '../../theme';

export interface FullBookingFlowProps extends DesignControlsProps {
  headline?: string;
  subheadline?: string;
  showPrices: boolean;
  showDuration: boolean;
  showDeposits: boolean;
  allowGuestCheckout: boolean;
  successMessage?: string;
  successRedirectUrl?: string;
}

type BookingStep = 'service' | 'datetime' | 'details' | 'confirm' | 'success';

interface GuestInfo {
  firstName: string;
  lastName: string;
  email: string;
  phone: string;
  notes: string;
}

const FullBookingFlowRender: React.FC<FullBookingFlowProps> = (props) => {
  const {
    headline,
    subheadline,
    showPrices,
    showDuration,
    showDeposits,
    allowGuestCheckout,
    successMessage,
    successRedirectUrl,
    ...designControls
  } = props;

  const applied = applyDesignControls(designControls);

  // State
  const [step, setStep] = useState<BookingStep>('service');
  const [selectedService, setSelectedService] = useState<PublicService | null>(null);
  const [selectedDate, setSelectedDate] = useState<Date | null>(null);
  const [selectedTimeSlot, setSelectedTimeSlot] = useState<string | null>(null);
  const [selectedTimeISO, setSelectedTimeISO] = useState<string | null>(null);
  const [guestInfo, setGuestInfo] = useState<GuestInfo>({
    firstName: '',
    lastName: '',
    email: '',
    phone: '',
    notes: '',
  });
  const [isSubmitting, setIsSubmitting] = useState(false);

  // Hooks
  const { data: services, isLoading: servicesLoading } = usePublicServices();
  const { data: businessInfo } = usePublicBusinessInfo();
  const createBooking = useCreateBooking();

  // Calendar state
  const today = new Date();
  const [currentMonth, setCurrentMonth] = useState(today.getMonth());
  const [currentYear, setCurrentYear] = useState(today.getFullYear());

  // Date range for business hours
  const { startDate, endDate } = useMemo(() => {
    const start = new Date(currentYear, currentMonth, 1);
    const end = new Date(currentYear, currentMonth + 1, 0);
    return {
      startDate: `${start.getFullYear()}-${String(start.getMonth() + 1).padStart(2, '0')}-01`,
      endDate: `${end.getFullYear()}-${String(end.getMonth() + 1).padStart(2, '0')}-${String(end.getDate()).padStart(2, '0')}`,
    };
  }, [currentMonth, currentYear]);

  const { data: businessHours, isLoading: businessHoursLoading } = usePublicBusinessHours(startDate, endDate);

  const openDaysMap = useMemo(() => {
    const map = new Map<string, boolean>();
    if (businessHours?.dates) {
      businessHours.dates.forEach((day) => {
        map.set(day.date, day.is_open);
      });
    }
    return map;
  }, [businessHours]);

  const dateString = selectedDate
    ? `${selectedDate.getFullYear()}-${String(selectedDate.getMonth() + 1).padStart(2, '0')}-${String(selectedDate.getDate()).padStart(2, '0')}`
    : undefined;

  const { data: availability, isLoading: availabilityLoading } = usePublicAvailability(
    selectedService?.id,
    dateString
  );

  // Format price from cents
  const formatPrice = (cents: number): string => `$${(cents / 100).toFixed(2)}`;

  // Calendar helpers
  const daysInMonth = new Date(currentYear, currentMonth + 1, 0).getDate();
  const firstDayOfMonth = new Date(currentYear, currentMonth, 1).getDay();
  const monthName = new Date(currentYear, currentMonth).toLocaleString('default', { month: 'long' });
  const days = Array.from({ length: daysInMonth }, (_, i) => i + 1);

  const isPast = (day: number) => {
    const d = new Date(currentYear, currentMonth, day);
    const now = new Date();
    now.setHours(0, 0, 0, 0);
    return d < now;
  };

  const isClosed = (day: number) => {
    const dateStr = `${currentYear}-${String(currentMonth + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
    if (openDaysMap.size > 0) {
      return openDaysMap.get(dateStr) === false;
    }
    return false;
  };

  const isSelected = (day: number) => {
    return (
      selectedDate?.getDate() === day &&
      selectedDate?.getMonth() === currentMonth &&
      selectedDate?.getFullYear() === currentYear
    );
  };

  // Handlers
  const handleSelectService = (service: PublicService) => {
    setSelectedService(service);
    setSelectedDate(null);
    setSelectedTimeSlot(null);
    setStep('datetime');
  };

  const handleSelectDate = (day: number) => {
    const newDate = new Date(currentYear, currentMonth, day);
    setSelectedDate(newDate);
    setSelectedTimeSlot(null);
  };

  const handleSelectTime = (displayTime: string, isoTime: string) => {
    setSelectedTimeSlot(displayTime);
    setSelectedTimeISO(isoTime);
  };

  const handleContinueToDetails = () => {
    if (selectedService && selectedDate && selectedTimeSlot) {
      setStep('details');
    }
  };

  const handleContinueToConfirm = () => {
    if (guestInfo.firstName && guestInfo.lastName && guestInfo.email) {
      setStep('confirm');
    }
  };

  const handleSubmitBooking = async () => {
    if (!selectedService || !selectedTimeISO) return;

    setIsSubmitting(true);
    try {
      await createBooking.mutateAsync({
        service_id: selectedService.id,
        start_time: selectedTimeISO,
        guest_first_name: guestInfo.firstName,
        guest_last_name: guestInfo.lastName,
        guest_email: guestInfo.email,
        guest_phone: guestInfo.phone || undefined,
        notes: guestInfo.notes || undefined,
      });

      setStep('success');
      toast.success('Booking confirmed!');
    } catch (error: any) {
      toast.error(error?.response?.data?.detail || 'Failed to create booking');
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleReset = () => {
    setStep('service');
    setSelectedService(null);
    setSelectedDate(null);
    setSelectedTimeSlot(null);
    setSelectedTimeISO(null);
    setGuestInfo({ firstName: '', lastName: '', email: '', phone: '', notes: '' });
  };

  // Step indicator
  const steps = [
    { key: 'service', label: 'Service' },
    { key: 'datetime', label: 'Date & Time' },
    { key: 'details', label: 'Your Info' },
    { key: 'confirm', label: 'Confirm' },
  ];

  const currentStepIndex = steps.findIndex((s) => s.key === step);

  // Render functions
  const renderStepIndicator = () => {
    if (step === 'success') return null;

    return (
      <div className="flex items-center justify-center mb-8">
        {steps.map((s, idx) => (
          <React.Fragment key={s.key}>
            <div className="flex items-center">
              <div
                className={`w-8 h-8 rounded-full flex items-center justify-center text-sm font-medium transition-colors ${
                  idx < currentStepIndex
                    ? 'bg-green-500 text-white'
                    : idx === currentStepIndex
                    ? 'bg-indigo-600 text-white'
                    : 'bg-gray-200 dark:bg-gray-700 text-gray-500 dark:text-gray-400'
                }`}
              >
                {idx < currentStepIndex ? <Check className="w-4 h-4" /> : idx + 1}
              </div>
              <span
                className={`ml-2 text-sm hidden sm:inline ${
                  idx === currentStepIndex
                    ? 'text-gray-900 dark:text-white font-medium'
                    : 'text-gray-500 dark:text-gray-400'
                }`}
              >
                {s.label}
              </span>
            </div>
            {idx < steps.length - 1 && (
              <div
                className={`w-8 sm:w-16 h-0.5 mx-2 ${
                  idx < currentStepIndex ? 'bg-green-500' : 'bg-gray-200 dark:bg-gray-700'
                }`}
              />
            )}
          </React.Fragment>
        ))}
      </div>
    );
  };

  const renderServiceStep = () => {
    if (servicesLoading) {
      return (
        <div className="flex justify-center items-center py-12">
          <Loader2 className="w-8 h-8 animate-spin text-indigo-600" />
        </div>
      );
    }

    if (!services || services.length === 0) {
      return (
        <div className="text-center py-12 text-gray-500 dark:text-gray-400">
          <AlertCircle className="w-12 h-12 mx-auto mb-4 text-gray-400" />
          <p>No services available at this time.</p>
        </div>
      );
    }

    return (
      <div className="space-y-4">
        {services.map((service) => (
          <button
            key={service.id}
            onClick={() => handleSelectService(service)}
            className={`w-full text-left p-5 rounded-xl border-2 transition-all ${
              selectedService?.id === service.id
                ? 'border-indigo-600 bg-indigo-50 dark:bg-indigo-900/20'
                : 'border-gray-200 dark:border-gray-700 hover:border-indigo-300 dark:hover:border-indigo-600 bg-white dark:bg-gray-800'
            }`}
          >
            <div className="flex justify-between items-start">
              <div className="flex-1">
                <h3 className="text-lg font-semibold text-gray-900 dark:text-white">
                  {service.name}
                </h3>
                {service.description && (
                  <p className="mt-1 text-sm text-gray-500 dark:text-gray-400 line-clamp-2">
                    {service.description}
                  </p>
                )}
                <div className="mt-3 flex items-center gap-4 text-sm">
                  {showDuration && (
                    <span className="flex items-center text-gray-600 dark:text-gray-400">
                      <Clock className="w-4 h-4 mr-1" />
                      {service.duration} min
                    </span>
                  )}
                  {showDeposits && service.deposit_amount_cents && service.deposit_amount_cents > 0 && (
                    <span className="text-indigo-600 dark:text-indigo-400 font-medium">
                      Deposit: {formatPrice(service.deposit_amount_cents)}
                    </span>
                  )}
                </div>
              </div>
              {showPrices && (
                <div className="text-lg font-bold text-gray-900 dark:text-white flex items-center">
                  <DollarSign className="w-4 h-4" />
                  {(service.price_cents / 100).toFixed(2)}
                </div>
              )}
            </div>
          </button>
        ))}
      </div>
    );
  };

  const renderDateTimeStep = () => {
    const displayTimezone = availability?.timezone_display_mode === 'viewer'
      ? getUserTimezone()
      : availability?.business_timezone || getUserTimezone();
    const tzAbbrev = getTimezoneAbbreviation(displayTimezone);

    return (
      <div className="space-y-6">
        {/* Back button */}
        <button
          onClick={() => setStep('service')}
          className="flex items-center text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white text-sm"
        >
          <ChevronLeft className="w-4 h-4 mr-1" />
          Back to services
        </button>

        {/* Selected service summary */}
        {selectedService && (
          <div className="p-4 bg-indigo-50 dark:bg-indigo-900/20 rounded-lg border border-indigo-200 dark:border-indigo-800">
            <p className="text-sm text-indigo-600 dark:text-indigo-400 font-medium">Selected Service</p>
            <p className="text-gray-900 dark:text-white font-semibold">{selectedService.name}</p>
            <p className="text-sm text-gray-600 dark:text-gray-400">
              {selectedService.duration} min • {formatPrice(selectedService.price_cents)}
            </p>
          </div>
        )}

        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          {/* Calendar */}
          <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-5">
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-lg font-semibold text-gray-900 dark:text-white flex items-center">
                <CalendarIcon className="w-5 h-5 mr-2 text-indigo-600" />
                Select Date
              </h3>
              <div className="flex items-center space-x-1">
                <button
                  onClick={() => {
                    if (currentMonth === 0) {
                      setCurrentMonth(11);
                      setCurrentYear(currentYear - 1);
                    } else {
                      setCurrentMonth(currentMonth - 1);
                    }
                  }}
                  className="p-1.5 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-full"
                >
                  <ChevronLeft className="w-4 h-4" />
                </button>
                <span className="text-sm font-medium w-28 text-center">
                  {monthName} {currentYear}
                </span>
                <button
                  onClick={() => {
                    if (currentMonth === 11) {
                      setCurrentMonth(0);
                      setCurrentYear(currentYear + 1);
                    } else {
                      setCurrentMonth(currentMonth + 1);
                    }
                  }}
                  className="p-1.5 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-full"
                >
                  <ChevronRight className="w-4 h-4" />
                </button>
              </div>
            </div>

            <div className="grid grid-cols-7 gap-1 mb-2 text-center text-xs font-medium text-gray-500 dark:text-gray-400">
              {['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'].map((d) => (
                <div key={d}>{d}</div>
              ))}
            </div>

            {businessHoursLoading ? (
              <div className="flex items-center justify-center h-48">
                <Loader2 className="w-6 h-6 animate-spin text-indigo-600" />
              </div>
            ) : (
              <div className="grid grid-cols-7 gap-1">
                {Array.from({ length: firstDayOfMonth }).map((_, i) => (
                  <div key={`empty-${i}`} />
                ))}
                {days.map((day) => {
                  const past = isPast(day);
                  const closed = isClosed(day);
                  const disabled = past || closed;
                  const selected = isSelected(day);

                  return (
                    <button
                      key={day}
                      disabled={disabled}
                      onClick={() => handleSelectDate(day)}
                      className={`h-9 w-9 rounded-full flex items-center justify-center text-sm transition-all ${
                        selected
                          ? 'bg-indigo-600 text-white'
                          : disabled
                          ? 'text-gray-300 dark:text-gray-600 cursor-not-allowed'
                          : 'hover:bg-indigo-50 dark:hover:bg-indigo-900/30 text-gray-700 dark:text-gray-200'
                      }`}
                    >
                      {day}
                    </button>
                  );
                })}
              </div>
            )}
          </div>

          {/* Time slots */}
          <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-5">
            <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
              Available Times
            </h3>
            {!selectedDate ? (
              <div className="h-48 flex items-center justify-center text-gray-400 italic">
                Please select a date
              </div>
            ) : availabilityLoading ? (
              <div className="h-48 flex items-center justify-center">
                <Loader2 className="w-6 h-6 animate-spin text-indigo-600" />
              </div>
            ) : availability?.is_open === false ? (
              <div className="h-48 flex items-center justify-center text-gray-400">
                Business closed on this date
              </div>
            ) : availability?.slots && availability.slots.length > 0 ? (
              <>
                <p className="text-xs text-gray-500 dark:text-gray-400 mb-3">
                  Times shown in {tzAbbrev}
                </p>
                <div className="grid grid-cols-3 gap-2 max-h-64 overflow-y-auto">
                  {availability.slots.map((slot) => {
                    const displayTime = formatTimeForDisplay(
                      slot.time,
                      availability.timezone_display_mode === 'viewer' ? null : availability.business_timezone
                    );

                    return (
                      <button
                        key={slot.time}
                        disabled={!slot.available}
                        onClick={() => handleSelectTime(displayTime, slot.time)}
                        className={`py-2 px-3 rounded-lg text-sm font-medium transition-all ${
                          !slot.available
                            ? 'bg-gray-100 dark:bg-gray-700 text-gray-400 cursor-not-allowed'
                            : selectedTimeSlot === displayTime
                            ? 'bg-indigo-600 text-white'
                            : 'bg-gray-50 dark:bg-gray-700 hover:bg-indigo-50 dark:hover:bg-indigo-900/30 text-gray-700 dark:text-gray-200'
                        }`}
                      >
                        {displayTime}
                      </button>
                    );
                  })}
                </div>
              </>
            ) : (
              <div className="h-48 flex items-center justify-center text-gray-400">
                No available times
              </div>
            )}
          </div>
        </div>

        {/* Continue button */}
        <div className="flex justify-end">
          <button
            onClick={handleContinueToDetails}
            disabled={!selectedDate || !selectedTimeSlot}
            className="px-6 py-3 bg-indigo-600 text-white rounded-lg font-medium disabled:opacity-50 disabled:cursor-not-allowed hover:bg-indigo-700 transition-colors flex items-center"
          >
            Continue
            <ArrowRight className="w-4 h-4 ml-2" />
          </button>
        </div>
      </div>
    );
  };

  const renderDetailsStep = () => (
    <div className="space-y-6 max-w-lg mx-auto">
      <button
        onClick={() => setStep('datetime')}
        className="flex items-center text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white text-sm"
      >
        <ChevronLeft className="w-4 h-4 mr-1" />
        Back to date & time
      </button>

      <div className="text-center">
        <h3 className="text-xl font-semibold text-gray-900 dark:text-white">Your Information</h3>
        <p className="text-gray-500 dark:text-gray-400 mt-1">
          {allowGuestCheckout
            ? "Enter your details to complete the booking"
            : "Create an account or sign in to book"}
        </p>
      </div>

      <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-6">
        <div className="space-y-4">
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                First Name *
              </label>
              <div className="relative">
                <UserIcon className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                <input
                  type="text"
                  required
                  value={guestInfo.firstName}
                  onChange={(e) => setGuestInfo({ ...guestInfo, firstName: e.target.value })}
                  className="w-full pl-10 pr-3 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                  placeholder="John"
                />
              </div>
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                Last Name *
              </label>
              <input
                type="text"
                required
                value={guestInfo.lastName}
                onChange={(e) => setGuestInfo({ ...guestInfo, lastName: e.target.value })}
                className="w-full px-3 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                placeholder="Doe"
              />
            </div>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              Email *
            </label>
            <div className="relative">
              <Mail className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
              <input
                type="email"
                required
                value={guestInfo.email}
                onChange={(e) => setGuestInfo({ ...guestInfo, email: e.target.value })}
                className="w-full pl-10 pr-3 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                placeholder="john@example.com"
              />
            </div>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              Phone (optional)
            </label>
            <div className="relative">
              <Phone className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
              <input
                type="tel"
                value={guestInfo.phone}
                onChange={(e) => setGuestInfo({ ...guestInfo, phone: e.target.value })}
                className="w-full pl-10 pr-3 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                placeholder="(555) 123-4567"
              />
            </div>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              Notes (optional)
            </label>
            <textarea
              value={guestInfo.notes}
              onChange={(e) => setGuestInfo({ ...guestInfo, notes: e.target.value })}
              rows={3}
              className="w-full px-3 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white resize-none"
              placeholder="Any special requests or notes..."
            />
          </div>
        </div>
      </div>

      <div className="flex justify-end">
        <button
          onClick={handleContinueToConfirm}
          disabled={!guestInfo.firstName || !guestInfo.lastName || !guestInfo.email}
          className="px-6 py-3 bg-indigo-600 text-white rounded-lg font-medium disabled:opacity-50 disabled:cursor-not-allowed hover:bg-indigo-700 transition-colors flex items-center"
        >
          Review Booking
          <ArrowRight className="w-4 h-4 ml-2" />
        </button>
      </div>
    </div>
  );

  const renderConfirmStep = () => (
    <div className="space-y-6 max-w-lg mx-auto">
      <button
        onClick={() => setStep('details')}
        className="flex items-center text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white text-sm"
      >
        <ChevronLeft className="w-4 h-4 mr-1" />
        Back to your info
      </button>

      <div className="text-center">
        <h3 className="text-xl font-semibold text-gray-900 dark:text-white">Confirm Your Booking</h3>
        <p className="text-gray-500 dark:text-gray-400 mt-1">Please review the details below</p>
      </div>

      <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-6 space-y-4">
        <div className="flex justify-between items-start pb-4 border-b border-gray-200 dark:border-gray-700">
          <div>
            <p className="text-sm text-gray-500 dark:text-gray-400">Service</p>
            <p className="text-lg font-semibold text-gray-900 dark:text-white">{selectedService?.name}</p>
            <p className="text-sm text-gray-600 dark:text-gray-400">
              {selectedService?.duration} minutes
            </p>
          </div>
          {showPrices && selectedService && (
            <p className="text-lg font-bold text-gray-900 dark:text-white">
              {formatPrice(selectedService.price_cents)}
            </p>
          )}
        </div>

        <div className="pb-4 border-b border-gray-200 dark:border-gray-700">
          <p className="text-sm text-gray-500 dark:text-gray-400">Date & Time</p>
          <p className="text-lg font-semibold text-gray-900 dark:text-white">
            {selectedDate?.toLocaleDateString('en-US', {
              weekday: 'long',
              month: 'long',
              day: 'numeric',
              year: 'numeric',
            })}
          </p>
          <p className="text-gray-600 dark:text-gray-400">{selectedTimeSlot}</p>
        </div>

        <div>
          <p className="text-sm text-gray-500 dark:text-gray-400">Contact Information</p>
          <p className="font-semibold text-gray-900 dark:text-white">
            {guestInfo.firstName} {guestInfo.lastName}
          </p>
          <p className="text-gray-600 dark:text-gray-400">{guestInfo.email}</p>
          {guestInfo.phone && <p className="text-gray-600 dark:text-gray-400">{guestInfo.phone}</p>}
        </div>

        {guestInfo.notes && (
          <div className="pt-4 border-t border-gray-200 dark:border-gray-700">
            <p className="text-sm text-gray-500 dark:text-gray-400">Notes</p>
            <p className="text-gray-700 dark:text-gray-300">{guestInfo.notes}</p>
          </div>
        )}
      </div>

      <button
        onClick={handleSubmitBooking}
        disabled={isSubmitting}
        className="w-full py-3 bg-indigo-600 text-white rounded-lg font-semibold disabled:opacity-50 hover:bg-indigo-700 transition-colors flex items-center justify-center"
      >
        {isSubmitting ? (
          <>
            <Loader2 className="w-4 h-4 mr-2 animate-spin" />
            Booking...
          </>
        ) : (
          <>
            <Check className="w-4 h-4 mr-2" />
            Confirm Booking
          </>
        )}
      </button>
    </div>
  );

  const renderSuccessStep = () => (
    <div className="text-center py-12 max-w-lg mx-auto">
      <div className="w-16 h-16 bg-green-100 dark:bg-green-900/30 rounded-full flex items-center justify-center mx-auto mb-6">
        <Check className="w-8 h-8 text-green-600 dark:text-green-400" />
      </div>
      <h3 className="text-2xl font-bold text-gray-900 dark:text-white mb-2">
        {successMessage || 'Booking Confirmed!'}
      </h3>
      <p className="text-gray-500 dark:text-gray-400 mb-6">
        A confirmation email has been sent to {guestInfo.email}
      </p>

      <div className="bg-gray-50 dark:bg-gray-800 rounded-lg p-4 mb-6 text-left">
        <p className="text-sm text-gray-600 dark:text-gray-400">
          <span className="font-medium text-gray-900 dark:text-white">{selectedService?.name}</span>
          <br />
          {selectedDate?.toLocaleDateString('en-US', {
            weekday: 'long',
            month: 'long',
            day: 'numeric',
          })}{' '}
          at {selectedTimeSlot}
        </p>
      </div>

      <div className="flex gap-4 justify-center">
        <button
          onClick={handleReset}
          className="px-6 py-2 bg-indigo-600 text-white rounded-lg font-medium hover:bg-indigo-700 transition-colors"
        >
          Book Another
        </button>
        {successRedirectUrl && (
          <a
            href={successRedirectUrl}
            className="px-6 py-2 border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 rounded-lg font-medium hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors"
          >
            Continue
          </a>
        )}
      </div>
    </div>
  );

  return (
    <section
      id={designControls.anchorId || undefined}
      className={applied.className}
      style={applied.style}
    >
      <div className={`${applied.containerClassName || 'max-w-4xl'} mx-auto px-4 sm:px-6 lg:px-8`}>
        {/* Header */}
        {(headline || subheadline) && step !== 'success' && (
          <div className="text-center mb-8">
            {headline && (
              <h2
                className={`text-3xl sm:text-4xl font-bold mb-4 ${
                  applied.textClassName || 'text-gray-900 dark:text-white'
                }`}
              >
                {headline}
              </h2>
            )}
            {subheadline && (
              <p className="text-lg text-gray-600 dark:text-gray-300 max-w-2xl mx-auto">
                {subheadline}
              </p>
            )}
          </div>
        )}

        {/* Step indicator */}
        {renderStepIndicator()}

        {/* Step content */}
        {step === 'service' && renderServiceStep()}
        {step === 'datetime' && renderDateTimeStep()}
        {step === 'details' && renderDetailsStep()}
        {step === 'confirm' && renderConfirmStep()}
        {step === 'success' && renderSuccessStep()}
      </div>
    </section>
  );
};

const designControlFields = createDesignControlsFields();

export const FullBookingFlow: ComponentConfig<FullBookingFlowProps> = {
  label: 'Full Booking Flow',
  fields: {
    headline: {
      type: 'text',
      label: 'Headline',
    },
    subheadline: {
      type: 'textarea',
      label: 'Subheadline',
    },
    showPrices: {
      type: 'radio',
      label: 'Show Prices',
      options: [
        { label: 'Yes', value: true },
        { label: 'No', value: false },
      ],
    },
    showDuration: {
      type: 'radio',
      label: 'Show Duration',
      options: [
        { label: 'Yes', value: true },
        { label: 'No', value: false },
      ],
    },
    showDeposits: {
      type: 'radio',
      label: 'Show Deposits',
      options: [
        { label: 'Yes', value: true },
        { label: 'No', value: false },
      ],
    },
    allowGuestCheckout: {
      type: 'radio',
      label: 'Allow Guest Checkout',
      options: [
        { label: 'Yes (no account required)', value: true },
        { label: 'No (require account)', value: false },
      ],
    },
    successMessage: {
      type: 'text',
      label: 'Success Message',
    },
    successRedirectUrl: {
      type: 'text',
      label: 'Success Redirect URL (optional)',
    },
    // Design Controls
    padding: designControlFields.padding,
    backgroundVariant: designControlFields.backgroundVariant,
    gradientPreset: designControlFields.gradientPreset,
    contentMaxWidth: designControlFields.contentMaxWidth,
    anchorId: designControlFields.anchorId,
  },
  defaultProps: {
    headline: 'Book Your Appointment',
    subheadline: 'Select a service, choose a time, and complete your booking in minutes.',
    showPrices: true,
    showDuration: true,
    showDeposits: true,
    allowGuestCheckout: true,
    successMessage: 'Booking Confirmed!',
    padding: 'xl',
    backgroundVariant: 'light',
    contentMaxWidth: 'normal',
  },
  render: FullBookingFlowRender,
};

export default FullBookingFlow;
