import React, { useState } from 'react';
import { usePublicServices, useCreateBooking } from '../../hooks/useBooking';
import { Loader2 } from 'lucide-react';

interface BookingWidgetProps {
  headline?: string;
  subheading?: string;
  accentColor?: string;
  buttonLabel?: string;
}

export const BookingWidget: React.FC<BookingWidgetProps> = ({ 
  headline = "Book Appointment", 
  subheading = "Select a service", 
  accentColor = "#2563eb", 
  buttonLabel = "Book Now" 
}) => {
  const { data: services, isLoading } = usePublicServices();
  const createBooking = useCreateBooking();
  const [selectedService, setSelectedService] = useState<any>(null);

  if (isLoading) return <div className="flex justify-center"><Loader2 className="animate-spin" /></div>;

  const handleBook = async () => {
    if (!selectedService) return;
    try {
      await createBooking.mutateAsync({ service_id: selectedService.id });
      alert("Booking created (stub)!");
    } catch (e) {
      console.error(e);
      alert("Error creating booking");
    }
  };

  return (
    <div className="booking-widget p-6 bg-white dark:bg-gray-800 rounded-lg shadow-md dark:shadow-gray-900/30 max-w-md mx-auto text-left border border-gray-100 dark:border-gray-700">
      <h2 className="text-2xl font-bold mb-2 text-indigo-600 dark:text-indigo-400">{headline}</h2>
      <p className="text-gray-600 dark:text-gray-300 mb-6">{subheading}</p>

      <div className="space-y-4 mb-6">
        {services?.length === 0 && <p className="text-gray-600 dark:text-gray-400">No services available.</p>}
        {services?.map((service: any) => (
          <div
            key={service.id}
            className={`p-4 border rounded-lg cursor-pointer transition-all ${
              selectedService?.id === service.id
                ? 'border-indigo-500 bg-indigo-50 dark:bg-indigo-900/20 dark:border-indigo-400'
                : 'border-gray-200 dark:border-gray-700 hover:border-indigo-300 dark:hover:border-indigo-600 bg-white dark:bg-gray-700/50'
            }`}
            onClick={() => setSelectedService(service)}
          >
            <h3 className="font-semibold text-gray-900 dark:text-white">{service.name}</h3>
            <p className="text-sm text-gray-500 dark:text-gray-400">{service.duration} min - ${(service.price_cents / 100).toFixed(2)}</p>
          </div>
        ))}
      </div>

      <button
        onClick={handleBook}
        disabled={!selectedService}
        className="w-full py-3 px-4 rounded-lg bg-indigo-600 dark:bg-indigo-500 text-white font-semibold disabled:opacity-50 hover:bg-indigo-700 dark:hover:bg-indigo-600 transition-all shadow-sm hover:shadow-md"
      >
        {buttonLabel}
      </button>
    </div>
  );
};

export default BookingWidget;
