import React, { useEffect, useRef } from 'react';
import type { IndicatorConfig } from '../types';
import { getIndicatorChartTitle } from '../utils/indicatorRegistry';
import { formatBbLegendLabel } from '../utils/bollingerConfig';

interface IndicatorContextToolbarProps {
  indicatorId:           string;
  config:                IndicatorConfig | null;
  chartType?:            string;
  screenX:               number;
  screenY:               number;
  onSettings:            () => void;
  onToggleHidden:        () => void;
  onRemove:              () => void;
  onClose:               () => void;
  /** 툴바 자체에 마우스 진입 시 hide 타이머 취소 */
  onMouseEnterToolbar?:  () => void;
  /** 툴바에서 마우스 이탈 시 hide 타이머 재시작 */
  onMouseLeaveToolbar?:  () => void;
}

/* SVG Icons */
const IcEye = ({ hidden }: { hidden: boolean }) => hidden ? (
  <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="1.5">
    <path d="M1 7 Q4 2.5 7 2.5 Q10 2.5 13 7 Q10 11.5 7 11.5 Q4 11.5 1 7 Z" strokeOpacity="0.35"/>
    <line x1="2" y1="2" x2="12" y2="12"/>
  </svg>
) : (
  <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="1.5">
    <path d="M1 7 Q4 2.5 7 2.5 Q10 2.5 13 7 Q10 11.5 7 11.5 Q4 11.5 1 7 Z"/>
    <circle cx="7" cy="7" r="2"/>
  </svg>
);
const IcGear = () => (
  <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="1.4">
    <circle cx="7" cy="7" r="2.3"/>
    <path d="M7 1 L7.7 2.8 L9.8 2 L9.8 4.2 L11.8 5 L11 7 L11.8 9 L9.8 9.8 L9.8 12 L7.7 11.2 L7 13 L6.3 11.2 L4.2 12 L4.2 9.8 L2.2 9 L3 7 L2.2 5 L4.2 4.2 L4.2 2 L6.3 2.8 Z"/>
  </svg>
);
const IcTrash = () => (
  <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="1.4">
    <line x1="2" y1="4.5" x2="12" y2="4.5"/>
    <path d="M5 4.5 V3 Q5 2 7 2 Q9 2 9 3 V4.5"/>
    <path d="M3 4.5 L3.5 12 Q3.5 12.5 4 12.5 L10 12.5 Q10.5 12.5 10.5 12 L11 4.5"/>
  </svg>
);
const IcMore = () => (
  <svg width="14" height="14" viewBox="0 0 14 14" fill="currentColor">
    <circle cx="2.5" cy="7" r="1.3"/>
    <circle cx="7"   cy="7" r="1.3"/>
    <circle cx="11.5"cy="7" r="1.3"/>
  </svg>
);

/** 인디케이터 파라미터 요약 문자열 (예: "RSI (14)") */
function paramSummary(config: IndicatorConfig): string {
  if (config.type === 'BollingerBands') {
    return formatBbLegendLabel(config.params ?? {});
  }
  const name = getIndicatorChartTitle(config.type);
  const nums = Object.values(config.params)
    .filter(v => typeof v === 'number')
    .slice(0, 2)
    .join(', ');
  return nums ? `${name} (${nums})` : name;
}

const IndicatorContextToolbar: React.FC<IndicatorContextToolbarProps> = ({
  indicatorId, config, chartType, screenX, screenY,
  onSettings, onToggleHidden, onRemove, onClose,
  onMouseEnterToolbar, onMouseLeaveToolbar,
}) => {
  const ref = useRef<HTMLDivElement>(null);

  // hover 모드(onMouseEnterToolbar 존재)에선 hover leave 로만 닫힘
  // 클릭 모드에선 외부 클릭 시 닫기
  useEffect(() => {
    if (onMouseEnterToolbar) return; // hover 모드 → 외부 클릭 핸들러 불필요
    const handler = (e: MouseEvent) => {
      if (ref.current && !ref.current.contains(e.target as Node)) {
        onClose();
      }
    };
    const tid = setTimeout(() => document.addEventListener('mousedown', handler), 100);
    return () => { clearTimeout(tid); document.removeEventListener('mousedown', handler); };
  }, [onClose, onMouseEnterToolbar]);

  // pane 좌측 상단 기준 (screenX = pane left, screenY = pane top)
  const W = 240;
  const isMain   = indicatorId === '__main__';
  /** 메인 캔들 pane 상단 tv-legend(OHLCV) 행 아래에 배치 */
  const TOP_GAP_MAIN = 38;
  let left = screenX + 8;
  let top  = screenY + (isMain ? TOP_GAP_MAIN : 8);
  // 화면 오른쪽 경계 보정
  if (left + W > window.innerWidth - 8) left = window.innerWidth - W - 8;

  const isHidden = config?.hidden === true;
  const label    = isMain
    ? (chartType === 'candlestick' ? '캔들스틱' : chartType ?? '메인 차트')
    : (config ? paramSummary(config) : indicatorId);

  return (
    <div
      ref={ref}
      className="ind-ctx-toolbar"
      style={{ left, top }}
      onMouseDown={e => e.stopPropagation()}
      onMouseEnter={onMouseEnterToolbar}
      onMouseLeave={onMouseLeaveToolbar}
    >
      {/* 이름 */}
      <span className="ind-ctx-name" title={label}>{label}</span>

      {/* 가시성 토글 */}
      {!isMain && (
        <button
          className="ind-ctx-btn"
          title={isHidden ? '표시' : '숨기기'}
          onClick={onToggleHidden}
        >
          <IcEye hidden={isHidden} />
        </button>
      )}

      {/* 설정 */}
      <button
        className="ind-ctx-btn"
        title="설정 (더블클릭)"
        onClick={onSettings}
      >
        <IcGear />
      </button>

      {/* 삭제 */}
      {!isMain && (
        <button
          className="ind-ctx-btn ind-ctx-del"
          title="삭제"
          onClick={onRemove}
        >
          <IcTrash />
        </button>
      )}

      {/* 더보기 */}
      <button className="ind-ctx-btn" title="더보기">
        <IcMore />
      </button>
    </div>
  );
};

export default IndicatorContextToolbar;
