import { useState, useCallback } from 'react';
import { useMapStore } from '../../stores/mapStore';
import useShipStore from '../../stores/shipStore';
import { downloadShipCsv } from '../../utils/csvDownload';
import { showLiveShips } from '../../utils/liveControl';
import useReplayStore from '../../replay/stores/replayStore';
import useAnimationStore from '../../replay/stores/animationStore';
import { unregisterReplayLayers } from '../../replay/utils/replayLayerRegistry';
import { shipBatchRenderer } from '../../map/ShipBatchRenderer';

// 면적 도형 옵션
const AREA_SHAPES = [
  { key: 'Box', label: '사각형' },
  { key: 'Polygon', label: '다각형' },
  { key: 'Circle', label: '원형' },
];

/**
 * 우측 툴바 컴포넌트
 * - 지도 도구 (초기화, 거리, 면적 등)
 * - 선명표시 (호버 패널)
 * - 줌 컨트롤
 * - 범례, 미니맵
 */
export default function ToolBar() {
  const [isLabelPanelOpen, setIsLabelPanelOpen] = useState(false);
  const [isAreaPanelOpen, setIsAreaPanelOpen] = useState(false);
  const { zoom, zoomIn, zoomOut, activeMeasureTool, setMeasureTool, setAreaShape } = useMapStore();
  const {
    isIntegrate,
    toggleIntegrate,
    showLabels,
    toggleShowLabels,
    labelOptions,
    toggleLabelOption,
    showLegend,
    toggleShowLegend,
  } = useShipStore();

  // 선명표시 옵션 목록
  const labelOptionList = [
    { key: 'showShipName', label: '선박명' },
    { key: 'showSpeedVector', label: '속도벡터' },
    { key: 'showShipSize', label: '선박크기' },
    { key: 'showSignalStatus', label: '신호상태' },
  ];

  return (
    <section id="tool">
      {/* 툴바 */}
      <div className="toolBar">
        <ul className="toolItem space">
          <li>
            <button
              type="button"
              className="tool01"
              onClick={() => {
                // 리플레이 상태 초기화
                useReplayStore.getState().reset();
                useAnimationStore.getState().reset();
                unregisterReplayLayers();

                // 라이브 선박 표시
                showLiveShips();

                // 지도 렌더링 갱신
                shipBatchRenderer.immediateRender();

                // 추후 모든 세팅 초기화 로직 추가 예정
              }}
              title="초기화"
            >초기화</button>
          </li>
          <li>
            <button
              type="button"
              className={`tool02 ${isIntegrate ? 'active' : ''}`}
              onClick={toggleIntegrate}
              title={isIntegrate ? '선박통합 ON' : '선박통합 OFF'}
            >선박통합</button>
          </li>
          {/* 선명표시 버튼 + 호버 패널 영역 */}
          <li
            className="label-panel-wrap"
            onMouseEnter={() => setIsLabelPanelOpen(true)}
            onMouseLeave={() => setIsLabelPanelOpen(false)}
          >
            <button
              type="button"
              className={`tool02 ${showLabels ? 'active' : ''}`}
              onClick={toggleShowLabels}
              title={showLabels ? '선명표시 ON' : '선명표시 OFF'}
            >선명표시</button>
            {/* 선명표시 호버 패널 */}
            {isLabelPanelOpen && (
              <div className="labelPanel">
                <div className="label-panel-inner">
                  <div className="label-panel-title">
                    선명표시 옵션
                  </div>
                  <ul className="label-panel-list">
                    {labelOptionList.map(({ key, label }) => (
                      <li key={key} className="label-panel-item">
                        <span>{label}</span>
                        <label className="switch sm">
                          <input
                            type="checkbox"
                            checked={labelOptions[key] || false}
                            onChange={() => toggleLabelOption(key)}
                          />
                          <span></span>
                        </label>
                      </li>
                    ))}
                  </ul>
                </div>
              </div>
            )}
          </li>
          <li><button type="button" className="tool03">구역설정</button></li>
        </ul>
        <ul className="toolItem mt30">
          <li>
            <button
              type="button"
              className={`tool04 ${activeMeasureTool === 'distance' ? 'active' : ''}`}
              onClick={() => setMeasureTool('distance')}
              title="거리 측정"
            >거리</button>
          </li>
          <li
            className="label-panel-wrap"
            onMouseEnter={() => activeMeasureTool === 'area' && setIsAreaPanelOpen(true)}
            onMouseLeave={() => setIsAreaPanelOpen(false)}
          >
            <button
              type="button"
              className={`tool05 ${activeMeasureTool === 'area' ? 'active' : ''}`}
              onClick={() => {
                setMeasureTool('area');
                setIsAreaPanelOpen(true);
              }}
              title="면적 측정"
            >면적</button>
            {activeMeasureTool === 'area' && isAreaPanelOpen && (
              <div className="labelPanel">
                <div className="label-panel-inner">
                  <div className="label-panel-title">도형 선택</div>
                  <ul className="label-panel-list">
                    {AREA_SHAPES.map(({ key, label }) => (
                      <li
                        key={key}
                        className="label-panel-item area-shape-item"
                        onClick={() => {
                          setAreaShape(key);
                          setIsAreaPanelOpen(false);
                        }}
                      >
                        <span>{label}</span>
                      </li>
                    ))}
                  </ul>
                </div>
              </div>
            )}
          </li>
          <li>
            <button
              type="button"
              className={`tool06 ${activeMeasureTool === 'rangeRing' ? 'active' : ''}`}
              onClick={() => setMeasureTool('rangeRing')}
              title="거리환 측정"
            >거리환</button>
          </li>
        </ul>
        <ul className="toolItem space mt30">
          <li><button type="button" className="tool07">인쇄</button></li>
          <li>
            <button
              type="button"
              className="tool08"
              onClick={async () => {
                const ships = useShipStore.getState().getDownloadShips();
                if (ships.length === 0) {
                  alert('다운로드할 선박 데이터가 없습니다.');
                  return;
                }
                await downloadShipCsv(ships);
              }}
            >다운로드</button>
          </li>
        </ul>
      </div>

      {/* 맵컨트롤 툴바 */}
      <div className="control">
        <ul className="toolItem zoom">
          <li>
            <button type="button" className="zoomin" title="확대" onClick={zoomIn}>
              <span className="blind">확대</span>
            </button>
          </li>
          <li className="num">{zoom}</li>
          <li>
            <button type="button" className="zoomout" title="축소" onClick={zoomOut}>
              <span className="blind">축소</span>
            </button>
          </li>
        </ul>
        <ul className="toolItem space mt30">
          <li>
            <button
              type="button"
              className={`legend ${showLegend ? 'active' : ''}`}
              onClick={toggleShowLegend}
              title={showLegend ? '범례 숨기기' : '범례 표시'}
            >
              범례
            </button>
          </li>
          <li><button type="button" className="minimap">미니맵</button></li>
        </ul>
      </div>
    </section>
  );
}
