import React, { useEffect, useRef } from 'react';
import {
  INFLECTION_33_FILTER_OPTIONS,
  inflection33FilterSummary,
  inflection33SummaryText,
  type Inflection33FilterLevel,
} from '../../utils/inflection33Strategy';

interface Props {
  mode: 'buy' | 'sell';
  period: number;
  filterLevel: Inflection33FilterLevel;
  onChange: (filterLevel: Inflection33FilterLevel) => void;
  onClose: () => void;
  popoverClassName?: string;
  variant?: 'popover' | 'inline';
}

export default function Inflection33PairNodeSettings({
  mode,
  period,
  filterLevel,
  onChange,
  onClose,
  popoverClassName = 'se-flow-settings-pop',
  variant = 'popover',
}: Props) {
  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (variant === 'inline') return;
    const onDoc = (e: MouseEvent) => {
      if (ref.current && !ref.current.contains(e.target as Node)) onClose();
    };
    document.addEventListener('mousedown', onDoc);
    return () => document.removeEventListener('mousedown', onDoc);
  }, [onClose, variant]);

  const body = (
    <>
      <label className="se-flow-settings-field se-flow-settings-field--readonly">
        <span>변곡 기간</span>
        <output className="se-flow-settings-readout">
          EMA{period} · {period}봉 종가 채널
        </output>
      </label>

      <label className="se-flow-settings-field">
        <span>필터 강도</span>
        <select
          className="se-combo-num-select sp-cond-sel"
          value={filterLevel}
          onChange={e => onChange(e.target.value as Inflection33FilterLevel)}
        >
          {INFLECTION_33_FILTER_OPTIONS.map(o => (
            <option key={o.value} value={o.value}>{o.label}</option>
          ))}
        </select>
      </label>

      <p className="se-flow-settings-hint">
        {INFLECTION_33_FILTER_OPTIONS.find(o => o.value === filterLevel)?.desc}
      </p>
      <p className="se-flow-settings-hint se-flow-settings-hint--muted">
        {inflection33FilterSummary(mode, filterLevel)}
      </p>
      <p className="se-flow-settings-hint se-flow-settings-hint--muted">
        {inflection33SummaryText(mode, period, filterLevel)}
      </p>
    </>
  );

  if (variant === 'inline') {
    return (
      <div className="se-inflection33-inline-settings" onClick={e => e.stopPropagation()}>
        {body}
      </div>
    );
  }

  return (
    <div
      ref={ref}
      className={popoverClassName}
      role="dialog"
      aria-label="33변곡 복합 필터 설정"
      onClick={e => e.stopPropagation()}
    >
      <div className="se-flow-settings-head">
        <span>필터 강도</span>
        <button
          type="button"
          className="se-flow-settings-close"
          aria-label="닫기"
          title="닫기"
          onClick={onClose}
        >
          ×
        </button>
      </div>
      {body}
    </div>
  );
}
