/**
 * 선박 검색/필터 컴포넌트
 * 선박명, 선종, 국적별 검색 및 필터링 기능
 * dark 프로젝트 스타일 적용
 */
import React, { useCallback, useMemo, useState, useEffect } from 'react';
import { VesselState } from '../../types/replay.types';
import { getSortedCountryOptions } from './utils/countryCodeUtils';
import './VesselSearchFilter.scss';

// 선종 코드별 표시명
const SHIP_KIND_NAMES = {
  '000020': '어선',
  '000021': '함정',
  '000022': '여객선',
  '000023': '화물선',
  '000024': '유조선',
  '000025': '관공선',
  '000027': '기타',
  '000028': '부이',
};

export const VesselSearchFilter = ({
  vessels,
  onFilteredVesselsChange,
  onSelectedVesselsChange,
  selectedVesselIds = new Set(),
  onBulkStateChange,
}) => {
  const [searchText, setSearchText] = useState('');
  const [selectedShipKind, setSelectedShipKind] = useState('');
  const [selectedCountryGroup, setSelectedCountryGroup] = useState(null);
  const [selectedState, setSelectedState] = useState('');

  // 고유 선종 목록 추출
  const availableShipKinds = useMemo(() => {
    const kinds = new Set(vessels.map(v => v.shipKindCode));
    return Array.from(kinds).map(code => ({
      code,
      name: SHIP_KIND_NAMES[code] || '기타',
    }));
  }, [vessels]);

  // 고유 국가 코드 목록 추출 및 한글명 매핑
  const availableCountryOptions = useMemo(() => {
    const codes = vessels.map(v => v.nationalCode).filter(Boolean);
    const uniqueCodes = Array.from(new Set(codes));
    return getSortedCountryOptions(uniqueCodes);
  }, [vessels]);

  /**
   * 다중 필터링 로직
   * 4가지 필터를 순차적으로 적용 (AND 조건)
   */
  const filteredVessels = useMemo(() => {
    let filtered = vessels;

    // 텍스트 검색 (선박명, targetId)
    if (searchText.trim()) {
      const search = searchText.toLowerCase().trim();
      filtered = filtered.filter(vessel => {
        const shipName = (vessel.shipName || '').toLowerCase();
        const targetId = (vessel.targetId || '').toLowerCase();
        return shipName.includes(search) || targetId.includes(search);
      });
    }

    // 선종 필터
    if (selectedShipKind) {
      filtered = filtered.filter(vessel => vessel.shipKindCode === selectedShipKind);
    }

    // 국적 필터
    if (selectedCountryGroup) {
      filtered = filtered.filter(vessel => selectedCountryGroup.codes.includes(vessel.nationalCode || ''));
    }

    // 상태 필터
    if (selectedState) {
      filtered = filtered.filter(vessel => vessel.state === selectedState);
    }

    return filtered;
  }, [vessels, searchText, selectedShipKind, selectedCountryGroup, selectedState]);

  // 필터링 결과 전달
  useEffect(() => {
    onFilteredVesselsChange(filteredVessels);
  }, [filteredVessels, onFilteredVesselsChange]);

  /**
   * 전체 선택/해제 토글 핸들러
   */
  const handleSelectAll = useCallback(() => {
    const newSelectedIds = new Set(selectedVesselIds);

    if (filteredVessels.every(vessel => selectedVesselIds.has(vessel.vesselId))) {
      filteredVessels.forEach(vessel => {
        newSelectedIds.delete(vessel.vesselId);
      });
    } else {
      filteredVessels.forEach(vessel => {
        newSelectedIds.add(vessel.vesselId);
      });
    }

    onSelectedVesselsChange?.(newSelectedIds);
  }, [filteredVessels, selectedVesselIds, onSelectedVesselsChange]);

  // 필터 초기화
  const handleClearFilters = useCallback(() => {
    setSearchText('');
    setSelectedShipKind('');
    setSelectedCountryGroup(null);
    setSelectedState('');
  }, []);

  // 선택된 선박들의 상태 일괄 변경
  const handleBulkStateChange = useCallback(
    (targetState) => {
      const selectedIds = Array.from(selectedVesselIds);
      if (selectedIds.length > 0 && onBulkStateChange) {
        onBulkStateChange(selectedIds, targetState);
        onSelectedVesselsChange?.(new Set());
      }
    },
    [selectedVesselIds, onBulkStateChange, onSelectedVesselsChange],
  );

  const isAllSelected =
    filteredVessels.length > 0 && filteredVessels.every(vessel => selectedVesselIds.has(vessel.vesselId));
  const isPartiallySelected = filteredVessels.some(vessel => selectedVesselIds.has(vessel.vesselId)) && !isAllSelected;

  return (
    <div className="vessel-search-filter-wrapper">
      <div className="vessel-search-filter">
        {/* 필터 옵션 */}
        <div className="filter-row">
          <div className="filter-group">
            <select
              value={selectedShipKind}
              onChange={e => setSelectedShipKind(e.target.value)}
              className="filter-select"
            >
              <option value="">선종 전체</option>
              {availableShipKinds.map(kind => (
                <option key={kind.code} value={kind.code}>
                  {kind.name}
                </option>
              ))}
            </select>
          </div>

          <div className="filter-group">
            <select
              value={selectedCountryGroup?.countryName || ''}
              onChange={e => {
                const selectedCountryName = e.target.value;
                const countryGroup = availableCountryOptions.find(c => c.countryName === selectedCountryName);
                setSelectedCountryGroup(countryGroup || null);
              }}
              className="filter-select"
            >
              <option value="">국적 전체</option>
              {availableCountryOptions.map(country => (
                <option
                  key={country.countryName}
                  value={country.countryName}
                  title={country.displayName}
                >
                  {country.truncatedName}
                </option>
              ))}
            </select>
          </div>

          <div className="filter-group search-group">
            <input
              type="text"
              placeholder="선박명 검색"
              value={searchText}
              onChange={e => setSearchText(e.target.value)}
              className="search-input"
            />
          </div>
        </div>
      </div>

      {/* 필터 결과 요약 */}
      {selectedVesselIds.size > 0 && (
        <div className="filter-summary">
          <div className="selected-actions">
            <span className="selected-count">{selectedVesselIds.size}척 선택됨</span>
            <div className="bulk-actions">
              <span className="action-label">일괄 이동:</span>
              <button
                className="bulk-action-btn normal"
                onClick={() => handleBulkStateChange(VesselState.NORMAL)}
                title="선택된 선박들을 일반 상태로 변경"
              >
                초기화
              </button>
              <button
                className="bulk-action-btn selected"
                onClick={() => handleBulkStateChange(VesselState.SELECTED)}
                title="선택된 선박들을 선택 상태로 변경"
              >
                선택
              </button>
              <button
                className="bulk-action-btn deleted"
                onClick={() => handleBulkStateChange(VesselState.DELETED)}
                title="선택된 선박들을 삭제 상태로 변경"
              >
                삭제
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default React.memo(VesselSearchFilter);
