import React, { useState } from 'react';
import { Calendar as CalendarIcon, Clock, UserPlus, ShoppingCart, Phone, Mail, X } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card } from '@/components/ui/card';
import { Calendar } from '@/components/ui/calendar';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { Badge } from '@/components/ui/badge';
import { useIsMobile } from '@/hooks/use-mobile';
import { cn } from '@/lib/utils';
import { format } from 'date-fns';
import { es } from 'date-fns/locale';
import { BookingModal } from '@/components/BookingModal';
import { useAuth } from '@/contexts/AuthContext';
import { useNavigate } from 'react-router-dom';
import { useToast } from '@/hooks/use-toast';

interface Listing {
  id: string;
  title: string;
  price: number;
  category: string;
  images: string[];
  location: {
    address: string;
  };
}

interface BookingSidebarProps {
  offer: Listing;
  onBookNow: (date: Date | undefined, guests: number, timeSlot?: string) => void;
  onAddToCart: (date: Date | undefined, guests: number, timeSlot?: string) => void;
}

interface AvailableDate {
  date: Date;
  available: boolean;
  timeSlots?: string[];
}

const BookingSidebar: React.FC<BookingSidebarProps> = ({ offer, onBookNow, onAddToCart }) => {
  const [selectedDate, setSelectedDate] = useState<Date | undefined>(undefined);
  const [selectedTimeSlot, setSelectedTimeSlot] = useState<string>('');
  const [guests, setGuests] = useState(1);
  const [isOpen, setIsOpen] = useState(false);
  const [showBookingModal, setShowBookingModal] = useState(false);
  const isMobile = useIsMobile();
  const { isAuthenticated } = useAuth();
  const navigate = useNavigate();
  const { toast } = useToast();

  // Mock available dates - in real app this would come from API
  const availableDates: AvailableDate[] = [
    { date: new Date(2025, 8, 15), available: true, timeSlots: ['09:00', '12:00', '15:00', '18:00'] },
    { date: new Date(2025, 8, 16), available: true, timeSlots: ['09:00', '15:00', '18:00'] },
    { date: new Date(2025, 8, 17), available: false },
    { date: new Date(2025, 8, 18), available: true, timeSlots: ['12:00', '15:00', '18:00'] },
    { date: new Date(2025, 8, 20), available: true, timeSlots: ['09:00', '12:00', '15:00'] },
    { date: new Date(2025, 8, 22), available: true, timeSlots: ['09:00', '12:00', '15:00', '18:00'] },
    { date: new Date(2025, 8, 25), available: true, timeSlots: ['10:00', '14:00', '16:00', '19:00'] },
    { date: new Date(2025, 8, 28), available: true, timeSlots: ['09:00', '13:00', '17:00'] },
  ];

  const isDateAvailable = (date: Date) => {
    return availableDates.some(d => 
      d.date.toDateString() === date.toDateString() && d.available
    );
  };

  const getTimeSlots = (date: Date) => {
    const availableDate = availableDates.find(d => 
      d.date.toDateString() === date.toDateString()
    );
    return availableDate?.timeSlots || [];
  };

  const handleDateSelect = (date: Date | undefined) => {
    setSelectedDate(date);
    setSelectedTimeSlot('');
  };

  const handleBookNow = () => {
    if (!isAuthenticated) {
      toast({
        title: 'Inicia sesión',
        description: 'Debes iniciar sesión para hacer una reserva',
        variant: 'destructive',
      });
      navigate('/sign-in');
      return;
    }

    if (!selectedDate) {
      toast({
        title: 'Selecciona una fecha',
        description: 'Por favor selecciona una fecha para continuar',
        variant: 'destructive',
      });
      return;
    }

    setShowBookingModal(true);
  };

  const handleAddToCart = () => {
    if (!selectedDate) {
      toast({
        title: 'Selecciona una fecha',
        description: 'Por favor selecciona una fecha para agregar al carrito',
        variant: 'destructive',
      });
      return;
    }
    onAddToCart(selectedDate, guests, selectedTimeSlot);
    if (isMobile) setIsOpen(false);
  };

  const handleBookingSuccess = () => {
    // Navigate to bookings page or show confirmation
    navigate('/dashboard/bookings');
  };

  const isFormValid = selectedDate && (offer.category === 'tour' ? selectedTimeSlot : true);

  const BookingForm = () => (
    <div className="space-y-4">
      <div className="text-center mb-6">
        <div className="text-3xl font-bold text-primary mb-2">
          ${offer.price}
          <span className="text-base font-normal text-muted-foreground">
            {offer.category === 'hotel' ? '/noche' : offer.category === 'restaurant' ? '/persona' : '/tour'}
          </span>
        </div>
      </div>

      {/* Calendar */}
      <div>
        <Label>Selecciona una fecha</Label>
        <Popover>
          <PopoverTrigger asChild>
            <Button
              variant="outline"
              className={cn(
                "w-full justify-start text-left font-normal",
                !selectedDate && "text-muted-foreground"
              )}
            >
              <CalendarIcon className="mr-2 h-4 w-4" />
              {selectedDate ? (
                <span>
                  {format(selectedDate, "MMMM d, yyyy", { locale: es })}
                  {selectedTimeSlot && ` - ${selectedTimeSlot}`}
                </span>
              ) : (
                <span>Elige una fecha</span>
              )}
            </Button>
          </PopoverTrigger>
          <PopoverContent className="w-auto p-0" align="start">
            <Calendar
              mode="single"
              selected={selectedDate}
              onSelect={handleDateSelect}
              disabled={(date) => {
                const today = new Date();
                today.setHours(0, 0, 0, 0);
                return date < today || !isDateAvailable(date);
              }}
              modifiers={{
                available: (date) => isDateAvailable(date),
                booked: (date) => !isDateAvailable(date) && date >= new Date()
              }}
              modifiersStyles={{
                available: { 
                  backgroundColor: 'hsl(var(--foreground))', 
                  color: 'hsl(var(--background))',
                  fontWeight: 'bold',
                  borderRadius: '6px',
                  border: '2px solid hsl(var(--primary))'
                },
                booked: { 
                  backgroundColor: 'hsl(var(--muted))', 
                  color: 'hsl(var(--muted-foreground))',
                  textDecoration: 'line-through',
                  opacity: '0.5'
                }
              }}
              modifiersClassNames={{
                available: 'hover:bg-primary hover:text-primary-foreground cursor-pointer transition-colors',
                booked: 'cursor-not-allowed'
              }}
              initialFocus
              className="pointer-events-auto"
            />
            <div className="p-3 border-t">
              <div className="flex gap-4 text-xs">
                <div className="flex items-center gap-1">
                  <div className="w-3 h-3 rounded-sm bg-foreground border border-primary"></div>
                  <span>Disponible</span>
                </div>
                <div className="flex items-center gap-1">
                  <div className="w-3 h-3 rounded-sm bg-muted opacity-50"></div>
                  <span>No disponible</span>
                </div>
              </div>
            </div>
          </PopoverContent>
        </Popover>
      </div>

      {/* Time Slots - only for tours and restaurants */}
      {selectedDate && (offer.category === 'tour' || offer.category === 'restaurant') && (
        <div>
          <Label>Horarios disponibles</Label>
          <div className="grid grid-cols-2 gap-2 mt-2">
            {getTimeSlots(selectedDate).map((timeSlot) => (
              <Button
                key={timeSlot}
                variant={selectedTimeSlot === timeSlot ? "default" : "outline"}
                size="sm"
                onClick={() => setSelectedTimeSlot(timeSlot)}
                className="h-8"
              >
                <Clock className="w-3 h-3 mr-1" />
                {timeSlot}
              </Button>
            ))}
          </div>
        </div>
      )}

      {/* Guests */}
      {(offer.category === 'hotel' || offer.category === 'restaurant' || offer.category === 'tour') && (
        <div>
          <Label htmlFor="guests">
            {offer.category === 'hotel' ? 'Huéspedes' : 
             offer.category === 'restaurant' ? 'Personas' : 'Participantes'}
          </Label>
          <Select value={guests.toString()} onValueChange={(value) => setGuests(parseInt(value))}>
            <SelectTrigger>
              <div className="flex items-center">
                <UserPlus className="w-4 h-4 mr-2 text-muted-foreground" />
                <SelectValue />
              </div>
            </SelectTrigger>
            <SelectContent>
              {[1, 2, 3, 4, 5, 6, 7, 8].map(num => (
                <SelectItem key={num} value={num.toString()}>
                  {num} {num === 1 ? 'persona' : 'personas'}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
      )}

      {/* Action Buttons */}
      <div className="space-y-3 pt-4">
        <Button 
          className="w-full" 
          size="lg"
          onClick={handleBookNow}
          disabled={!isFormValid}
        >
          Reservar Ahora
        </Button>
        <Button 
          variant="outline" 
          className="w-full" 
          size="lg"
          onClick={handleAddToCart}
          disabled={!isFormValid}
        >
          <ShoppingCart className="w-4 h-4 mr-2" />
          Agregar al Carrito
        </Button>
        <div className="grid grid-cols-2 gap-2">
          <Button variant="outline" size="sm">
            <Phone className="w-4 h-4 mr-1" />
            Llamar
          </Button>
          <Button variant="outline" size="sm">
            <Mail className="w-4 h-4 mr-1" />
            Contactar
          </Button>
        </div>
      </div>

      {/* Stats */}
      <div className="border-t pt-4 space-y-3 text-sm">
        <div className="flex justify-between">
          <span className="text-muted-foreground">Tiempo de respuesta:</span>
          <span className="font-medium">En 1 hora</span>
        </div>
        <div className="flex justify-between">
          <span className="text-muted-foreground">Tasa de respuesta:</span>
          <span className="font-medium">100%</span>
        </div>
        <div className="flex justify-between">
          <span className="text-muted-foreground">Última vez activo:</span>
          <span className="font-medium">Hace 2 horas</span>
        </div>
      </div>
    </div>
  );

  if (isMobile) {
    return (
      <>
        {/* Mobile Floating Button */}
        <div className="fixed bottom-4 right-4 z-50 lg:hidden">
          <Button 
            size="lg" 
            onClick={() => setIsOpen(true)}
            className="rounded-full shadow-lg px-6 py-3 h-auto min-w-fit"
          >
            <CalendarIcon className="h-5 w-5 mr-2" />
            <span className="font-semibold">Reservar</span>
          </Button>
        </div>

        {/* Mobile Booking Sheet */}
        {isOpen && (
          <div className="fixed inset-0 z-50 lg:hidden">
            <div className="absolute inset-0 bg-black/80" onClick={() => setIsOpen(false)} />
            <div className="absolute bottom-0 left-0 right-0 bg-background rounded-t-2xl">
              <div className="flex items-center justify-between p-4 border-b">
                <h3 className="text-lg font-semibold">Reservar</h3>
                <Button variant="ghost" size="sm" onClick={() => setIsOpen(false)}>
                  <X className="h-4 w-4" />
                </Button>
              </div>
              <div className="p-4 max-h-[80vh] overflow-auto">
                <BookingForm />
              </div>
            </div>
          </div>
        )}

        <BookingModal
          open={showBookingModal}
          onClose={() => setShowBookingModal(false)}
          listingId={offer.id}
          listingTitle={offer.title}
          listingPrice={offer.price}
          selectedDate={selectedDate}
          selectedTimeSlot={selectedTimeSlot}
          guests={guests}
          onSuccess={handleBookingSuccess}
        />
      </>
    );
  }

  // Desktop Sidebar
  return (
    <>
      <Card className="p-6 sticky top-24">
        <BookingForm />
      </Card>

      <BookingModal
        open={showBookingModal}
        onClose={() => setShowBookingModal(false)}
        listingId={offer.id}
        listingTitle={offer.title}
        listingPrice={offer.price}
        selectedDate={selectedDate}
        selectedTimeSlot={selectedTimeSlot}
        guests={guests}
        onSuccess={handleBookingSuccess}
      />
    </>
  );
};

export default BookingSidebar;