/**
 * 선박 목록 관리자 컴포넌트
 * HTML5 드래그앤드롭을 통한 선박 상태 전환 인터페이스
 * dark 프로젝트 스타일 적용
 */
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { VesselState } from '../../types/replay.types';
import { useVesselClassification } from './hooks/useVesselClassification';
import { useVesselActions } from './hooks/useVesselActions';
import VesselListPanel from './VesselListPanel';
import VesselSearchFilter from './VesselSearchFilter';
import VesselContextMenu from './VesselContextMenu';
import useReplayStore from '../../stores/replayStore';
import './VesselListManager.scss';

export const VesselListManager = ({ className = '' }) => {
  const { vesselsByState, totalCount, hasVessels } = useVesselClassification();
  const { handleDragDrop } = useVesselActions();

  // 필터링 및 선택 상태
  const [filteredVessels, setFilteredVessels] = useState([]);
  const [selectedVesselIds, setSelectedVesselIds] = useState(new Set());

  // 패널 상태 (기본 열림)
  const [isOpen, setIsOpen] = useState(true);
  const [tap, setTap] = useState(1);

  // 컨텍스트 메뉴 상태
  const [contextMenu, setContextMenu] = useState(null);

  // 전체 선박 목록 (필터링 전)
  const allVessels = useMemo(() => {
    return [...vesselsByState.normal, ...vesselsByState.selected, ...vesselsByState.deleted];
  }, [vesselsByState]);

  // 상태별로 필터링된 선박 분류
  const filteredVesselsByState = useMemo(() => {
    return {
      normal: filteredVessels.filter(v => v.state === VesselState.NORMAL),
      selected: filteredVessels.filter(v => v.state === VesselState.SELECTED),
      deleted: filteredVessels.filter(v => v.state === VesselState.DELETED),
    };
  }, [filteredVessels]);

  /**
   * 지도 상의 항적 하이라이트 핸들러
   */
  const handleMouseEnterVessel = useCallback((vesselId) => {
    // replayStore의 하이라이트 시스템 사용
    useReplayStore.getState().setHighlightedVesselId(vesselId);
  }, []);

  const handleMouseLeaveVessel = useCallback((vesselId) => {
    // 하이라이트 제거
    useReplayStore.getState().setHighlightedVesselId(null);
  }, []);

  /**
   * HTML5 드래그앤드롭 완료 핸들러
   */
  const onDrop = useCallback(
    (vesselId, sourceState, targetState) => {
      // 드래그앤드롭 결과를 상태 전환으로 변환
      handleDragDrop({
        vesselId,
        sourceState: sourceState,
        targetState: targetState,
      });
    },
    [handleDragDrop],
  );

  /**
   * 선박 선택/해제 핸들러
   */
  const handleToggleSelection = useCallback((vesselId, isSelected) => {
    setSelectedVesselIds(prev => {
      const newSet = new Set(prev);
      if (isSelected) {
        newSet.add(vesselId);
      } else {
        newSet.delete(vesselId);
      }
      return newSet;
    });
  }, []);

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

  /**
   * 선박 상세보기 핸들러 (컨텍스트 메뉴에서 호출)
   */
  const handleShowVesselDetail = useCallback(
    (vesselId) => {
      // 선박 정보 찾기
      const vessel = allVessels.find(v => v.vesselId === vesselId);
      if (vessel) {
        console.log('[VesselListManager] 상세보기:', vessel);
        // TODO: 상세 모달 구현
      }
    },
    [allVessels],
  );

  /**
   * 컨텍스트 메뉴 열기
   */
  const handleContextMenu = useCallback(
    (vesselId, event) => {
      const vessel = allVessels.find(v => v.vesselId === vesselId);
      if (vessel) {
        setContextMenu({
          vessel,
          position: { x: event.clientX, y: event.clientY },
        });
      }
    },
    [allVessels],
  );

  /**
   * 컨텍스트 메뉴 닫기
   */
  const handleCloseContextMenu = useCallback(() => {
    setContextMenu(null);
  }, []);

  /**
   * 선박 일괄 상태 변경 핸들러
   */
  const handleBulkStateChange = useCallback(
    (selectedVesselIds, targetState) => {
      // 각 선박에 대해 상태 변경 실행
      selectedVesselIds.forEach(vesselId => {
        const vessel = allVessels.find(v => v.vesselId === vesselId);
        if (vessel && vessel.state !== targetState) {
          handleDragDrop({
            vesselId,
            sourceState: vessel.state,
            targetState,
          });
        }
      });
    },
    [allVessels, handleDragDrop],
  );

  /**
   * 패널별 전체선택/해제 핸들러
   */
  const handleSelectAllInPanel = useCallback((vesselIds, isSelected) => {
    setSelectedVesselIds(prev => {
      const newSet = new Set(prev);

      if (isSelected) {
        // 선택: 해당 패널의 모든 선박 추가
        vesselIds.forEach(id => newSet.add(id));
      } else {
        // 해제: 해당 패널의 모든 선박 제거
        vesselIds.forEach(id => newSet.delete(id));
      }

      return newSet;
    });
  }, []);

  // 탭 스타일 헬퍼
  const getTabStyle = (tabIndex) => ({
    flex: 1,
    height: '100%',
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
    fontSize: '1.2rem',
    fontWeight: '600',
    color: tap === tabIndex ? '#fff' : 'rgba(255, 255, 255, 0.6)',
    backgroundColor: tap === tabIndex ? 'rgba(74, 158, 255, 0.3)' : 'transparent',
    borderBottom: tap === tabIndex ? '2px solid #4a9eff' : '2px solid transparent',
    cursor: 'pointer',
    transition: 'all 0.2s ease',
  });

  return (
    <div className={`vessel-list-manager ${className}`}>
      {/* 헤더 */}
      <div className="manager-header-toggle" onClick={openHandler}>
        <span className="header-title">
          분석 결과 - 선박 목록 {`(총 ${totalCount.toLocaleString()}척)`}
        </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="manager-content">
          {/* 검색/필터 영역 */}
          <VesselSearchFilter
            vessels={allVessels}
            onFilteredVesselsChange={setFilteredVessels}
            onSelectedVesselsChange={setSelectedVesselIds}
            selectedVesselIds={selectedVesselIds}
            onBulkStateChange={handleBulkStateChange}
          />

          {/* 탭 헤더 */}
          <div className="tab-header">
            <div
              className={`tab-item ${tap === 1 ? 'active' : ''}`}
              onClick={() => setTap(1)}
            >
              기본 ({filteredVesselsByState.normal.length})
            </div>
            <div
              className={`tab-item ${tap === 2 ? 'active' : ''}`}
              onClick={() => setTap(2)}
            >
              선택 ({filteredVesselsByState.selected.length})
            </div>
            <div
              className={`tab-item ${tap === 3 ? 'active' : ''}`}
              onClick={() => setTap(3)}
            >
              삭제 ({filteredVesselsByState.deleted.length})
            </div>
          </div>

          <div className="vessel-lists-container">
            {tap === 1 && (
              <VesselListPanel
                state={VesselState.NORMAL}
                vessels={filteredVesselsByState.normal}
                title="기본 선박"
                color="#4ade80"
                emptyMessage="기본 상태 선박이 없습니다"
                selectedVesselIds={selectedVesselIds}
                onDrop={onDrop}
                onMouseEnterVessel={handleMouseEnterVessel}
                onMouseLeaveVessel={handleMouseLeaveVessel}
                onToggleSelection={handleToggleSelection}
                onShowVesselDetail={handleShowVesselDetail}
                onContextMenu={handleContextMenu}
                onSelectAllInPanel={handleSelectAllInPanel}
              />
            )}

            {tap === 2 && (
              <VesselListPanel
                state={VesselState.SELECTED}
                vessels={filteredVesselsByState.selected}
                title="선택 선박"
                color="#4a9eff"
                emptyMessage="선택된 선박이 없습니다"
                selectedVesselIds={selectedVesselIds}
                onDrop={onDrop}
                onMouseEnterVessel={handleMouseEnterVessel}
                onMouseLeaveVessel={handleMouseLeaveVessel}
                onToggleSelection={handleToggleSelection}
                onShowVesselDetail={handleShowVesselDetail}
                onContextMenu={handleContextMenu}
                onSelectAllInPanel={handleSelectAllInPanel}
              />
            )}

            {tap === 3 && (
              <VesselListPanel
                state={VesselState.DELETED}
                vessels={filteredVesselsByState.deleted}
                title="삭제 선박"
                color="#f87171"
                emptyMessage="삭제된 선박이 없습니다"
                selectedVesselIds={selectedVesselIds}
                onDrop={onDrop}
                onMouseEnterVessel={handleMouseEnterVessel}
                onMouseLeaveVessel={handleMouseLeaveVessel}
                onToggleSelection={handleToggleSelection}
                onShowVesselDetail={handleShowVesselDetail}
                onContextMenu={handleContextMenu}
                onSelectAllInPanel={handleSelectAllInPanel}
              />
            )}
          </div>
        </div>
      )}

      {/* 컨텍스트 메뉴 */}
      {contextMenu && (
        <VesselContextMenu
          vessel={contextMenu.vessel}
          position={contextMenu.position}
          onClose={handleCloseContextMenu}
          onShowDetail={handleShowVesselDetail}
        />
      )}
    </div>
  );
};

export default React.memo(VesselListManager);
