import React, { useState, useEffect } from 'react';
import DatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css';
import { useSearchParams } from 'react-router-dom';
import { useFormatCurrency } from '../../payments/hooks/useFormatCurrency';
import { Calendar, DollarSign, Users, X } from 'lucide-react';
import { useTheme } from '../../../shared/contexts/ThemeContext';
import { getThemeTextClasses, getThemeCardClasses, getThemeInputClasses } from '../../../shared/utils/themeUtils';

interface RoomFilterProps {
  onFilterChange?: (filters: FilterValues) => void;
}

export interface FilterValues {
  type?: string;
  minPrice?: number;
  maxPrice?: number;
  capacity?: number;
  from?: string;
  to?: string;
}

const RoomFilter: React.FC<RoomFilterProps> = ({ onFilterChange }) => {
  const { theme } = useTheme();
  const textClasses = getThemeTextClasses(theme.theme_layout_mode);
  const cardClasses = getThemeCardClasses(theme.theme_layout_mode);
  const inputClasses = getThemeInputClasses(theme.theme_layout_mode);
  const [searchParams, setSearchParams] = useSearchParams();
  const { formatCurrency: formatCurrencyUtil } = useFormatCurrency();

  const [filters, setFilters] = useState<FilterValues>({
    type: searchParams.get('type') || '',
    minPrice: searchParams.get('minPrice') 
      ? Number(searchParams.get('minPrice')) 
      : undefined,
    maxPrice: searchParams.get('maxPrice')
      ? Number(searchParams.get('maxPrice'))
      : undefined,
    capacity: searchParams.get('capacity')
      ? Number(searchParams.get('capacity'))
      : undefined,
    from: searchParams.get('from') || undefined,
    to: searchParams.get('to') || undefined,
  });

  const [availableAmenities, setAvailableAmenities] = useState<string[]>([]);
  const [selectedAmenities, setSelectedAmenities] = useState<string[]>(
    searchParams.get('amenities')
      ? searchParams.get('amenities')!.split(',').map((s) => s.trim())
      : []
  );

  const [checkInDate, setCheckInDate] = useState<Date | null>(
    searchParams.get('from') ? new Date(searchParams.get('from')!) : null
  );
  const [checkOutDate, setCheckOutDate] = useState<Date | null>(
    searchParams.get('to') ? new Date(searchParams.get('to')!) : null
  );

  

  
  useEffect(() => {
    const type = searchParams.get('type') || '';
    const minPrice = searchParams.get('minPrice')
      ? Number(searchParams.get('minPrice'))
      : undefined;
    const maxPrice = searchParams.get('maxPrice')
      ? Number(searchParams.get('maxPrice'))
      : undefined;
    const capacity = searchParams.get('capacity')
      ? Number(searchParams.get('capacity'))
      : undefined;
    const from = searchParams.get('from') || undefined;
    const to = searchParams.get('to') || undefined;

    setFilters({ type, minPrice, maxPrice, capacity, from, to });

    
    const checkIn = from ? new Date(from) : null;
    const checkOut = to ? new Date(to) : null;
    
    setCheckInDate(checkIn);
    
    if (checkIn && checkOut && checkOut <= checkIn) {
      setCheckOutDate(null);
    } else {
      setCheckOutDate(checkOut);
    }
  }, [searchParams]);

  
  useEffect(() => {
    if (checkInDate && checkOutDate && checkOutDate <= checkInDate) {
      setCheckOutDate(null);
    }
  }, [checkInDate, checkOutDate]);

  
  useEffect(() => {
    let mounted = true;
    import('../services/roomService').then((mod) => {
      mod.getAmenities().then((res) => {
        const list = res.data?.amenities || [];
        if (mounted) setAvailableAmenities(list);
      }).catch(() => {});
    });
    return () => {
      mounted = false;
    };
  }, []);

  const parseCurrency = (value: string): number | undefined => {
    const digits = value.replace(/\D/g, '');
    if (!digits) return undefined;
    try {
      return Number(digits);
    } catch {
      return undefined;
    }
  };

  
  const formatCurrency = (n?: number): string => {
    if (n == null) return '';
    return formatCurrencyUtil(n);
  };

  const handleInputChange = (
    e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>
  ) => {
    const { name, value } = e.target;

    
    if (name === 'type') {
      setFilters((prev) => ({ ...prev, type: value || '' }));
      return;
    }

    
    if (name === 'capacity') {
      setFilters((prev) => ({
        ...prev,
        capacity: value === '' ? undefined : Number(value),
      }));
      return;
    }

    
    if (name === 'minPrice' || name === 'maxPrice') {
      const parsed = parseCurrency(value);
      setFilters((prev) => ({ ...prev, [name]: parsed }));
      return;
    }

    
    setFilters((prev) => ({
      ...prev,
      [name]: value === '' ? undefined : Number(value),
    }));
  };

  const formatDate = (d: Date) => d.toISOString().split('T')[0];

  
  

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

    
    const newParams = new URLSearchParams(searchParams);
    
    
    newParams.set('page', '1');

    
    if (filters.type) {
      newParams.set('type', filters.type);
    } else {
      newParams.delete('type');
    }

    if (filters.minPrice !== undefined && filters.minPrice > 0) {
      newParams.set('minPrice', String(filters.minPrice));
    } else {
      newParams.delete('minPrice');
    }

    if (filters.maxPrice !== undefined && filters.maxPrice > 0) {
      newParams.set('maxPrice', String(filters.maxPrice));
    } else {
      newParams.delete('maxPrice');
    }

    if (filters.capacity !== undefined && filters.capacity > 0) {
      newParams.set('capacity', String(filters.capacity));
    } else {
      newParams.delete('capacity');
    }

    
    if (checkInDate) {
      newParams.set('from', formatDate(checkInDate));
    } else {
      newParams.delete('from');
    }

    if (checkOutDate) {
      newParams.set('to', formatDate(checkOutDate));
    } else {
      newParams.delete('to');
    }
    
    if (selectedAmenities.length > 0) {
      newParams.set('amenities', selectedAmenities.join(','));
    } else {
      newParams.delete('amenities');
    }

    setSearchParams(newParams);
    onFilterChange?.({
      ...filters,
      from: checkInDate ? formatDate(checkInDate) : undefined,
      to: checkOutDate ? formatDate(checkOutDate) : undefined,
      
      ...(selectedAmenities.length > 0 ? { amenities: selectedAmenities.join(',') } : {}),
    });
  };

  const handleReset = () => {
    setFilters({
      type: '',
      minPrice: undefined,
      maxPrice: undefined,
      capacity: undefined,
      from: undefined,
      to: undefined,
    });

    setCheckInDate(null);
    setCheckOutDate(null);
    setSelectedAmenities([]);

    
    setSearchParams({});
    onFilterChange?.({});
  };

  const toggleAmenity = (amenity: string) => {
    setSelectedAmenities((prev) => {
      if (prev.includes(amenity)) return prev.filter((a) => a !== amenity);
      return [...prev, amenity];
    });
  };

  return (
    <div className={`${cardClasses} 
      rounded-xl border border-[var(--luxury-gold)]/30 
      backdrop-blur-xl shadow-2xl shadow-[var(--luxury-gold)]/10 
      p-4 sm:p-5 md:p-6`}
    >
      <div className="flex items-center gap-2 sm:gap-3 mb-4 sm:mb-5 md:mb-6">
        <div className="p-1.5 sm:p-2 bg-[var(--luxury-gold)]/10 rounded-lg 
          border border-[var(--luxury-gold)]/30">
          <svg className="w-4 h-4 sm:w-5 sm:h-5 text-[var(--luxury-gold)]" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 4a1 1 0 011-1h16a1 1 0 011 1v2.586a1 1 0 01-.293.707l-6.414 6.414a1 1 0 00-.293.707V17l-4 4v-6.586a1 1 0 00-.293-.707L3.293 7.293A1 1 0 013 6.586V4z" />
          </svg>
        </div>
        <h2 className={`text-lg sm:text-xl font-serif font-semibold mb-0 ${textClasses.primary} tracking-tight`}>
          Room Filters
        </h2>
      </div>
      <form onSubmit={handleSubmit} className="space-y-3 sm:space-y-4">
        {}
        <div>
          <label 
            htmlFor="type" 
            className={`block text-sm font-medium 
              ${textClasses.secondary} mb-2 tracking-wide`}
          >
            Room Type
          </label>
          <div className="relative">
          <select
            id="type"
            name="type"
            value={filters.type || ''}
            onChange={handleInputChange}
              className={`w-full px-4 py-3.5 ${inputClasses} border-2
                border-[var(--luxury-gold)]/30 rounded-lg text-base
                placeholder-gray-400 focus:ring-2 
                focus:ring-[var(--luxury-gold)]/60 focus:border-[var(--luxury-gold)] 
                transition-all duration-300 font-normal tracking-wide
                appearance-none cursor-pointer
                hover:border-[var(--luxury-gold)]/50`}
          >
              <option value="" className={theme.theme_layout_mode === 'light' ? 'bg-white text-gray-900' : 'bg-[#1a1a1a] text-white'}>All Room Types</option>
              <option value="Standard Room" className={theme.theme_layout_mode === 'light' ? 'bg-white text-gray-900' : 'bg-[#1a1a1a] text-white'}>Standard Room</option>
              <option value="Deluxe Room" className={theme.theme_layout_mode === 'light' ? 'bg-white text-gray-900' : 'bg-[#1a1a1a] text-white'}>Deluxe Room</option>
              <option value="Luxury Room" className={theme.theme_layout_mode === 'light' ? 'bg-white text-gray-900' : 'bg-[#1a1a1a] text-white'}>Luxury Room</option>
              <option value="Family Room" className={theme.theme_layout_mode === 'light' ? 'bg-white text-gray-900' : 'bg-[#1a1a1a] text-white'}>Family Room</option>
              <option value="Twin Room" className={theme.theme_layout_mode === 'light' ? 'bg-white text-gray-900' : 'bg-[#1a1a1a] text-white'}>Twin Room</option>
          </select>
            <div className="absolute right-3 top-1/2 -translate-y-1/2 pointer-events-none">
              <svg className="w-5 h-5 text-[var(--luxury-gold)]" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
              </svg>
            </div>
          </div>
        </div>

        {}
        <div className="space-y-4">
          <div>
            <label
              htmlFor="from"
              className={`block text-sm font-medium ${textClasses.secondary} mb-2 tracking-wide flex items-center gap-2`}
            >
              <Calendar className="w-4 h-4 text-[var(--luxury-gold)]" />
              Check-in Date
            </label>
            <div className="relative">
            <DatePicker
              selected={checkInDate}
                onChange={(date: Date | null) => {
                  setCheckInDate(date);
                  
                  if (date && checkOutDate && checkOutDate <= date) {
                    setCheckOutDate(null);
                  }
                }}
              selectsStart
              startDate={checkInDate}
              endDate={checkOutDate}
              minDate={new Date()}
              dateFormat="dd/MM/yyyy"
                placeholderText="Select check-in"
                className={`w-full px-4 py-3.5 pl-11 ${inputClasses} border-2
                  border-[var(--luxury-gold)]/30 rounded-lg text-base
                  placeholder-gray-400 focus:ring-2 
                  focus:ring-[var(--luxury-gold)]/60 focus:border-[var(--luxury-gold)] 
                  transition-all duration-300 font-normal tracking-wide
                  hover:border-[var(--luxury-gold)]/50`}
                wrapperClassName="w-full"
              />
              {checkInDate && (
                <button
                  type="button"
                  onClick={(e) => {
                    e.stopPropagation();
                    setCheckInDate(null);
                    if (checkOutDate) {
                      setCheckOutDate(null);
                    }
                  }}
                  className={`absolute right-3 top-1/2 -translate-y-1/2 
                    ${textClasses.muted} hover:text-[var(--luxury-gold)] transition-colors`}
                >
                  <X className="w-4 h-4" />
                </button>
              )}
              <Calendar className="absolute left-3 top-1/2 -translate-y-1/2 
                w-5 h-5 text-[var(--luxury-gold)] pointer-events-none" />
            </div>
          </div>

          <div>
            <label
              htmlFor="to"
              className={`block text-sm font-medium ${textClasses.secondary} mb-2 tracking-wide flex items-center gap-2`}
            >
              <Calendar className="w-4 h-4 text-[var(--luxury-gold)]" />
              Check-out Date
            </label>
            <div className="relative">
            <DatePicker
              selected={checkOutDate}
              onChange={(date: Date | null) => setCheckOutDate(date)}
              selectsEnd
              startDate={checkInDate}
              endDate={checkOutDate}
                minDate={
                  checkInDate 
                    ? new Date(checkInDate.getTime() + 24 * 60 * 60 * 1000) 
                    : new Date()
                }
                disabled={!checkInDate}
              dateFormat="dd/MM/yyyy"
                placeholderText={checkInDate ? "Select check-out" : "Select check-in first"}
                className={`w-full px-4 py-3.5 pl-11 ${inputClasses} border-2
                  border-[var(--luxury-gold)]/30 rounded-lg text-base
                  placeholder-gray-400 focus:ring-2 
                  focus:ring-[var(--luxury-gold)]/60 focus:border-[var(--luxury-gold)] 
                  transition-all duration-300 font-normal tracking-wide
                  hover:border-[var(--luxury-gold)]/50
                  disabled:opacity-50 disabled:cursor-not-allowed`}
                wrapperClassName="w-full"
              />
              {checkOutDate && (
                <button
                  type="button"
                  onClick={(e) => {
                    e.stopPropagation();
                    setCheckOutDate(null);
                  }}
                  className={`absolute right-3 top-1/2 -translate-y-1/2 
                    ${textClasses.muted} hover:text-[var(--luxury-gold)] transition-colors`}
                >
                  <X className="w-4 h-4" />
                </button>
              )}
              <Calendar className="absolute left-3 top-1/2 -translate-y-1/2 
                w-5 h-5 text-[var(--luxury-gold)] pointer-events-none" />
            </div>
            {checkInDate && !checkOutDate && (
              <p className={`mt-1.5 text-xs ${textClasses.muted} font-light`}>
                Select check-out date (minimum 1 night stay)
              </p>
            )}
          </div>
        </div>

        {}
        <div>
          <label className={`block text-sm font-medium ${textClasses.secondary} mb-3 tracking-wide flex items-center gap-2`}>
            <DollarSign className="w-4 h-4 text-[var(--luxury-gold)]" />
            Price Range
          </label>
        <div className="grid grid-cols-2 gap-4">
          <div>
            <label
              htmlFor="minPrice"
                className={`block text-xs font-normal 
                  ${textClasses.muted} mb-1.5 tracking-wide`}
            >
                Minimum
            </label>
              <div className="relative">
                <DollarSign className="absolute left-3 top-1/2 -translate-y-1/2 
                  w-4 h-4 text-[var(--luxury-gold)] pointer-events-none" />
            <input
              type="text"
              id="minPrice"
              name="minPrice"
              value={
                filters.minPrice != null
                  ? formatCurrency(filters.minPrice)
                  : ''
              }
              onChange={handleInputChange}
              placeholder="0"
              inputMode="numeric"
              pattern="[0-9.]*"
                  className={`w-full px-4 py-3.5 pl-10 ${inputClasses} border-2
                    border-[var(--luxury-gold)]/30 rounded-lg text-base
                    placeholder-gray-400 focus:ring-2 
                    focus:ring-[var(--luxury-gold)]/60 focus:border-[var(--luxury-gold)] 
                    transition-all duration-300 font-normal tracking-wide
                    hover:border-[var(--luxury-gold)]/50`}
            />
              </div>
          </div>
          <div>
            <label
              htmlFor="maxPrice"
                className={`block text-xs font-normal 
                  ${textClasses.muted} mb-1.5 tracking-wide`}
            >
                Maximum
            </label>
              <div className="relative">
                <DollarSign className="absolute left-3 top-1/2 -translate-y-1/2 
                  w-4 h-4 text-[var(--luxury-gold)] pointer-events-none" />
            <input
              type="text"
              id="maxPrice"
              name="maxPrice"
              value={
                filters.maxPrice != null
                  ? formatCurrency(filters.maxPrice)
                  : ''
              }
              onChange={handleInputChange}
                  placeholder="No limit"
              inputMode="numeric"
              pattern="[0-9.]*"
                  className={`w-full px-4 py-3.5 pl-10 ${inputClasses} border-2
                    border-[var(--luxury-gold)]/30 rounded-lg text-base
                    placeholder-gray-400 focus:ring-2 
                    focus:ring-[var(--luxury-gold)]/60 focus:border-[var(--luxury-gold)] 
                    transition-all duration-300 font-normal tracking-wide
                    hover:border-[var(--luxury-gold)]/50`}
            />
              </div>
            </div>
          </div>
        </div>

        {}
        <div>
          <label
            htmlFor="capacity"
            className={`block text-sm font-medium 
              ${textClasses.secondary} mb-2 tracking-wide flex items-center gap-2`}
          >
            <Users className="w-4 h-4 text-[var(--luxury-gold)]" />
            Number of Guests
          </label>
          <div className="relative">
            <Users className="absolute left-3 top-1/2 -translate-y-1/2 
              w-5 h-5 text-[var(--luxury-gold)] pointer-events-none" />
          <input
            type="number"
            id="capacity"
            name="capacity"
            value={filters.capacity || ''}
            onChange={handleInputChange}
            placeholder="1"
            min="1"
            max="10"
              className={`w-full px-4 py-3.5 pl-11 ${inputClasses} border-2
                border-[var(--luxury-gold)]/30 rounded-lg text-base
                placeholder-gray-400 focus:ring-2 
                focus:ring-[var(--luxury-gold)]/60 focus:border-[var(--luxury-gold)] 
                transition-all duration-300 font-normal tracking-wide
                hover:border-[var(--luxury-gold)]/50
                [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none 
                [&::-webkit-inner-spin-button]:appearance-none`}
          />
          </div>
        </div>

        {}
        <div>
          <label className={`block text-sm font-medium ${textClasses.secondary} mb-3 tracking-wide`}>
            Amenities
          </label>
          {availableAmenities.length === 0 ? (
            <div className={`text-sm ${textClasses.muted} font-light ${theme.theme_layout_mode === 'light' ? 'bg-gray-50' : 'bg-[#1a1a1a]/50'} 
              border border-[var(--luxury-gold)]/20 rounded-lg px-4 py-3`}>
              Loading amenities...
            </div>
          ) : (
            <div className={`${theme.theme_layout_mode === 'light' ? 'bg-gray-50' : 'bg-[#1a1a1a]/50'} border border-[var(--luxury-gold)]/20 rounded-lg p-3 
              max-h-48 overflow-y-auto custom-scrollbar space-y-2`}>
              {availableAmenities.map((amenity) => (
                <label
                  key={amenity}
                  className={`flex items-center gap-3 text-sm w-full font-normal tracking-wide 
                    hover:text-[var(--luxury-gold)] transition-colors cursor-pointer 
                    ${textClasses.secondary} group`}
                >
                  <input
                    type="checkbox"
                    checked={selectedAmenities.includes(amenity)}
                    onChange={() => toggleAmenity(amenity)}
                    className="h-5 w-5 accent-[var(--luxury-gold)] cursor-pointer 
                      border-2 border-[var(--luxury-gold)]/30 rounded 
                      checked:bg-[var(--luxury-gold)] checked:border-[var(--luxury-gold)]
                      group-hover:border-[var(--luxury-gold)] transition-all"
                  />
                  <span className="flex-1 group-hover:text-[var(--luxury-gold)] transition-colors">
                    {amenity}
                  </span>
                </label>
              ))}
            </div>
          )}
          {selectedAmenities.length > 0 && (
            <p className="mt-2 text-xs text-[var(--luxury-gold)] font-light">
              {selectedAmenities.length} amenit{selectedAmenities.length === 1 ? 'y' : 'ies'} selected
            </p>
          )}
        </div>

        {}
        <div className="flex flex-col sm:flex-row gap-2 sm:gap-3 pt-2">
          <button
            type="submit"
            className="flex-1 bg-gradient-to-r from-[var(--luxury-gold)] to-[var(--luxury-gold-dark)] 
              text-[#0f0f0f] py-2.5 sm:py-3 px-4 rounded-sm font-medium tracking-wide text-sm sm:text-base
              hover:from-[var(--luxury-gold-light)] hover:to-[var(--luxury-gold)] active:scale-95
              transition-all duration-300 shadow-lg shadow-[var(--luxury-gold)]/30
              relative overflow-hidden group touch-manipulation min-h-[44px]"
          >
            <span className="relative z-10">Apply</span>
            <span className="absolute inset-0 bg-gradient-to-r from-white/0 via-white/20 to-white/0 translate-x-[-100%] group-hover:translate-x-[100%] transition-transform duration-700"></span>
          </button>
          <button
            type="button"
            onClick={handleReset}
            className={`flex-1 ${theme.theme_layout_mode === 'light' ? 'bg-gray-100' : 'bg-[#0a0a0a]'} backdrop-blur-sm ${textClasses.secondary} 
              py-2.5 sm:py-3 px-4 rounded-sm border border-[var(--luxury-gold)]/30 
              ${theme.theme_layout_mode === 'light' ? 'hover:bg-gray-200' : 'hover:bg-[#1a1a1a]'} hover:border-[var(--luxury-gold)] hover:text-[var(--luxury-gold)] active:scale-95
              transition-all font-medium tracking-wide text-sm sm:text-base
              touch-manipulation min-h-[44px]`}
          >
            Reset
          </button>
        </div>
      </form>
    </div>
  );
};

export default RoomFilter;
