import React, { useState, useRef, useCallback, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { searchAccommodation, AccommodationSearchItem, AutocompleteRequest } from '../utils/api';
import { useSearchHistory } from './SearchHistory/useSearchHistory';
import SearchHistoryDropdown from './SearchHistory/SearchHistoryDropdown';
import BusinessNameInputModal from './BusinessNameInputModal';

type SearchType = 'url' | 'name' | 'manual';

export type { SearchType };

const isValidUrl = (string: string): boolean => {
  try {
    const url = new URL(string);
    return url.protocol === 'http:' || url.protocol === 'https:';
  } catch {
    return false;
  }
};

interface SearchInputFormProps {
  onAnalyze?: (value: string, type: SearchType) => void;
  onAutocomplete?: (data: AutocompleteRequest) => void;
  onManualInput?: (businessName: string, address: string) => void;
  /** 직접입력 버튼 클릭 시 기본 동작(모달 열기)을 대체합니다. 제공 시 모달을 직접 관리해야 합니다. */
  onManualButtonClick?: () => void;
  error?: string | null;
}

const SearchInputForm: React.FC<SearchInputFormProps> = ({
  onAnalyze,
  onAutocomplete,
  onManualInput,
  onManualButtonClick,
  error: externalError,
}) => {
  const { t } = useTranslation();
  const [inputValue, setInputValue] = useState('');
  const [searchType] = useState<SearchType>('name');
  const [isFocused, setIsFocused] = useState(false);
  const [isManualModalOpen, setIsManualModalOpen] = useState(false);
  const [localError, setLocalError] = useState('');
  const [autocompleteResults, setAutocompleteResults] = useState<AccommodationSearchItem[]>([]);
  const [isAutocompleteLoading, setIsAutocompleteLoading] = useState(false);
  const [showAutocomplete, setShowAutocomplete] = useState(false);
  const [selectedItem, setSelectedItem] = useState<AccommodationSearchItem | null>(null);
  const [highlightedIndex, setHighlightedIndex] = useState<number>(-1);

  const { filteredHistory, showHistory, openHistory, closeHistory, hideOnInput, deleteItem } = useSearchHistory('name');
  const debounceRef = useRef<NodeJS.Timeout | null>(null);
  const autocompleteRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (autocompleteRef.current && !autocompleteRef.current.contains(event.target as Node)) {
        setShowAutocomplete(false);
      }
    };
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  const handleAutocompleteSearch = useCallback(async (query: string) => {
    if (!query.trim()) {
      setAutocompleteResults([]);
      setShowAutocomplete(false);
      return;
    }
    setIsAutocompleteLoading(true);
    try {
      const response = await searchAccommodation(query);
      setAutocompleteResults(response.items || []);
      setShowAutocomplete(response.items && response.items.length > 0);
    } catch {
      setAutocompleteResults([]);
      setShowAutocomplete(false);
    } finally {
      setIsAutocompleteLoading(false);
    }
  }, []);

  const handleSelectAutocomplete = (item: AccommodationSearchItem) => {
    setInputValue(item.title.replace(/<[^>]*>/g, ''));
    setSelectedItem(item);
    setShowAutocomplete(false);
    setAutocompleteResults([]);
    setHighlightedIndex(-1);
  };

  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (showAutocomplete && autocompleteResults.length > 0) {
      switch (e.key) {
        case 'ArrowDown':
          e.preventDefault();
          setHighlightedIndex(prev => prev < autocompleteResults.length - 1 ? prev + 1 : 0);
          return;
        case 'ArrowUp':
          e.preventDefault();
          setHighlightedIndex(prev => prev > 0 ? prev - 1 : autocompleteResults.length - 1);
          return;
        case 'Enter':
          e.preventDefault();
          if (highlightedIndex >= 0 && highlightedIndex < autocompleteResults.length) {
            handleSelectAutocomplete(autocompleteResults[highlightedIndex]);
          }
          return;
        case 'Escape':
          e.preventDefault();
          setShowAutocomplete(false);
          setHighlightedIndex(-1);
          return;
      }
    }
    if (e.key === 'Enter') {
      e.preventDefault();
    }
  };

  const handleStart = () => {
    const trimmed = inputValue.trim();
    if (!trimmed) {
      setLocalError(t('landing.hero.errorInputRequired'));
      return;
    }
    if (isValidUrl(trimmed)) {
      setLocalError('');
      onAnalyze?.(trimmed, 'url');
      return;
    }

    setLocalError('');

    if (selectedItem && onAutocomplete) {
      onAutocomplete({
        address: selectedItem.address,
        roadAddress: selectedItem.roadAddress,
        title: selectedItem.title,
      });
    } else if (onAnalyze) {
      onAnalyze(inputValue, searchType);
    }
  };

  const handleManualButtonClick = () => {
    if (onManualButtonClick) {
      onManualButtonClick();
    } else {
      setIsManualModalOpen(true);
    }
  };

  const error = externalError || localError;

  return (
    <div className="hero-form">
      <div className={`hero-input-wrapper ${isFocused ? 'focused' : ''} ${error ? 'error' : ''} ${inputValue && !isFocused ? 'filled' : ''}`}>
        {/* 유형 라벨 */}
        {/* <div className="hero-dropdown-container">
          <div className="hero-dropdown-trigger">
            <span className="hero-dropdown-main">
              {t('landing.hero.searchTypeLabel')}
            </span>
          </div>
        </div> */}

        {/* 입력 필드 */}
        <div className="hero-input-container" ref={autocompleteRef}>
          <input
            type="text"
            value={inputValue}
            onChange={(e) => {
              const value = e.target.value;
              setInputValue(value);
              setSelectedItem(null);
              setHighlightedIndex(-1);
              hideOnInput(value);
              if (localError) setLocalError('');
              if (debounceRef.current) clearTimeout(debounceRef.current);
              if (isValidUrl(value)) {
                setAutocompleteResults([]);
                setShowAutocomplete(false);
              } else {
                debounceRef.current = setTimeout(() => handleAutocompleteSearch(value), 300);
              }
            }}
            onFocus={() => {
              setIsFocused(true);
              if (autocompleteResults.length > 0) setShowAutocomplete(true);
              openHistory(inputValue);
            }}
            onBlur={() => { setIsFocused(false); setTimeout(() => closeHistory(), 150); }}
            onKeyDown={handleKeyDown}
            placeholder={t('landing.hero.placeholderCombined')}
            className={`hero-input ${inputValue ? 'has-value' : ''}`}
          />

          {/* 최근 검색 히스토리 */}
          {showHistory && !showAutocomplete && (
            <SearchHistoryDropdown
              items={filteredHistory}
              onSelect={(item) => {
                closeHistory();
                setInputValue(item.value);
                if (item.type === 'name') {
                  setSelectedItem({ title: item.value, address: item.address || '', roadAddress: item.roadAddress || '' });
                }
              }}
              onDelete={(e, value) => { e.preventDefault(); e.stopPropagation(); deleteItem(value); }}
              className="hero-autocomplete-dropdown"
              itemClassName="hero-autocomplete-item"
              titleClassName="hero-autocomplete-title"
              addressClassName="hero-autocomplete-address"
            />
          )}

          {/* 자동완성 결과 */}
          {showAutocomplete && (
            <div className="hero-autocomplete-dropdown">
              {isAutocompleteLoading ? (
                <div className="hero-autocomplete-loading">{t('landing.hero.searching')}</div>
              ) : (
                autocompleteResults.map((item, index) => (
                  <button
                    key={index}
                    type="button"
                    className={`hero-autocomplete-item ${highlightedIndex === index ? 'highlighted' : ''}`}
                    onMouseDown={(e) => { e.preventDefault(); handleSelectAutocomplete(item); }}
                    onMouseEnter={() => setHighlightedIndex(index)}
                  >
                    <div className="hero-autocomplete-title" dangerouslySetInnerHTML={{ __html: item.title }} />
                    <div className="hero-autocomplete-address">{item.roadAddress || item.address}</div>
                  </button>
                ))
              )}
            </div>
          )}
        </div>

        {/* 입력 clear 버튼 */}
        {inputValue && (
          <button
            type="button"
            className="hero-input-clear"
            onClick={() => {
              setInputValue('');
              setSelectedItem(null);
              setLocalError('');
              setAutocompleteResults([]);
              setShowAutocomplete(false);
            }}
          >
            <img src="/assets/images/input-clear-icon.svg" alt="Clear" />
          </button>
        )}
      </div>

      <span className="hero-input-hint">{t('landing.hero.guideCombined')}</span>

      {error && <p className="hero-error">{error}</p>}

      <button onClick={handleStart} className="hero-button">
        {t('landing.hero.analyzeButton')}
      </button>

      <div className="hero-divider"><span>또는</span></div>

      <div className="hero-manual-card" onClick={handleManualButtonClick} role="button" tabIndex={0}
        onKeyDown={(e) => e.key === 'Enter' && handleManualButtonClick()}>
        <span className="hero-manual-card-title">{t('landing.hero.searchTypeManual')}</span>
        <p className="hero-manual-button-desc">{t('landing.hero.manualButtonDesc')}</p>
      </div>

      {/* onManualButtonClick 미제공 시 모달을 내부에서 관리 */}
      {!onManualButtonClick && isManualModalOpen && (
        <BusinessNameInputModal
          onClose={() => setIsManualModalOpen(false)}
          onSubmit={(businessName, address) => {
            setIsManualModalOpen(false);
            onManualInput?.(businessName, address);
          }}
        />
      )}
    </div>
  );
};

export default SearchInputForm;
