/**
 * 항적 조회 컨트롤 뷰어
 * 참조: mda-react-front/src/tracking/components/TrackQueryViewer.tsx
 *
 * 레이아웃:
 *   Header: [선명 | TargetId | 선종] [닫기]
 *   Progress: [시작시간 | 현재시간 | 종료시간] + 프로그레스 바
 *   Options: [포인트] [선박아이콘] [선명표시]
 *   Time Form: [조회기간] [시작] ~ [종료] [조회]
 *   Equipment Filter: [장비별항적] [전체][기본] [A][V][E][T][D][R]  (통합선박만)
 *
 * 모달 모드에서는 재생/배속 컨트롤 없음 (Phase 2 확장점)
 */
import { useRef, useState, useCallback, useEffect } from 'react';
import useTrackStore, { getShipKindTrackColor } from '../../stores/trackStore';
import { SHIP_KIND_LABELS, SIGNAL_FLAG_CONFIGS, SIGNAL_SOURCE_LABELS, TRACK_QUERY_MAX_DAYS, TRACK_QUERY_DEFAULT_DAYS } from '../../types/constants';
import { showToast } from '../common/Toast';
import './TrackQueryModal.scss';

/** 기본 조회 기간 (일) */
const DEFAULT_QUERY_DAYS = TRACK_QUERY_DEFAULT_DAYS;

/** 최대 조회 기간 (일) */
const MAX_QUERY_DAYS = TRACK_QUERY_MAX_DAYS;

/** 일 단위를 밀리초로 변환 */
const DAYS_TO_MS = 24 * 60 * 60 * 1000;

/** datetime-local 입력용 포맷 */
function toDateTimeLocal(date) {
  const pad = (n) => String(n).padStart(2, '0');
  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}`;
}

/** MM-DD HH:mm 형식 */
function formatShortDateTime(ms) {
  if (!ms) return '--/-- --:--';
  const d = new Date(ms);
  const pad = (n) => String(n).padStart(2, '0');
  return `${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
}

/** YYYY-MM-DD HH:mm:ss 형식 */
function formatDateTime(ms) {
  if (!ms) return '-';
  const d = new Date(ms);
  const pad = (n) => String(n).padStart(2, '0');
  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
}

/**
 * 항적 조회 뷰어 패널
 */
