/**
 * 경비함정 선택 드롭다운
 * 선박 모드에서 추적할 함정을 선택
 * - 검색 기능 (like 검색)
 * - 반경 설정
 */
import { useState, useMemo, useCallback, useRef, useEffect } from 'react';
import useShipStore from '../../stores/shipStore';
import useTrackingModeStore, { isPatrolShip, RADIUS_OPTIONS } from '../../stores/trackingModeStore';
import './PatrolShipSelector.scss';

/**
 * 검색어 정규화 (공백/특수문자 제거, 소문자 변환)
 */
function normalizeText(text) {
  if (!text) return '';
  return text.toLowerCase().replace(/[\s\-_.,:;!@#$%^&*()+=\[\]{}|\\/<>?'"]/g, '');
}

export default function PatrolShipSelector() {
  const features = useShipStore((s) => s.features);
  const showShipSelector = useTrackingModeStore((s) => s.showShipSelector);
  const closeShipSelector = useTrackingModeStore((s) => s.closeShipSelector);
  const selectTrackedShip = useTrackingModeStore((s) => s.selectTrackedShip);
  const setMapMode = useTrackingModeStore((s) => s.setMapMode);
  const setRadius = useTrackingModeStore((s) => s.setRadius);
  const currentRadius = useTrackingModeStore((s) => s.radiusNM);

  const [searchValue, setSearchValue] = useState('');
  const [selectedRadius, setSelectedRadius] = useState(currentRadius);
  const containerRef = useRef(null);
  const searchInputRef = useRef(null);

  // 패널 열릴 때 검색창 포커스
  useEffect(() => {
    if (showShipSelector && searchInputRef.current) {
      searchInputRef.current.focus();
    }
  }, [showShipSelector]);

  // 외부 클릭 시 닫기
  useEffect(() => {
    if (!showShipSelector) return;

    const handleClickOutside = (e) => {
      if (containerRef.current && !containerRef.current.contains(e.target)) {
        // 선박 버튼 클릭은 제외 (TopBar에서 처리)
        if (e.target.closest('.ship')) return;
        closeShipSelector();
      }
    };

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

  // 패널 닫힐 때 검색어 초기화
  useEffect(() => {
    if (!showShipSelector) {
      setSearchValue('');
    }
  }, [showShipSelector]);

  // 경비함정 목록 필터링
  const patrolShips = useMemo(() => {
    const ships = [];
    features.forEach((ship, featureId) => {
      if (isPatrolShip(ship.originalTargetId)) {
        ships.push({
          featureId,
          ship,
          shipName: ship.shipName || ship.originalTargetId || '-',
          originalTargetId: ship.originalTargetId,
        });
      }
    });

    // 선박명 정렬
    ships.sort((a, b) => a.shipName.localeCompare(b.shipName, 'ko'));
    return ships;
  }, [features]);

  // 검색 필터링된 목록
  const filteredShips = useMemo(() => {
    const normalizedSearch = normalizeText(searchValue);
    if (!normalizedSearch) return patrolShips;

    return patrolShips.filter((item) => {
      const normalizedName = normalizeText(item.shipName);
      const normalizedId = normalizeText(item.originalTargetId);
      return normalizedName.includes(normalizedSearch) || normalizedId.includes(normalizedSearch);
    });
  }, [patrolShips, searchValue]);

  // 함정 선택 핸들러
  const handleSelectShip = useCallback((item) => {
    setRadius(selectedRadius);
    selectTrackedShip(item.featureId, item.ship);
    setSearchValue('');
  }, [selectTrackedShip, setRadius, selectedRadius]);

  // 취소 (지도 모드로 복귀)
  const handleCancel = useCallback(() => {
    setMapMode();
    setSearchValue('');
  }, [setMapMode]);

  // 검색어 변경
  const handleSearchChange = useCallback((e) => {
    setSearchValue(e.target.value);
  }, []);

  // 검색어 초기화
  const handleClearSearch = useCallback(() => {
    setSearchValue('');
    searchInputRef.current?.focus();
  }, []);

  // 반경 선택
  const handleRadiusChange = useCallback((radius) => {
    setSelectedRadius(radius);
  }, []);

  if (!showShipSelector) return null;

  return (
    <div className="patrol-ship-selector" ref={containerRef}>
      {/* 헤더 */}
      <div className="selector-header">
        <span className="selector-title">경비함정 선택</span>
        <button type="button" className="close-btn" onClick={handleCancel}>
          ×
        </button>
      </div>

      {/* 검색 영역 */}
      <div className="selector-search">
        <div className="search-input-wrapper">
          <input
            ref={searchInputRef}
            type="text"
            className="search-input"
            placeholder="함정명 또는 ID 검색"
            value={searchValue}
            onChange={handleSearchChange}
          />
          {searchValue && (
            <button type="button" className="search-clear-btn" onClick={handleClearSearch}>
              ×
            </button>
          )}
        </div>
      </div>

      {/* 반경 설정 */}
      <div className="selector-radius">
        <span className="radius-label">반경 설정</span>
        <div className="radius-options">
          {RADIUS_OPTIONS.map((radius) => (
            <button
              key={radius}
              type="button"
              className={`radius-btn ${selectedRadius === radius ? 'active' : ''}`}
              onClick={() => handleRadiusChange(radius)}
            >
              {radius}
            </button>
          ))}
          <span className="radius-unit">NM</span>
        </div>
      </div>

      {/* 함정 목록 */}
      <div className="selector-content">
        {filteredShips.length === 0 ? (
          <div className="no-ships">
            {searchValue ? '검색 결과가 없습니다' : '활성화된 경비함정이 없습니다'}
          </div>
        ) : (
          <ul className="ship-list">
            {filteredShips.map((item) => (
              <li
                key={item.featureId}
                className="ship-item"
                onClick={() => handleSelectShip(item)}
              >
                <span className="ship-name">{item.shipName}</span>
                <span className="ship-id">{item.originalTargetId}</span>
              </li>
            ))}
          </ul>
        )}
      </div>

      {/* 푸터 */}
      <div className="selector-footer">
        <span className="ship-count">
          {searchValue ? `${filteredShips.length} / ${patrolShips.length}척` : `${patrolShips.length}척`}
        </span>
      </div>
    </div>
  );
}
