'use client';

import { useState, useRef, useEffect, useCallback } from 'react';
import { X } from 'lucide-react';
import { useCitiesSearch } from '@/hooks/useCitiesSearch';
import { useRecentSearches } from '@/hooks/useRecentSearches';
import type { City } from '@/types/city';
import LocationSearchDropdown from './LocationSearchDropdown';

export interface LocationData {
  destination: string;
  code: string; // city_id, destination_id, country_id, or property_code
  type?: string;
  country?: string;
  /** When type is 'city': 'city' | 'destination' | 'country' - which id is in code for /srp/prices */
  location_type?: string;
  city_id?: string
}

interface LocationSearchInputProps {
  value: LocationData;
  onChange: (value: LocationData) => void;
  /** When true, show city, destination, and property in dropdown; hide only country (used on SRP form). */
  onlyCityAndProperty?: boolean;
}

export default function LocationSearchInput({
  value,
  onChange,
  onlyCityAndProperty = false,
}: LocationSearchInputProps) {
  const [isOpen, setIsOpen] = useState(false);
  const [typedText, setTypedText] = useState('');
  const containerRef = useRef<HTMLDivElement>(null);

  // Cities search with useCitiesSearch hook
  const {
    searchTerm,
    setSearchTerm,
    cities,
    isLoading: isSearching,
    error: searchError,
    clearResults
  } = useCitiesSearch({ debounceMs: 300, minChars: 2, limit: 10 });

  // Recent searches
  const {
    recentSearches,
    clearRecentSearches,
    isLoading: isLoadingRecent,
    error: recentError,
    refetch
  } = useRecentSearches();

  useEffect(() => {
    refetch();
  }, [isOpen, refetch])

  // Continuous typing animation effect with cycling city names
  useEffect(() => {
    if (isOpen && searchTerm.length < 2) {
      const cities = ['London', 'New York', 'Paris', 'Tokyo', 'Dubai'];
      let cityIndex = 0;
      let charIndex = 0;
      let isDeleting = false;
      let timeoutId: NodeJS.Timeout;
      let isMounted = true;

      const animate = () => {
        if (!isMounted) return;

        const currentCity = cities[cityIndex];

        if (!isDeleting) {
          // Typing forward
          if (charIndex <= currentCity.length) {
            setTypedText(' ' + currentCity.substring(0, charIndex));
            charIndex++;

            if (charIndex > currentCity.length) {
              // Finished typing, wait then start deleting
              timeoutId = setTimeout(() => {
                isDeleting = true;
                animate();
              }, 2000); // Pause at full word
              return;
            }
            timeoutId = setTimeout(animate, 100); // Typing speed
          }
        } else {
          // Deleting backward
          if (charIndex >= 0) {
            setTypedText(' ' + currentCity.substring(0, charIndex));
            charIndex--;

            if (charIndex < 0) {
              // Finished deleting, move to next city
              isDeleting = false;
              charIndex = 0;
              cityIndex = (cityIndex + 1) % cities.length;
              timeoutId = setTimeout(animate, 200); // Brief pause before next city
              return;
            }
            timeoutId = setTimeout(animate, 20); // Deleting speed (faster)
          }
        }
      };

      animate(); // Start animation

      // Cleanup on unmount
      return () => {
        isMounted = false;
        if (timeoutId) clearTimeout(timeoutId);
        setTypedText('');
      };
    } else {
      setTypedText('');
    }
  }, [isOpen, searchTerm, recentSearches.length]);

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        containerRef.current &&
        !containerRef.current.contains(event.target as Node)
      ) {
        setIsOpen(false);
        if (searchTerm) {
          clearResults();
        }
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, [searchTerm, clearResults]);

  const handleSelectLocation = (city: City | { cityName: string; code?: string; iataCode?: string; country?: string; type?: string }) => {
    const cityName = 'name' in city ? city.name : city.cityName;
    const code = 'code' in city ? (city.code ?? '') : ((city as { code?: string; iataCode?: string }).code || (city as { iataCode?: string }).iataCode || '');
    const countryName = ('country' in city ? city.country : '') || '';
    const locationType = 'location_type' in city ? (city as City).location_type : undefined;

    // Validate that both destination and code are present
    if (!cityName || !code) {
      console.warn('Cannot select location: destination or code is missing', city);
      return;
    }

    onChange({
      destination: cityName,
      code: code,
      country: countryName,
      type: city.type || '',
      location_type: locationType,
      city_id: (city as any)?.city_id, // for backward compatibility with old city objects
    });

    setIsOpen(false);
    clearResults();
  };

  const handleClear = () => {
    setSearchTerm('');
    clearResults();
  };

  return (
    <div className="w-100 bg-body-secondary rounded-3 shadow-sm mb-md-0 mb-1 position-relative" ref={containerRef}>
      <div
        className="collapse-fields py-1 px-2"
        data-id="collapseHotelDestination"
      >
        <label className="d-block">City or Property Name</label>
        <input
          type="text"
          placeholder="Miami"
          className="form-control bg-body-secondary rounded-0 p-0 collapse-fields-font fw-bold"
          value={value.destination || ''}
          onFocus={() => setIsOpen(true)}
          readOnly
          required
        />
        <div className="invalid-feedback">
          Please fill the city or airport name.
        </div>
      </div>

      <LocationSearchDropdown
        showMenu={isOpen}
        searchTerm={searchTerm}
        setSearchTerm={setSearchTerm}
        cities={cities}
        isSearching={isSearching}
        searchError={searchError}
        recentSearches={recentSearches}
        isLoadingRecent={isLoadingRecent}
        recentError={recentError}
        clearResults={clearResults}
        clearRecentSearches={clearRecentSearches}
        handleSelectLocation={handleSelectLocation}
        typedText={typedText}
        onStopPropagation={(e) => e.stopPropagation()}
        onlyCityAndProperty={onlyCityAndProperty}
      />

      {value.destination && (
        <button
          type="button"
          className="removeValueButton border-0 bg-body-secondary p-0"
          onClick={handleClear}
        >
          <X className="color-text-first" size={14} aria-hidden />
        </button>
      )}
    </div>
  );
}
