/**
 * 개별 선박 목록 패널 컴포넌트
 * HTML5 드래그앤드롭 API를 사용하여 상태별(일반/선택/삭제) 선박 목록을 드롭 영역으로 표시
 */
import React, { useCallback, useMemo, useState } from 'react';
import { VesselState } from '../../types/replay.types';
import VesselItem from './VesselItem';
import VirtualVesselList from './VirtualVesselList';
import './VesselListPanel.scss';

// 상태별 설정
const STATE_CONFIG = {
  [VesselState.NORMAL]: {
    title: '기본 선박',
    color: '#28a745',
    emptyMessage: '기본 상태 선박이 없습니다',
  },
  [VesselState.SELECTED]: {
    title: '선택 선박',
    color: '#007bff',
    emptyMessage: '선택된 선박이 없습니다',
  },
  [VesselState.DELETED]: {
    title: '삭제 선박',
    color: '#dc3545',
    emptyMessage: '삭제된 선박이 없습니다',
  },
};

const VesselListPanel = ({
  state,
  vessels,
  title,
  color,
  emptyMessage,
  selectedVesselIds = new Set(),
  onDrop,
  onMouseEnterVessel,
  onMouseLeaveVessel,
  onToggleSelection,
  onShowVesselDetail,
  onContextMenu,
  onSelectAllInPanel,
}) => {
  const [isDragOver, setIsDragOver] = useState(false);
  const [dragData, setDragData] = useState(null);

  const config = STATE_CONFIG[state];
  const panelTitle = title || config.title;
  const panelColor = color || config.color;
  const panelEmptyMessage = emptyMessage || config.emptyMessage;

  // HTML5 드롭 이벤트 핸들러
  const handleDragOver = useCallback((event) => {
    event.preventDefault();
    event.dataTransfer.dropEffect = 'move';
    setIsDragOver(true);
  }, []);

  const handleDragEnter = useCallback((event) => {
    event.preventDefault();
    setIsDragOver(true);
  }, []);

  const handleDragLeave = useCallback((event) => {
    // 실제로 컨테이너를 벗어날 때만 drag over 상태 해제
    const rect = event.currentTarget.getBoundingClientRect();
    const x = event.clientX;
    const y = event.clientY;

    if (x < rect.left || x > rect.right || y < rect.top || y > rect.bottom) {
      setIsDragOver(false);
    }
  }, []);

  const handleDrop = useCallback(
    (event) => {
      event.preventDefault();
      setIsDragOver(false);

      try {
        const data = JSON.parse(event.dataTransfer.getData('text/plain'));
        const { vesselId, sourceState } = data;

        if (vesselId && sourceState && sourceState !== state) {
          onDrop?.(vesselId, sourceState, state);
        }
      } catch (error) {
        // 드롭 데이터 파싱 실패 시 무시 (외부 드래그 소스일 수 있음)
      }
    },
    [state, onDrop],
  );

  const handleVesselDragStart = useCallback((vesselId, sourceState) => {
    setDragData({ vesselId, sourceState });
  }, []);

  const handleVesselDragEnd = useCallback(() => {
    setDragData(null);
  }, []);

  // 패널 내 선택 상태 계산
  const vesselIds = useMemo(() => vessels.map(v => v.vesselId), [vessels]);
  const selectedInPanel = useMemo(
    () => vesselIds.filter(id => selectedVesselIds.has(id)).length,
    [vesselIds, selectedVesselIds],
  );
  const isAllSelected = vesselIds.length > 0 && selectedInPanel === vesselIds.length;
  const isPartiallySelected = selectedInPanel > 0 && selectedInPanel < vesselIds.length;

  // 패널별 전체선택/해제
  const handleSelectAllInPanel = useCallback(
    (event) => {
      event.preventDefault();
      event.stopPropagation();

      if (!onSelectAllInPanel || vesselIds.length === 0) return;

      onSelectAllInPanel(vesselIds, !isAllSelected);
    },
    [vesselIds, isAllSelected, onSelectAllInPanel],
  );

  return (
    <div className="vessel-list-panel" data-state={state}>
      {/* 드롭 영역 */}
      <div
        className={`vessel-list-container ${isDragOver ? 'drag-over' : ''}`}
        onDragOver={handleDragOver}
        onDragEnter={handleDragEnter}
        onDragLeave={handleDragLeave}
        onDrop={handleDrop}
      >
        {/* 선박 목록 - 대용량 데이터는 가상 스크롤 적용 */}
        {vessels.length > 0 ? (
          vessels.length > 100 ? (
            // 100척 초과 시 가상 스크롤링 사용
            <VirtualVesselList
              vessels={vessels}
              selectedVesselIds={selectedVesselIds}
              onDragStart={handleVesselDragStart}
              onDragEnd={handleVesselDragEnd}
              onMouseEnterVessel={onMouseEnterVessel}
              onMouseLeaveVessel={onMouseLeaveVessel}
              onToggleSelection={onToggleSelection}
              onShowVesselDetail={onShowVesselDetail}
              onContextMenu={onContextMenu}
              containerHeight={320} // 컨테이너 높이 고정
              itemHeight={50} // VesselItem 높이 (60px + margin 4px)
            />
          ) : (
            // 100척 이하는 기존 방식 사용
            <div className="vessel-list">
              {vessels.map((vessel, index) => (
                <VesselItem
                  key={vessel.vesselId}
                  vessel={vessel}
                  index={index}
                  isDragDisabled={false}
                  isSelected={selectedVesselIds.has(vessel.vesselId)}
                  onDragStart={handleVesselDragStart}
                  onDragEnd={handleVesselDragEnd}
                  onMouseEnterVessel={onMouseEnterVessel}
                  onMouseLeaveVessel={onMouseLeaveVessel}
                  onToggleSelection={onToggleSelection}
                  onShowVesselDetail={onShowVesselDetail}
                  onContextMenu={onContextMenu}
                />
              ))}
            </div>
          )
        ) : (
          <div className="empty-message">
            <div className="empty-text">{panelEmptyMessage}</div>
          </div>
        )}
      </div>
    </div>
  );
};

export default React.memo(VesselListPanel);
