import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import DatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css';
import { Search } from 'lucide-react';
import { toast } from 'react-toastify';

interface SearchRoomFormProps {
  className?: string;
}

const SearchRoomForm: React.FC<SearchRoomFormProps> = ({
  className = '',
}) => {
  const navigate = useNavigate();
  const [checkInDate, setCheckInDate] = useState<Date | null>(null);
  const [checkOutDate, setCheckOutDate] = useState<Date | null>(null);
  const [roomType, setRoomType] = useState('');
  const [guestCount, setGuestCount] = useState<number>(1);
  const [isSearching, setIsSearching] = useState(false);
  const [isMobile, setIsMobile] = useState(false);

  
  useEffect(() => {
    const checkMobile = () => {
      setIsMobile(window.innerWidth < 640);
    };
    checkMobile();
    window.addEventListener('resize', checkMobile);
    return () => window.removeEventListener('resize', checkMobile);
  }, []);

  
  const today = new Date();
  today.setHours(0, 0, 0, 0);

  const handleSearch = (e: React.FormEvent) => {
    e.preventDefault();

    
    if (!checkInDate) {
      toast.error('Please select check-in date');
      return;
    }

    if (!checkOutDate) {
      toast.error('Please select check-out date');
      return;
    }

    
    const checkInStart = new Date(checkInDate);
    checkInStart.setHours(0, 0, 0, 0);
    
    if (checkInStart < today) {
      toast.error(
        'Check-in date cannot be in the past'
      );
      return;
    }

    
    if (checkOutDate <= checkInDate) {
      toast.error(
        'Check-out date must be after check-in date'
      );
      return;
    }

    
    const formatDate = (date: Date) => {
      return date.toISOString().split('T')[0];
    };

    
    const params = new URLSearchParams({
      from: formatDate(checkInDate),
      to: formatDate(checkOutDate),
    });

    if (roomType.trim()) {
      params.append('type', roomType.trim());
    }

    
    if (guestCount && guestCount > 0) {
      params.append('capacity', String(guestCount));
    }

    
    setIsSearching(true);
    navigate(`/rooms/search?${params.toString()}`);
  };

  
  
  
  
  
  
  

  const isOverlay = className.includes('overlay');

  return (
    <div className={`w-full ${isOverlay ? 'bg-transparent shadow-none border-none p-0' : 'luxury-glass rounded-sm shadow-2xl p-6 border border-[#d4af37]/20'} ${className}`}>
      {}
      {(!isOverlay || !isMobile) && (
        <div className={`flex items-center justify-center gap-2 sm:gap-3 ${isOverlay ? 'mb-2 sm:mb-3 md:mb-4 lg:mb-6' : 'mb-6'}`}>
          <div className={`${isOverlay ? 'w-0.5 sm:w-1' : 'w-1'} ${isOverlay ? 'h-4 sm:h-6 md:h-8' : 'h-8'} bg-gradient-to-b from-[#d4af37] to-[#c9a227]`}></div>
          <h3 className={`${isOverlay ? 'text-sm sm:text-base md:text-lg lg:text-xl xl:text-2xl' : 'text-2xl'} font-serif font-semibold text-gray-900 tracking-tight`}>
            {isOverlay && isMobile ? 'Find Rooms' : 'Find Available Rooms'}
          </h3>
          <div className={`${isOverlay ? 'w-0.5 sm:w-1' : 'w-1'} ${isOverlay ? 'h-4 sm:h-6 md:h-8' : 'h-8'} bg-gradient-to-b from-[#d4af37] to-[#c9a227]`}></div>
        </div>
      )}

      <form onSubmit={handleSearch}>
        <div className={`grid ${isOverlay ? 'grid-cols-1 sm:grid-cols-2 lg:grid-cols-12' : 'grid-cols-1 md:grid-cols-12'} ${isOverlay ? 'gap-2 sm:gap-3 md:gap-4' : 'gap-4'} items-end`}>
          <div className={isOverlay ? 'sm:col-span-1 lg:col-span-3' : 'md:col-span-3'}>
            <label className={`block ${isOverlay ? 'text-xs sm:text-sm' : 'text-sm'} font-medium text-gray-700 ${isOverlay ? 'mb-1 sm:mb-2' : 'mb-2'} tracking-wide`}>Check-in</label>
            <DatePicker
              selected={checkInDate}
              onChange={(date) => setCheckInDate(date)}
              selectsStart
              startDate={checkInDate}
              endDate={checkOutDate}
              minDate={today}
              placeholderText="Check-in"
              dateFormat={isOverlay && isMobile ? "dd/MM" : "dd/MM/yyyy"}
              className={`luxury-input ${isOverlay ? 'text-xs sm:text-sm' : 'text-sm'} ${isOverlay ? 'py-1.5 sm:py-2' : ''}`}
            />
          </div>

          <div className={isOverlay ? 'sm:col-span-1 lg:col-span-3' : 'md:col-span-3'}>
            <label className={`block ${isOverlay ? 'text-xs sm:text-sm' : 'text-sm'} font-medium text-gray-700 ${isOverlay ? 'mb-1 sm:mb-2' : 'mb-2'} tracking-wide`}>Check-out</label>
            <DatePicker
              selected={checkOutDate}
              onChange={(date) => setCheckOutDate(date)}
              selectsEnd
              startDate={checkInDate}
              endDate={checkOutDate}
              minDate={checkInDate || today}
              placeholderText="Check-out"
              dateFormat={isOverlay && isMobile ? "dd/MM" : "dd/MM/yyyy"}
              className={`luxury-input ${isOverlay ? 'text-xs sm:text-sm' : 'text-sm'} ${isOverlay ? 'py-1.5 sm:py-2' : ''}`}
            />
          </div>

          <div className={isOverlay ? 'sm:col-span-1 lg:col-span-2' : 'md:col-span-2'}>
            <label className={`block ${isOverlay ? 'text-xs sm:text-sm' : 'text-sm'} font-medium text-gray-700 ${isOverlay ? 'mb-1 sm:mb-2' : 'mb-2'} tracking-wide`}>Room Type</label>
            <select
              value={roomType}
              onChange={(e) => setRoomType(e.target.value)}
              className={`luxury-input ${isOverlay ? 'text-xs sm:text-sm' : 'text-sm'} ${isOverlay ? 'py-1.5 sm:py-2' : ''}`}
            >
              <option value="">All Types</option>
              <option value="Standard Room">Standard Room</option>
              <option value="Deluxe Room">Deluxe Room</option>
              <option value="Luxury Room">Luxury Room</option>
              <option value="Family Room">Family Room</option>
              <option value="Twin Room">Twin Room</option>
            </select>
          </div>

          <div className={isOverlay ? 'sm:col-span-1 lg:col-span-2' : 'md:col-span-2'}>
            <label className={`block ${isOverlay ? 'text-xs sm:text-sm' : 'text-sm'} font-medium text-gray-700 ${isOverlay ? 'mb-1 sm:mb-2' : 'mb-2'} tracking-wide`}>Guests</label>
            <select
              value={guestCount}
              onChange={(e) => setGuestCount(Number(e.target.value))}
              className={`luxury-input ${isOverlay ? 'text-xs sm:text-sm' : 'text-sm'} ${isOverlay ? 'py-1.5 sm:py-2' : ''}`}
            >
              {Array.from({ length: 6 }).map((_, i) => (
                <option key={i} value={i + 1}>{i + 1} guest{i !== 0 ? 's' : ''}</option>
              ))}
            </select>
          </div>
          
          <div className={`${isOverlay ? 'sm:col-span-2 lg:col-span-2' : 'md:col-span-2'} flex items-end ${isOverlay ? 'mt-1 sm:mt-2 md:mt-0' : 'mt-3 md:mt-0'}`}>
            <button
              type="submit"
              disabled={isSearching}
              className={`btn-luxury-primary w-full flex items-center justify-center gap-1.5 sm:gap-2 ${isOverlay ? 'text-xs sm:text-sm py-1.5 sm:py-2 md:py-3' : 'text-sm'} relative`}
            >
              <Search className={`${isOverlay ? 'w-3 h-3 sm:w-4 sm:h-4' : 'w-4 h-4'} relative z-10`} />
              <span className="relative z-10">
                {isSearching ? 'Searching...' : 'Search'}
              </span>
            </button>
          </div>
        </div>
      </form>
    </div>
  );
};

export default SearchRoomForm;
