/**
 * Replay 전용 통합 필터 컴포넌트
 * TrackingControl 패턴을 확장하여 리플레이 전용 필터들을 통합 관리
 * dark 프로젝트 스타일 적용
 */
import { useState, useCallback } from 'react';
import useReplayStore from '../stores/replayStore';
import useMergedTrackStore from '../stores/mergedTrackStore';
import usePlaybackTrailStore from '../stores/playbackTrailStore';
import './ReplayControlV2.scss';

// 리플레이 필터 옵션
const CUSTOM_FILTER_OPTIONS = [
  { key: 'showNormal', label: '기본' },
  { key: 'showSelected', label: '선택' },
  { key: 'showDeleted', label: '삭제' },
];

// 선종 필터 옵션
const SHIP_KIND_OPTIONS = [
  { code: '000020', label: '어선', key: 'fishing' },
  { code: '000021', label: '함정', key: 'naval' },
  { code: '000022', label: '여객선', key: 'passenger' },
  { code: '000023', label: '화물선', key: 'cargo' },
  { code: '000024', label: '유조선', key: 'tanker' },
  { code: '000025', label: '관공선', key: 'government' },
  { code: '000027', label: '기타', key: 'other' },
  { code: '000028', label: '부이', key: 'buoy' },
];

const ReplayControlV2 = () => {
  // Replay Store 연결
  const filterModules = useReplayStore(state => state.filterModules);
  const shipKindCodeFilter = useReplayStore(state => state.shipKindCodeFilter);
  const selectedVesselIds = useReplayStore(state => state.selectedVesselIds);
  const deletedVesselIds = useReplayStore(state => state.deletedVesselIds);
  const vesselChunks = useMergedTrackStore(state => state.vesselChunks);
  const [isOpen, setIsOpen] = useState(true);

  // Playback Trail Store 연결 (항적표시 토글)
  const isTrailEnabled = usePlaybackTrailStore(state => state.isEnabled);
  const setTrailEnabled = usePlaybackTrailStore(state => state.setEnabled);

  // 전체 선박 수에서 선택/삭제된 선박을 제외한 기본 선박 수 계산
  const totalVesselCount = vesselChunks.size;
  const normalVesselCount = totalVesselCount - selectedVesselIds.size - deletedVesselIds.size;

  // Actions
  const updateFilterModule = useReplayStore(state => state.updateFilterModule);
  const toggleShipKindCode = useReplayStore(state => state.toggleShipKindCode);

  // 커스텀 필터 토글 핸들러
  const handleCustomFilterToggle = (key) => {
    const newValue = !filterModules.custom[key];
    updateFilterModule('custom', { [key]: newValue });
  };

  // 항적 필터 토글 핸들러
  const handlePathFilterToggle = (key) => {
    const newValue = !filterModules.path[key];
    updateFilterModule('path', { [key]: newValue });
  };

  // 라벨 필터 토글 핸들러
  const handleLabelFilterToggle = (key) => {
    const newValue = !filterModules.label[key];
    updateFilterModule('label', { [key]: newValue });
  };

  // 항적표시 토글 핸들러
  const handleTrailToggle = useCallback(() => {
    setTrailEnabled(!isTrailEnabled);
  }, [setTrailEnabled, isTrailEnabled]);

  const openHandler = () => {
    setIsOpen(!isOpen);
  };

  // 카운트 표시 헬퍼
  const getCountLabel = (key) => {
    if (key === 'showNormal') return ` (${normalVesselCount})`;
    if (key === 'showSelected') return ` (${selectedVesselIds.size})`;
    if (key === 'showDeleted') return ` (${deletedVesselIds.size})`;
    return '';
  };

  return (
    <div className="replay-control-v2">
      {/* 헤더 (접기/펼치기) */}
      <div className="filter-header-toggle" onClick={openHandler}>
        <span className="filter-title">분석 결과 - 필터 설정</span>
        <svg
          width="12"
          height="8"
          viewBox="0 0 12 8"
          fill="none"
          xmlns="http://www.w3.org/2000/svg"
          className={`toggle-icon ${isOpen ? 'is-open' : ''}`}
        >
          <path d="M11 1.5L6 6.5L1 1.5" stroke="#888888" strokeWidth="1.5" />
        </svg>
      </div>

      {isOpen && (
        <>
          {/* 커스텀 필터 (선박 목록) */}
          <div className="sig-src-cd-filter">
            <div className="filter-header">
              <h3>
                <div>선박</div>
                <div>목록</div>
              </h3>
            </div>
            <div className="filter-list">
              {CUSTOM_FILTER_OPTIONS.map(option => (
                <div key={option.key} className="filter-item-wrapper">
                  <strong>{option.label}{getCountLabel(option.key)}</strong>
                  <div className="toggle-area">
                    <input
                      type="checkbox"
                      id={`ship-${option.key}`}
                      checked={filterModules.custom[option.key]}
                      onChange={() => handleCustomFilterToggle(option.key)}
                    />
                    <label htmlFor={`ship-${option.key}`} />
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* 선종 필터 */}
          <div className="sig-src-cd-filter">
            <div className="filter-header">
              <h3>선종</h3>
            </div>
            <div className="filter-list">
              {SHIP_KIND_OPTIONS.map(option => (
                <div key={option.code} className="filter-item-wrapper">
                  <strong>{option.label}</strong>
                  <div className="toggle-area">
                    <input
                      type="checkbox"
                      id={option.code}
                      checked={shipKindCodeFilter.has(option.code)}
                      onChange={() => toggleShipKindCode(option.code)}
                    />
                    <label htmlFor={option.code} />
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* 항적 필터 */}
          <div className="sig-src-cd-filter">
            <div className="filter-header">
              <h3>항적</h3>
            </div>
            <div className="filter-list">
              {CUSTOM_FILTER_OPTIONS.map(option => (
                <div key={option.key} className="filter-item-wrapper">
                  <strong>{option.label}{getCountLabel(option.key)}</strong>
                  <div className="toggle-area">
                    <input
                      type="checkbox"
                      id={`track-${option.key}`}
                      checked={filterModules.path[option.key]}
                      onChange={() => handlePathFilterToggle(option.key)}
                    />
                    <label htmlFor={`track-${option.key}`} />
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* 라벨 필터 */}
          <div className="sig-src-cd-filter">
            <div className="filter-header">
              <h3>라벨</h3>
            </div>
            <div className="filter-list">
              {CUSTOM_FILTER_OPTIONS.map(option => (
                <div key={option.key} className="filter-item-wrapper">
                  <strong>{option.label}{getCountLabel(option.key)}</strong>
                  <div className="toggle-area">
                    <input
                      type="checkbox"
                      id={`label-${option.key}`}
                      checked={filterModules.label[option.key]}
                      onChange={() => handleLabelFilterToggle(option.key)}
                    />
                    <label htmlFor={`label-${option.key}`} />
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* 항적표시 토글 (애니메이션 재생 시 이동 궤적) */}
          <div className="sig-src-cd-filter trail-filter">
            <div className="filter-header">
              <h3>항적</h3>
            </div>
            <div className="filter-list">
              <div className="filter-item-wrapper">
                <strong>궤적 표시</strong>
                <div className="toggle-area trail-toggle">
                  <input
                    type="checkbox"
                    id="trail-enabled"
                    checked={isTrailEnabled}
                    onChange={handleTrailToggle}
                  />
                  <label htmlFor="trail-enabled" />
                </div>
              </div>
            </div>
          </div>
        </>
      )}
    </div>
  );
};

export default ReplayControlV2;
