import React, { useState, useEffect, useCallback } from 'react';
import { useTheme } from '@emotion/react';
import { StyledSegment } from '../../Segment/style';
import { ECalendarMode } from '../../../SACalendar/types';

export interface IModeSelector {
  mode: ECalendarMode;
  setMode: (mode: ECalendarMode) => void;
}

export const ModeSelector = ({ mode, setMode }: IModeSelector) => {
  const colors = useTheme();
  const [width, setWidth] = useState<number>(100);

  const getId = useCallback((mode: ECalendarMode) => `view_button_${mode}`, []);

  useEffect(() => {
    const item = document.getElementById(getId(mode));
    if (item) {
      setWidth(item.offsetLeft);
    }
  }, [mode]);

  return (
    <StyledSegment
      theme={{ ...colors }}
      isPressed={mode !== Object.values(ECalendarMode)[0]}
      width={width}
    >
      <div>
        <span className="background">
          {Object.values(ECalendarMode).map((item) => (
            <span
              key={item}
              id={getId(item)}
              className="label"
              onClick={() => setMode(item)}
            >
              {item}
            </span>
          ))}
          <span className="toggle">{mode}</span>
        </span>
      </div>
    </StyledSegment>
  );
};
