/**
 * 개별 선박 아이템 컴포넌트
 * HTML5 드래그앤드롭 API를 사용하여 드래그 가능하며 선종/국적 아이콘, 선박명을 표시
 * dark 프로젝트 아이콘 경로 사용
 */
import React, { useCallback, useState } from 'react';
import { getCountryNameFromCode } from './utils/countryCodeUtils';
import './VesselItem.scss';

// 선종 아이콘 import (dark 프로젝트 assets)
import fishingIcon from '../../../assets/img/shipDetail/detailKindIcon/fishing.svg';
import kcgvIcon from '../../../assets/img/shipDetail/detailKindIcon/kcgv.svg';
import passengerIcon from '../../../assets/img/shipDetail/detailKindIcon/passenger.svg';
import cargoIcon from '../../../assets/img/shipDetail/detailKindIcon/cargo.svg';
import tankerIcon from '../../../assets/img/shipDetail/detailKindIcon/tanker.svg';
import govIcon from '../../../assets/img/shipDetail/detailKindIcon/gov.svg';
import etcIcon from '../../../assets/img/shipDetail/detailKindIcon/etc.svg';

// 선종 코드 상수
import {
  SIGNAL_KIND_CODE_FISHING,
  SIGNAL_KIND_CODE_KCGV,
  SIGNAL_KIND_CODE_PASSENGER,
  SIGNAL_KIND_CODE_CARGO,
  SIGNAL_KIND_CODE_TANKER,
  SIGNAL_KIND_CODE_GOV,
  SIGNAL_KIND_CODE_NORMAL,
  SIGNAL_KIND_CODE_BUOY,
} from '../../../types/constants';

// 선종코드 → 아이콘 매핑
const SHIP_KIND_ICONS = {
  [SIGNAL_KIND_CODE_FISHING]: fishingIcon,    // 000020: 어선
  [SIGNAL_KIND_CODE_KCGV]: kcgvIcon,          // 000021: 함정
  [SIGNAL_KIND_CODE_PASSENGER]: passengerIcon, // 000022: 여객선
  [SIGNAL_KIND_CODE_CARGO]: cargoIcon,        // 000023: 화물선
  [SIGNAL_KIND_CODE_TANKER]: tankerIcon,      // 000024: 유조선
  [SIGNAL_KIND_CODE_GOV]: govIcon,            // 000025: 관공선
  [SIGNAL_KIND_CODE_NORMAL]: etcIcon,         // 000027: 기타
  [SIGNAL_KIND_CODE_BUOY]: etcIcon,           // 000028: 부이
};

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

// 신호원 코드별 표시명
const SIGNAL_SOURCE_NAMES = {
  '000001': 'AIS',
  '000002': 'E-NAV',
  '000003': 'V-PASS',
  '000004': 'VTS-AIS',
};

/**
 * 선종 아이콘 반환
 */
const getShipKindIcon = (shipKindCode) => {
  return SHIP_KIND_ICONS[shipKindCode] || etcIcon;
};

/**
 * 국기 이미지 URL 생성 (서버 API)
 * 개발 환경에서는 Vite 프록시를 통해 API 서버로 전달됨
 * @param {string} nationalCode - MID 숫자코드 (예: '440', '412')
 * @returns {string} 국기 이미지 URL
 */
const getNationalFlagUrl = (nationalCode) => {
  // 국적 코드가 없으면 기본값 '000' 사용
  const code = nationalCode || '000';
  // 상대 경로 사용 (Vite 프록시가 /ship/image를 API 서버로 전달)
  return `/ship/image/small/${code}.svg`;
};

