import React, { useCallback, useEffect, useMemo, useState } from 'react';
import {
  CHART_TIME_FORMAT_PRESETS,
  formatUnixWithChartPattern,
  isPresetChartTimeFormat,
  normalizeChartTimeFormat,
} from '../utils/chartTimeFormat';

const CUSTOM_VALUE = '__custom__';

interface ChartTimeFormatPickerProps {
  value: string;
  onChange: (format: string) => void;
}

const ChartTimeFormatPicker: React.FC<ChartTimeFormatPickerProps> = ({ value, onChange }) => {
  const normalized = normalizeChartTimeFormat(value);
  const isPreset = isPresetChartTimeFormat(normalized);

  const [selectValue, setSelectValue] = useState(
    isPreset ? normalized : CUSTOM_VALUE,
  );
  const [customText, setCustomText] = useState(
    isPreset ? '' : normalized,
  );

  useEffect(() => {
    const n = normalizeChartTimeFormat(value);
    if (isPresetChartTimeFormat(n)) {
      setSelectValue(n);
      setCustomText('');
    } else {
      setSelectValue(CUSTOM_VALUE);
      setCustomText(n);
    }
  }, [value]);

  const preview = useMemo(() => {
    const fmt = selectValue === CUSTOM_VALUE
      ? normalizeChartTimeFormat(customText)
      : selectValue;
    return formatUnixWithChartPattern(Math.floor(Date.now() / 1000), fmt);
  }, [selectValue, customText]);

  const commitCustom = useCallback(() => {
    const next = normalizeChartTimeFormat(customText);
    onChange(next);
  }, [customText, onChange]);

  return (
    <div className="stg-chart-time-format">
      <select
        className="stg-select"
        value={selectValue}
        onChange={e => {
          const v = e.target.value;
          setSelectValue(v);
          if (v !== CUSTOM_VALUE) {
            onChange(v);
          } else if (customText.trim()) {
            onChange(normalizeChartTimeFormat(customText));
          }
        }}
      >
        {CHART_TIME_FORMAT_PRESETS.map(p => (
          <option key={p.id} value={p.id}>{p.label}</option>
        ))}
        <option value={CUSTOM_VALUE}>직접 입력…</option>
      </select>
      {selectValue === CUSTOM_VALUE && (
        <input
          type="text"
          className="stg-input stg-chart-time-format-custom"
          placeholder="예: yyyy-MM-dd HH:mm:ss, dd/MM/yyyy HH:mm"
          value={customText}
          onChange={e => setCustomText(e.target.value)}
          onBlur={commitCustom}
          onKeyDown={e => { if (e.key === 'Enter') commitCustom(); }}
        />
      )}
      <span className="stg-hint stg-chart-time-format-preview" title="현재 시각 미리보기">
        미리보기: {preview}
      </span>
      <span className="stg-hint">
        토큰: yyyy, yy, MM, dd, HH, mm, ss
      </span>
    </div>
  );
};

export default ChartTimeFormatPicker;
