'use client';

import { useRef, useEffect, useState } from 'react';
import Image from 'next/image';
import type { City } from '@/types/city';
import type { RecentSearch } from '@/types/city';
import location from '@/public/images/icons/location.png';
import hotel from '@/public/images/icons/hotel.png';

interface LocationSearchDropdownProps {
  showMenu: boolean;
  searchTerm: string;
  setSearchTerm: (value: string) => void;
  cities: City[];
  isSearching: boolean;
  searchError: string | null;
  recentSearches: RecentSearch[];
  isLoadingRecent: boolean;
  recentError: string | null;
  clearResults: () => void;
  clearRecentSearches: () => void;
  handleSelectLocation: (city: City | { cityName: string; code?: string; country?: string; type?: string }) => void;
  typedText: string;
  selectedIndex?: number;
  onStopPropagation?: (e: React.MouseEvent) => void;
  /** When true, show city, destination, and property; hide only country. Use for booking form and SRP form. */
  onlyCityAndProperty?: boolean;
}

export default function LocationSearchDropdown({
  showMenu,
  searchTerm,
  setSearchTerm,
  cities,
  isSearching,
  searchError,
  recentSearches,
  isLoadingRecent,
  recentError,
  clearResults,
  clearRecentSearches,
  handleSelectLocation,
  typedText,
  selectedIndex = -1,
  onStopPropagation,
  onlyCityAndProperty = false
}: LocationSearchDropdownProps) {
  const searchInputRef = useRef<HTMLInputElement>(null);
  const [showNoResults, setShowNoResults] = useState(false);

  // When onlyCityAndProperty: show property, city (location_type 'city'), and destination. Exclude only country.
  // API returns type: 'city' for all; location_type distinguishes 'city' | 'destination' | 'country'.
  const filterCity = (city: City) => {
    if (!city.code) return false;
    if (!onlyCityAndProperty) return true;
    if (city.type === 'property') return true;
    if (city.type === 'city') {
      const loc = city.location_type;
      if (loc === 'country') return false;
      return true; // 'city', 'destination', or undefined/empty → show
    }
    return false;
  };
  const filterRecent = (search: RecentSearch) =>
    (search.code || search.iataCode) &&
    (!onlyCityAndProperty || !search.type || search.type === 'city' || search.type === 'property');
  const filteredCities = cities.filter(filterCity);
  const filteredRecentSearches = recentSearches.filter(filterRecent);

  // Helper function to convert text to title case (first letter of each word uppercase, rest lowercase)
  const toTitleCase = (text: string | undefined): string => {
    if (!text) return '';
    return text
      .toLowerCase()
      .split(' ')
      .map(word => word.charAt(0).toUpperCase() + word.slice(1))
      .join(' ');
  };

  // Auto focus the search input when the menu opens
  useEffect(() => {
    if (showMenu && searchInputRef.current) {
      // Small-delay to ensure the DOM is fully rendered
      const timer = setTimeout(() => {
        searchInputRef.current?.focus();
      }, 100);
      return () => clearTimeout(timer);
    }
  }, [showMenu]);

  // Delay showing "No results" message - wait 1 second after search completes
  useEffect(() => {
    if (!isSearching && searchTerm.length >= 2 && filteredCities.length === 0 && !searchError) {
      const timer = setTimeout(() => {
        setShowNoResults(true);
      }, 1000); // Wait 1 second before showing "No results"
      return () => {
        clearTimeout(timer);
        setShowNoResults(false);
      };
    } else {
      setShowNoResults(false);
    }
  }, [isSearching, searchTerm, filteredCities.length, searchError]);

  return (
    <div
      className={`submenu-web bgColor-white rounded-3 shadow-sm ${showMenu ? 'd-block' : 'd-none'}`}
      onClick={onStopPropagation}
    >
      <div className="card border-0 rounded-2">
        <div className="card-body p-0 text-start">
          {/* Search Input */}
          <div className="d-flex align-items-center search-destination-datalist px-2">
            <div className="flex-shrink-0 pe-2 text-center">
              <svg className="iconSize-15" viewBox="-2 -2 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M8.04937 16.0923C9.837 16.0923 11.5735 15.4959 12.9838 14.3974L18.3044 19.7181C18.7019 20.1019 19.3353 20.0909 19.7191 19.6934C20.0936 19.3057 20.0936 18.691 19.7191 18.3034L14.3985 12.9827C17.1242 9.47394 16.4895 4.41986 12.9807 1.6941C9.47194 -1.03165 4.41791 -0.396918 1.69215 3.11187C-1.03361 6.62065 -0.398871 11.6747 3.10991 14.4005C4.52252 15.4979 6.26057 16.0932 8.04937 16.0923ZM3.77429 3.77316C6.13538 1.41203 9.96346 1.41199 12.3246 3.77308C14.6857 6.13417 14.6858 9.96225 12.3247 12.3234C9.96359 14.6845 6.13551 14.6846 3.77438 12.3235C3.77433 12.3234 3.77433 12.3234 3.77429 12.3234C1.4132 9.97949 1.39929 6.16537 3.74317 3.80428C3.75353 3.79388 3.76389 3.78352 3.77429 3.77316Z" fill="#B6B6B6" />
              </svg>
            </div>
            <div className="flex-grow-1">
              <input
                ref={searchInputRef}
                className="form-control search-destination-field px-0"
                placeholder="Where do you want to stay?"
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                autoComplete="off"
              />
            </div>
            <div className="flex-shrink-0 ps-2">
              <span
                className="clear-input-box"
                role="button"
                onClick={() => {
                  setSearchTerm('');
                  clearResults();
                }}
              >
                CLEAR
              </span>
            </div>
          </div>

          {/* Loading State - Skeleton Loader */}
          {isSearching && (
            <div className="px-3 py-4">
              <div className="d-flex align-items-center gap-3 mb-3">
                <div className="skeleton" style={{ width: '20px', height: '20px', borderRadius: '4px' }}></div>
                <div className="flex-grow-1">
                  <div className="skeleton mb-2" style={{ width: '60%', height: '16px', borderRadius: '4px' }}></div>
                  <div className="skeleton" style={{ width: '40%', height: '14px', borderRadius: '4px' }}></div>
                </div>
              </div>
              <div className="d-flex align-items-center gap-3 mb-3">
                <div className="skeleton" style={{ width: '20px', height: '20px', borderRadius: '4px' }}></div>
                <div className="flex-grow-1">
                  <div className="skeleton mb-2" style={{ width: '70%', height: '16px', borderRadius: '4px' }}></div>
                  <div className="skeleton" style={{ width: '45%', height: '14px', borderRadius: '4px' }}></div>
                </div>
              </div>
              <div className="d-flex align-items-center gap-3">
                <div className="skeleton" style={{ width: '20px', height: '20px', borderRadius: '4px' }}></div>
                <div className="flex-grow-1">
                  <div className="skeleton mb-2" style={{ width: '65%', height: '16px', borderRadius: '4px' }}></div>
                  <div className="skeleton" style={{ width: '50%', height: '14px', borderRadius: '4px' }}></div>
                </div>
              </div>
            </div>
          )}

          {/* Error State */}
          {searchError && (
            <div className="px-3 py-4 text-center">
              <small className="text-danger" style={{ fontSize: '14px' }}>{searchError}</small>
            </div>
          )}

          {/* Search Results */}
          {!isSearching && searchTerm.length >= 2 && filteredCities.length > 0 && (
            <>
              <div className="px-3 pt-2 pb-1">
                <small className="text-uppercase fw-semibold" style={{ fontSize: '11px', color: '#666', letterSpacing: '0.5px' }}>Search Results</small>
              </div>
              <ul className="list-group list-group-flush" style={{ maxHeight: '350px', overflowY: 'auto' }}>
                {filteredCities.map((city, index) => {
                  const isSelected = selectedIndex === index;
                  return (
                    <li
                      key={city.id}
                      className="list-group-item border-0 px-3 py-2 cursor-pointer"
                      onClick={() => handleSelectLocation(city)}
                      style={{
                        transition: 'background-color 0.2s',
                        backgroundColor: isSelected ? '#e7f3ff' : 'transparent',
                      }}
                      onMouseEnter={(e) => {
                        if (!isSelected) {
                          e.currentTarget.style.backgroundColor = '#f8f9fa';
                        }
                      }}
                      onMouseLeave={(e) => {
                        if (!isSelected) {
                          e.currentTarget.style.backgroundColor = 'transparent';
                        }
                      }}
                    >
                      <div className="d-flex align-items-center gap-3">
                        <div style={{ width: '20px', height: '20px', flexShrink: 0 }}>
                          {city.type === 'property' ? (
                            <Image src={hotel} height={20} width={20} alt="hotel" style={{ opacity: 0.6 }} />
                          ) : city.location_type === 'destination' ? (
                            <svg width={20} height={20} viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg" style={{ opacity: 0.6 }}>
                              <path d="M2 6a2 2 0 012-2h12a2 2 0 012 2v8a2 2 0 01-2 2H4a2 2 0 01-2-2V6z" stroke="#B6B6B6" strokeWidth="1.5" fill="none" />
                              <path d="M2 8h16M7 2v4M13 2v4" stroke="#B6B6B6" strokeWidth="1.2" strokeLinecap="round" />
                            </svg>
                          ) : city.location_type === 'country' ? (
                            <svg width={20} height={20} viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg" style={{ opacity: 0.6 }}>
                              <circle cx="10" cy="10" r="7.5" stroke="#B6B6B6" strokeWidth="1.5" fill="none" />
                              <path d="M2 10h16M10 2.5a12.2 12.2 0 013 4.5 12.2 12.2 0 01-3 4.5 12.2 12.2 0 01-3-4.5 12.2 12.2 0 013-4.5z" stroke="#B6B6B6" strokeWidth="1.2" strokeLinecap="round" />
                            </svg>
                          ) : (
                            <Image src={location} height={20} width={20} alt="location" style={{ opacity: 0.6 }} />
                          )}
                        </div>
                        <div className="flex-grow-1">
                          <p className="mb-0 fw-medium" style={{ fontSize: '15px', color: '#212529' }}>
                            {city.type === 'property' ? toTitleCase(city.name) : (city.city_name || city.destination_name || city.country_name || city.name)}
                          </p>
                          {city.type === 'property' ? (
                            city.city_name && (
                              <small className="text-muted" style={{ fontSize: '13px' }}>
                                Hotel in {toTitleCase(city.city_name)}{city.country_name ? `, ${toTitleCase(city.country_name)}` : ''}
                              </small>
                            )
                          ) : city.location_type === 'destination' ? (
                            <small className="text-muted" style={{ fontSize: '13px' }}>
                              State in {city.country_name ? city.country_name : (city.country || '')}
                            </small>
                          ) : city.location_type === 'country' ? null : (
                            city.destination_name && city.country_name && (
                              <small className="text-muted" style={{ fontSize: '13px' }}>
                                {city.destination_name} · {city.country_name}
                              </small>
                            )
                          )}
                        </div>
                      </div>
                    </li>
                  );
                })}
              </ul>
            </>
          )}

          {/* No Results - Small message with delay */}
          {showNoResults && !isSearching && searchTerm.length >= 2 && filteredCities.length === 0 && !searchError && (
            <div className="px-3 py-3 text-center">
              <small style={{ color: '#999', fontSize: '13px' }}>
                No results found for &quot;{searchTerm}&quot;
              </small>
            </div>
          )}

          {/* Loading Recent Searches - Skeleton */}
          {searchTerm.length < 2 && isLoadingRecent && (
            <div className="px-3 py-4">
              <div className="d-flex align-items-center gap-3 mb-3">
                <div className="skeleton" style={{ width: '20px', height: '20px', borderRadius: '4px' }}></div>
                <div className="flex-grow-1">
                  <div className="skeleton mb-2" style={{ width: '60%', height: '16px', borderRadius: '4px' }}></div>
                  <div className="skeleton" style={{ width: '40%', height: '14px', borderRadius: '4px' }}></div>
                </div>
              </div>
              <div className="d-flex align-items-center gap-3">
                <div className="skeleton" style={{ width: '20px', height: '20px', borderRadius: '4px' }}></div>
                <div className="flex-grow-1">
                  <div className="skeleton mb-2" style={{ width: '70%', height: '16px', borderRadius: '4px' }}></div>
                  <div className="skeleton" style={{ width: '45%', height: '14px', borderRadius: '4px' }}></div>
                </div>
              </div>
            </div>
          )}

          {/* Recent Searches Error */}
          {searchTerm.length < 2 && recentError && !isLoadingRecent && (
            <div className="px-3 py-4 text-center">
              <small className="text-danger" style={{ fontSize: '14px' }}>{recentError}</small>
            </div>
          )}

          {/* Recent Searches */}
          {searchTerm.length < 2 && !isLoadingRecent && filteredRecentSearches.length > 0 && (
            <>
              <div className="px-3 pt-2 pb-1 d-flex justify-content-between align-items-center">
                <small className="text-uppercase fw-semibold" style={{ fontSize: '11px', color: '#666', letterSpacing: '0.5px' }}>Recent Searches</small>
                <button
                  type="button"
                  className="btn btn-link btn-sm text-decoration-none p-0"
                  onClick={clearRecentSearches}
                  style={{ fontSize: '12px', color: '#0066cc' }}
                >
                  Clear All
                </button>
              </div>
              <ul className="list-group list-group-flush" style={{ maxHeight: '150px', overflowY: 'auto' }}>
                {filteredRecentSearches.slice(0, 6).map((search, index) => {
                  const isSelected = selectedIndex === index;
                  return (
                  <li
                    key={`${search.code}-${index}`}
                    className="list-group-item border-0 px-3 py-2 cursor-pointer"
                    onClick={() => handleSelectLocation(search)}
                    style={{
                      transition: 'background-color 0.2s',
                      backgroundColor: isSelected ? '#e7f3ff' : 'transparent',
                    }}
                    onMouseEnter={(e) => {
                      if (!isSelected) {
                        e.currentTarget.style.backgroundColor = '#f8f9fa';
                      }
                    }}
                    onMouseLeave={(e) => {
                      if (!isSelected) {
                        e.currentTarget.style.backgroundColor = 'transparent';
                      }
                    }}
                  >
                    <div className="d-flex align-items-center gap-3">
                      <div style={{ width: '20px', height: '20px', flexShrink: 0 }}>
                        {search.type === 'property' ? (
                          <Image src={hotel} height={20} width={20} alt="hotel" style={{ opacity: 0.6 }} />
                        ) : (
                          <Image src={location} height={20} width={20} alt="location" style={{ opacity: 0.6 }} />
                        )}
                      </div>
                      <div className="flex-grow-1">
                        <p className="mb-0 fw-medium" style={{ fontSize: '15px', color: '#212529' }}>{search.cityName}</p>
                        {search.country && (
                          <small className="text-muted" style={{ fontSize: '13px' }}>
                            {search.cityName} · {search.country}
                          </small>
                        )}
                      </div>
                    </div>
                  </li>
                  );
                })}
              </ul>
            </>
          )}

          {/* Empty State with Typing Animation - Better UX */}
          {searchTerm.length < 2 && !isLoadingRecent && filteredRecentSearches.length === 0 && !recentError && (
            <div className="px-3 py-4 text-center">
              <div className="typewrap mb-2">
                <span style={{ color: '#666', fontSize: '14px' }}>Search: </span>
                <span id="type-target" className="fw-semibold" style={{ color: '#212529', fontSize: '14px' }}>{typedText}</span>
                <span className="cursor"></span>
              </div>
              <small style={{ color: '#999', fontSize: '13px' }}>
                Start typing to search for cities or properties
              </small>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