const VesselItem = ({
  vessel,
  index,
  isDragDisabled = false,
  isSelected = false,
  onDragStart,
  onDragEnd,
  onMouseEnterVessel,
  onMouseLeaveVessel,
  onToggleSelection,
  onShowVesselDetail,
  onContextMenu,
}) => {
  const [showTooltip, setShowTooltip] = useState(false);
  const [tooltipPosition, setTooltipPosition] = useState({ x: 0, y: 0 });
  const [isDragging, setIsDragging] = useState(false);

  // 아이콘 및 정보
  const shipKindIcon = getShipKindIcon(vessel.shipKindCode);
  const countryFlagUrl = getNationalFlagUrl(vessel.nationalCode || '000');
  const shipKindName = SHIP_KIND_NAMES[vessel.shipKindCode] || '기타';
  const signalSourceName = SIGNAL_SOURCE_NAMES[vessel.sigSrcCd || '000001'] || vessel.sigSrcCd || '기타';
  const countryName = getCountryNameFromCode(vessel.nationalCode || '000');

  // 마우스 호버 이벤트 핸들러
  const handleMouseEnter = useCallback(
    (event) => {
      if (isDragDisabled || isDragging) return;

      const rect = event.currentTarget.getBoundingClientRect();
      setTooltipPosition({
        x: rect.left + rect.width / 2,
        y: rect.top,
      });
      setShowTooltip(true);

      // 지도 상의 항적 하이라이트
      onMouseEnterVessel?.(vessel.vesselId);
    },
    [isDragDisabled, isDragging, onMouseEnterVessel, vessel.vesselId],
  );

  const handleMouseLeave = useCallback(() => {
    setShowTooltip(false);

    // 지도 상의 항적 하이라이트 제거
    onMouseLeaveVessel?.(vessel.vesselId);
  }, [onMouseLeaveVessel, vessel.vesselId]);

  // HTML5 드래그앤드롭 이벤트 핸들러
  const handleDragStart = useCallback(
    (event) => {
      if (isDragDisabled) {
        event.preventDefault();
        return;
      }

      setIsDragging(true);
      setShowTooltip(false);

      // 드래그 데이터 설정
      event.dataTransfer.setData(
        'text/plain',
        JSON.stringify({
          vesselId: vessel.vesselId,
          sourceState: vessel.state,
        }),
      );

      event.dataTransfer.effectAllowed = 'move';

      // 커스텀 드래그 이미지 설정 (선택적)
      const dragImage = event.currentTarget.cloneNode(true);
      dragImage.style.transform = 'rotate(5deg)';
      dragImage.style.opacity = '0.8';
      event.dataTransfer.setDragImage(dragImage, 50, 25);

      onDragStart?.(vessel.vesselId, vessel.state);
    },
    [isDragDisabled, vessel.vesselId, vessel.state, onDragStart],
  );

  const handleDragEnd = useCallback(
    (event) => {
      setIsDragging(false);
      onDragEnd?.();
    },
    [onDragEnd],
  );

  // 체크박스 토글 핸들러
  const handleToggleSelection = useCallback(
    (event) => {
      event.stopPropagation();
      onToggleSelection?.(vessel.vesselId, !isSelected);
    },
    [vessel.vesselId, isSelected, onToggleSelection],
  );

  // 우클릭 컨텍스트 메뉴 핸들러
  const handleRightClick = useCallback(
    (event) => {
      event.preventDefault();
      event.stopPropagation();
      onContextMenu?.(vessel.vesselId, event);
    },
    [onContextMenu, vessel.vesselId],
  );

  return (
    <>
      <div
        className={`vessel-item ${isDragging ? 'dragging' : ''} ${isDragDisabled ? 'disabled' : ''} ${
          isSelected ? 'selected' : ''
        }`}
        title={`${vessel.shipName} (${shipKindName})`}
        draggable={!isDragDisabled}
        onDragStart={handleDragStart}
        onDragEnd={handleDragEnd}
        onMouseEnter={handleMouseEnter}
        onMouseLeave={handleMouseLeave}
        onContextMenu={handleRightClick}
      >
        <div className="vessel-item-content">
          {/* 선택 체크박스 */}
          {onToggleSelection && (
            <div className="selection-checkbox" onClick={handleToggleSelection}>
              <input
                type="checkbox"
                checked={isSelected}
                onChange={() => {}} // onClick에서 처리
                tabIndex={-1}
              />
              <span className="checkmark"></span>
            </div>
          )}

          <div className="vessel-index">{index + 1}</div>

          {/* 선박 정보 */}
          <div className="vessel-info">
            <div className="vessel-name">
              <span className="name-text">{vessel.shipName || '-'}</span>
              <img
                src={shipKindIcon}
                alt={shipKindName}
                className="ship-kind-icon"
                onError={(e) => { e.target.style.display = 'none'; }}
              />
              <img
                src={countryFlagUrl}
                alt={countryName}
                className="country-flag"
                onError={(e) => { e.target.style.display = 'none'; }}
              />
              <span className="signal-source">({signalSourceName})</span>
            </div>
          </div>

          {/* 드래그 핸들 아이콘 */}
          {!isDragDisabled && (
            <div className="drag-handle">
              <svg width="12" height="12" viewBox="0 0 12 12" fill="currentColor">
                <circle cx="3" cy="2" r="1.5" />
                <circle cx="9" cy="2" r="1.5" />
                <circle cx="3" cy="6" r="1.5" />
                <circle cx="9" cy="6" r="1.5" />
                <circle cx="3" cy="10" r="1.5" />
                <circle cx="9" cy="10" r="1.5" />
              </svg>
            </div>
          )}
        </div>

        {/* 드래그 중 오버레이 */}
        {isDragging && <div className="drag-overlay" />}
      </div>
    </>
  );
};

export default React.memo(VesselItem);
