import { useState } from 'react';
import type { ChangeEvent, KeyboardEvent } from 'react';
import { parseMileageQuery } from '../../utils/mileage';
import styles from './PlaybackControls.module.scss';

interface PlaybackControlsProps {
  playing: boolean;
  onTogglePlay: () => void;
  onStop: () => void;
  onCapture: () => void;
  onJumpToMileage: (mileage: number) => void;
  /** 측점선 토글을 외부 상태로 제어할 때 사용(미지정 시 내부 상태). */
  lineOn?: boolean;
  onToggleLine?: () => void;
}

export function PlaybackControls({
  playing,
  onTogglePlay,
  onStop,
  onCapture,
  onJumpToMileage,
  lineOn: lineOnProp,
  onToggleLine,
}: PlaybackControlsProps) {
  const [query, setQuery] = useState('');
  const [lineOnInternal, setLineOnInternal] = useState(false);
  const lineOn = lineOnProp ?? lineOnInternal;
  const toggleLine = onToggleLine ?? (() => setLineOnInternal((v) => !v));

  const handleQueryChange = (e: ChangeEvent<HTMLInputElement>): void => {
    setQuery(e.target.value);
  };

  const handleQueryKeyDown = (e: KeyboardEvent<HTMLInputElement>): void => {
    if (e.key !== 'Enter') return;
    const mileage = parseMileageQuery(query);
    if (mileage !== null) {
      onJumpToMileage(mileage);
      setQuery('');
    }
  };

  return (
    <div className={styles.controlsRow}>
      <div className={styles.transportGroup}>
        <div className={styles.leftPanel} />
        <button
          type="button"
          className={styles.transportBtn}
          onClick={onTogglePlay}
          aria-label={playing ? '일시정지' : '재생'}
        >
          {/* 호버 시 _on SVG 로 교체(:hover). 재생/일시정지는 상태로 아이콘 전환 */}
          <span className={playing ? styles.pauseIcon : styles.playIcon} />
        </button>
        <button
          type="button"
          className={styles.stopBtn}
          onClick={onStop}
          aria-label="정지"
        >
          <span className={styles.stopIcon} />
        </button>
        <input
          className={styles.mileageInput}
          value={query}
          onChange={handleQueryChange}
          onKeyDown={handleQueryKeyDown}
          placeholder="측점입력"
        />
      </div>
      <div className={styles.toolGroup}>
        <button
          type="button"
          className={`${styles.toolBtn} ${styles.captureBtn}`}
          onClick={onCapture}
          aria-label="화면캡처"
        >
          <span className={styles.cameraIcon} />
          <span className={styles.toolLabel}>화면캡처</span>
        </button>
        <button
          type="button"
          className={`${styles.toolBtn} ${styles.lineBtn}${lineOn ? ` ${styles.active}` : ''}`}
          onClick={toggleLine}
          aria-pressed={lineOn}
          aria-label="측점선 보기"
        >
          <span className={styles.lineIcon} />
          <span className={styles.toolLabel}>
            {lineOn ? '측점선 끄기' : '측점선 보기'}
          </span>
        </button>
      </div>
    </div>
  );
}