export default function TrackQueryModal({ modal }) {
  const closeTrackModal = useTrackStore((s) => s.closeTrackModal);

  // 스토어 상태 구독
  const tracks = useTrackStore((s) => s.tracks);
  const isLoading = useTrackStore((s) => s.isLoading);
  const error = useTrackStore((s) => s.error);
  const currentTime = useTrackStore((s) => s.currentTime);
  const dataStartTime = useTrackStore((s) => s.dataStartTime);
  const dataEndTime = useTrackStore((s) => s.dataEndTime);
  const showPoints = useTrackStore((s) => s.showPoints);
  const showVirtualShip = useTrackStore((s) => s.showVirtualShip);
  const showLabels = useTrackStore((s) => s.showLabels);

  // 시간 입력
  const [startInput, setStartInput] = useState(() => {
    const now = new Date();
    return toDateTimeLocal(new Date(now.getTime() - DEFAULT_QUERY_DAYS * DAYS_TO_MS));
  });
  const [endInput, setEndInput] = useState(() => toDateTimeLocal(new Date()));

  // 시작일 변경 핸들러
  const handleStartChange = useCallback((e) => {
    setStartInput(e.target.value);
  }, []);

  // 종료일 변경 핸들러
  const handleEndChange = useCallback((e) => {
    setEndInput(e.target.value);
  }, []);

  // 조회 기간 검증 및 자동 조정 (blur 시 실행)
  const validateAndAdjustDates = useCallback((changedField) => {
    const startDate = new Date(startInput);
    const endDate = new Date(endInput);

    // 유효하지 않은 날짜면 무시
    if (isNaN(startDate.getTime()) || isNaN(endDate.getTime())) return;

    const diffDays = (endDate - startDate) / DAYS_TO_MS;

    if (changedField === 'start') {
      // 시작일이 종료일보다 뒤인 경우 → 종료일을 시작일 + 기본조회기간으로 조정
      if (diffDays < 0) {
        const adjustedEnd = new Date(startDate.getTime() + DEFAULT_QUERY_DAYS * DAYS_TO_MS);
        setEndInput(toDateTimeLocal(adjustedEnd));
        showToast(`종료일이 시작일보다 앞서 기본 조회기간 ${DEFAULT_QUERY_DAYS}일로 자동 설정됩니다.`);
      }
      // 최대 조회기간 초과 시 종료일 자동 조정
      else if (diffDays > MAX_QUERY_DAYS) {
        const adjustedEnd = new Date(startDate.getTime() + MAX_QUERY_DAYS * DAYS_TO_MS);
        setEndInput(toDateTimeLocal(adjustedEnd));
        showToast(`최대 조회기간 ${MAX_QUERY_DAYS}일로 자동 설정됩니다.`);
      }
    } else {
      // 종료일이 시작일보다 앞인 경우 → 시작일을 종료일 - 기본조회기간으로 조정
      if (diffDays < 0) {
        const adjustedStart = new Date(endDate.getTime() - DEFAULT_QUERY_DAYS * DAYS_TO_MS);
        setStartInput(toDateTimeLocal(adjustedStart));
        showToast(`시작일이 종료일보다 뒤서 기본 조회기간 ${DEFAULT_QUERY_DAYS}일로 자동 설정됩니다.`);
      }
      // 최대 조회기간 초과 시 시작일 자동 조정
      else if (diffDays > MAX_QUERY_DAYS) {
        const adjustedStart = new Date(endDate.getTime() - MAX_QUERY_DAYS * DAYS_TO_MS);
        setStartInput(toDateTimeLocal(adjustedStart));
        showToast(`최대 조회기간 ${MAX_QUERY_DAYS}일로 자동 설정됩니다.`);
      }
    }
  }, [startInput, endInput]);

  // blur 핸들러
  const handleStartBlur = useCallback(() => {
    validateAndAdjustDates('start');
  }, [validateAndAdjustDates]);

  const handleEndBlur = useCallback(() => {
    validateAndAdjustDates('end');
  }, [validateAndAdjustDates]);

  // 드래그 상태
  const [position, setPosition] = useState({ x: 0, y: 0 });
  const dragging = useRef(false);
  const dragStart = useRef({ x: 0, y: 0 });

  // 선박 정보
  const { ships, isIntegrated } = modal;
  const ship = ships[0];
  const shipName = ship?.shipName || '';
  const targetId = ship?.originalTargetId || ship?.targetId || '';
  const kindLabel = SHIP_KIND_LABELS[ship?.signalKindCode] || '기타';
  const sourceLabel = SIGNAL_SOURCE_LABELS[ship?.signalSourceCode] || '';

  const hasTracks = tracks.length > 0;

  // 진행률 계산
  const progress = dataEndTime > dataStartTime
    ? ((currentTime - dataStartTime) / (dataEndTime - dataStartTime)) * 100
    : 0;

  // 드래그 핸들러
  const handleDragStart = useCallback((e) => {
    dragging.current = true;
    dragStart.current = {
      x: e.clientX - position.x,
      y: e.clientY - position.y,
    };
    e.preventDefault();
  }, [position]);

  useEffect(() => {
    const handleMouseMove = (e) => {
      if (!dragging.current) return;
      setPosition({
        x: e.clientX - dragStart.current.x,
        y: e.clientY - dragStart.current.y,
      });
    };
    const handleMouseUp = () => { dragging.current = false; };

    window.addEventListener('mousemove', handleMouseMove);
    window.addEventListener('mouseup', handleMouseUp);
    return () => {
      window.removeEventListener('mousemove', handleMouseMove);
      window.removeEventListener('mouseup', handleMouseUp);
    };
  }, []);

  // 재조회
  const handleRequery = useCallback(() => {
    const start = new Date(startInput);
    const end = new Date(endInput);

    // 유효성 검사
    if (isNaN(start.getTime()) || isNaN(end.getTime())) {
      showToast('올바른 날짜/시간을 입력해주세요.');
      return;
    }
    if (start >= end) {
      showToast('종료 시간은 시작 시간보다 이후여야 합니다.');
      return;
    }

    useTrackStore.getState().queryTracks(modal.ships, start, end);
  }, [startInput, endInput, modal.ships]);

  // 프로그레스 바 클릭
  const handleProgressClick = useCallback((e) => {
    const rect = e.currentTarget.getBoundingClientRect();
    const ratio = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width));
    useTrackStore.getState().setProgressByRatio(ratio);
  }, []);

  // 닫기
  const handleClose = useCallback(() => {
    closeTrackModal(modal.id);
  }, [closeTrackModal, modal.id]);

  return (
    <div
      className="track-query-viewer"
      style={{
        transform: `translate(calc(-50% + ${position.x}px), calc(${position.y}px))`,
      }}
    >
      {/* === Header === */}
      <div className="track-query-viewer__header" onMouseDown={handleDragStart}>
        <div className="track-query-viewer__header-info">
          <span className="track-query-viewer__ship-name">
            {shipName || targetId || '항적조회'}
          </span>
          {shipName && targetId && (
            <span className="track-query-viewer__badge track-query-viewer__badge--id">
              {targetId}
            </span>
          )}
          <span className="track-query-viewer__badge track-query-viewer__badge--kind">
            {kindLabel}
          </span>
          {sourceLabel && (
            <span className="track-query-viewer__badge track-query-viewer__badge--signal">
              {sourceLabel}
            </span>
          )}
          {isIntegrated && (
            <span className="track-query-viewer__badge track-query-viewer__badge--integrated">
              통합
            </span>
          )}
          {isLoading && (
            <span className="track-query-viewer__loading-badge">조회중</span>
          )}
        </div>
        <div className="track-query-viewer__header-actions">
          <button
            type="button"
            className="track-query-viewer__close-btn"
            onClick={handleClose}
            title="닫기"
          >
            &#10005;
          </button>
        </div>
      </div>

      {/* === Body === */}
      <div className="track-query-viewer__body">
        {/* 에러 */}
        {error && (
          <div className="track-query-viewer__error">{error}</div>
        )}

        {/* 로딩 (데이터 없을 때) */}
        {isLoading && !hasTracks && (
          <div className="track-query-viewer__loading">항적 데이터 조회 중...</div>
        )}

        {/* 데이터 없음 */}
        {!isLoading && !hasTracks && !error && (
          <div className="track-query-viewer__empty">항적 데이터가 없습니다.</div>
        )}

        {/* === Progress Section === */}
        {hasTracks && (
          <div className="track-query-viewer__progress-section">
            {/* 시간 정보 (3열) */}
            <div className="track-query-viewer__time-info">
              <span className="track-query-viewer__time-start">
                {formatShortDateTime(dataStartTime)}
              </span>
              <span className="track-query-viewer__time-current">
                {formatDateTime(currentTime)}
              </span>
              <span className="track-query-viewer__time-end">
                {formatShortDateTime(dataEndTime)}
              </span>
            </div>

            {/* 프로그레스 바 */}
            <div
              className="track-query-viewer__progress-bar"
              onClick={handleProgressClick}
            >
              <div className="track-query-viewer__progress-track" />
              <div
                className="track-query-viewer__progress-fill"
                style={{ width: `${progress}%` }}
              />
              <div
                className="track-query-viewer__progress-handle"
                style={{ left: `${progress}%` }}
              />
            </div>

            {/* 옵션 체크박스 */}
            <div className="track-query-viewer__options">
              <label className="track-query-viewer__option">
                <input
                  type="checkbox"
                  checked={showPoints}
                  onChange={(e) => useTrackStore.getState().setShowPoints(e.target.checked)}
                />
                <span>포인트</span>
              </label>
              <label className="track-query-viewer__option">
                <input
                  type="checkbox"
                  checked={showVirtualShip}
                  onChange={(e) => useTrackStore.getState().setShowVirtualShip(e.target.checked)}
                />
                <span>선박 아이콘</span>
              </label>
              <label className="track-query-viewer__option">
                <input
                  type="checkbox"
                  checked={showLabels}
                  onChange={(e) => useTrackStore.getState().setShowLabels(e.target.checked)}
                />
                <span>선명 표시</span>
              </label>
            </div>
          </div>
        )}

        {/* === Time Form (조회 기간) === */}
        <div className="track-query-viewer__time-form">
          <span className="track-query-viewer__form-label">조회 기간</span>
          <div className="track-query-viewer__time-inputs">
            <input
              type="datetime-local"
              value={startInput}
              onChange={handleStartChange}
              onBlur={handleStartBlur}
              className="track-query-viewer__datetime-input"
            />
            <span className="track-query-viewer__time-separator">~</span>
            <input
              type="datetime-local"
              value={endInput}
              onChange={handleEndChange}
              onBlur={handleEndBlur}
              className="track-query-viewer__datetime-input"
            />
          </div>
          <button
            type="button"
            className="track-query-viewer__query-btn"
            onClick={handleRequery}
            disabled={isLoading}
          >
            {isLoading ? '조회 중...' : '조회'}
          </button>
        </div>

        {/* === Equipment Filter (통합선박만) === */}
        {isIntegrated && (
          <EquipmentFilter ship={ship} />
        )}

        {/* === 항적 통계 (단일 항적) === */}
        {hasTracks && tracks.length === 1 && (
          <div className="track-query-viewer__stats">
            <span>거리: {tracks[0].stats.totalDistance.toFixed(1)} NM</span>
            <span>평균: {tracks[0].stats.avgSpeed.toFixed(1)} kn</span>
            <span>최대: {tracks[0].stats.maxSpeed.toFixed(1)} kn</span>
            <span>포인트: {tracks[0].stats.pointCount}</span>
          </div>
        )}

        {/* === 다중 항적 선박 목록 === */}
        {hasTracks && tracks.length > 1 && !isIntegrated && (
          <div className="track-query-viewer__vessel-list">
            {tracks.map((track) => (
              <VesselItem key={track.vesselId} track={track} />
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

/**
 * 장비 필터 (통합선박 AVETDR)
 * 참조: mda-react-front/src/tracking/hooks/useEquipmentFilter.ts
 */
function EquipmentFilter({ ship }) {
  const tracks = useTrackStore((s) => s.tracks);
  const disabledSigSrcCds = useTrackStore((s) => s.disabledSigSrcCds);

  // 항적 데이터에 존재하는 장비만 표시
  const availableSigSrcCds = new Set(tracks.map((t) => t.sigSrcCd));

  const handleToggle = useCallback((sigSrcCd) => {
    useTrackStore.getState().toggleEquipment(sigSrcCd);
  }, []);

  const handleEnableAll = useCallback(() => {
    useTrackStore.getState().enableAllEquipment();
  }, []);

  const handleResetDefault = useCallback(() => {
    useTrackStore.getState().resetEquipmentToDefault(ship);
  }, [ship]);

  return (
    <div className="track-query-viewer__equipment-filter">
      <span className="track-query-viewer__filter-title">장비별 항적</span>
      <div className="track-query-viewer__filter-actions">
        <button
          type="button"
          className="track-query-viewer__filter-btn"
          onClick={handleEnableAll}
        >
          전체
        </button>
        <button
          type="button"
          className="track-query-viewer__filter-btn"
          onClick={handleResetDefault}
        >
          기본
        </button>
      </div>
      <div className="track-query-viewer__equipment-badges">
        {SIGNAL_FLAG_CONFIGS.map((config) => {
          const hasData = availableSigSrcCds.has(config.signalSourceCode);
          const isEnabled = !disabledSigSrcCds.has(config.signalSourceCode);

          return (
            <button
              key={config.key}
              type="button"
              className={`track-query-viewer__equipment-badge${isEnabled && hasData ? ' active' : ''}${!hasData ? ' no-data' : ''}`}
              style={{
                backgroundColor: isEnabled && hasData ? config.activeColor : undefined,
                borderColor: hasData ? config.activeColor : config.inactiveColor,
              }}
              onClick={() => hasData && handleToggle(config.signalSourceCode)}
              disabled={!hasData}
              title={config.name}
            >
              {config.key}
            </button>
          );
        })}
      </div>
    </div>
  );
}

/**
 * 다중 선박 목록 아이템
 */
function VesselItem({ track }) {
  const handleToggle = useCallback(() => {
    useTrackStore.getState().toggleVesselEnabled(track.vesselId);
  }, [track.vesselId]);

  const enabled = useTrackStore((s) => !s.disabledVesselIds.has(track.vesselId));
  const kindLabel = SHIP_KIND_LABELS[track.shipKindCode] || '기타';
  const color = getShipKindTrackColor(track.shipKindCode);
  const rgbaStr = `rgba(${color[0]}, ${color[1]}, ${color[2]}, ${color[3] / 255})`;

  return (
    <div
      className={`track-query-viewer__vessel-item${enabled ? '' : ' disabled'}`}
      onClick={handleToggle}
    >
      <span
        className="track-query-viewer__vessel-color"
        style={{ backgroundColor: rgbaStr }}
      />
      <span className="track-query-viewer__vessel-name">
        {track.shipName || track.targetId}
      </span>
      <span className="track-query-viewer__vessel-kind">{kindLabel}</span>
      <span className="track-query-viewer__vessel-points">
        {track.stats.pointCount}pts
      </span>
    </div>
  );
}
