import React, { useCallback, useEffect, useState } from 'react';
import { loadCustomTabs, type IndicatorCustomTab } from '../utils/indicatorCustomTabsStorage';
import { applyIndicatorTab } from '../utils/indicatorTabApply';

const IcApplyTab = () => (
  <svg width="12" height="12" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="1.8">
    <line x1="7" y1="2" x2="7" y2="12" />
    <line x1="2" y1="7" x2="12" y2="7" />
  </svg>
);

interface Props {
  onAddMany?: (types: string[]) => void;
  onAdd?: (type: string) => void;
}

const IndicatorTabQuickButtons: React.FC<Props> = ({ onAddMany, onAdd }) => {
  const [customTabs, setCustomTabs] = useState<IndicatorCustomTab[]>(() => loadCustomTabs());

  const refreshTabs = useCallback(() => {
    setCustomTabs(loadCustomTabs());
  }, []);

  useEffect(() => {
    refreshTabs();
    window.addEventListener('gc-indicator-custom-tabs-changed', refreshTabs);
    return () => window.removeEventListener('gc-indicator-custom-tabs-changed', refreshTabs);
  }, [refreshTabs]);

  if (!onAddMany && !onAdd) return null;

  const applyMain = () => {
    applyIndicatorTab({ kind: 'main' }, onAddMany, onAdd);
  };

  const applyCustom = (tab: IndicatorCustomTab) => {
    applyIndicatorTab({ kind: 'custom', tab }, onAddMany, onAdd);
  };

  return (
    <div className="tv-ind-tab-quick" role="group" aria-label="지표 탭 빠른 적용">
      <button
        type="button"
        className="tv-ind-tab-quick-btn"
        title="주요지표 탭 — 차트 보조지표 일괄 교체"
        aria-label="주요지표 탭 일괄 적용"
        onClick={applyMain}
      >
        <IcApplyTab />
        <span className="tv-ind-tab-quick-label">주요</span>
      </button>
      {customTabs.map(tab => (
        <button
          key={tab.id}
          type="button"
          className="tv-ind-tab-quick-btn"
          title={`${tab.name} 탭 — 차트 보조지표 일괄 교체`}
          aria-label={`${tab.name} 탭 일괄 적용`}
          onClick={() => applyCustom(tab)}
        >
          <IcApplyTab />
          <span className="tv-ind-tab-quick-label">{tab.name}</span>
        </button>
      ))}
    </div>
  );
};

export default IndicatorTabQuickButtons;
