import React, { ReactElement, useRef, useLayoutEffect } from 'react';

import {
  PanelColumnWrapper,
  PanelCellWrapper,
  PanelCellInner,
} from './StyledTimePicker';

export type Unit = {
  label: React.ReactText;
  value: number;
};

export type PanelColumnProps = {
  onSelect?: (value: number) => void;
  units?: Unit[];
  value?: number;
};

const PanelColumn = (props: PanelColumnProps): ReactElement => {
  const { units, onSelect, value } = props;

  const ulRef = useRef<HTMLUListElement>(null);
  const liRefs = useRef<Map<number, HTMLElement | null>>(new Map());

  useLayoutEffect(() => {
    const li = value !== undefined ? liRefs.current.get(value) : undefined;
    if (li !== undefined && li !== null && ulRef.current !== null) {
      ulRef.current.scrollTop = li.offsetTop;
    }
  }, [value]);
  return (
    <PanelColumnWrapper ref={ulRef}>
      {units !== undefined &&
        units.map(unit => {
          return (
            <PanelCellWrapper
              key={unit.value}
              ref={(element): void => {
                liRefs.current.set(unit.value, element);
              }}
              onClick={(): void => {
                if (onSelect !== undefined) {
                  onSelect(unit.value);
                }
              }}
            >
              <PanelCellInner themeActive={unit.value === value}>
                {unit.label}
              </PanelCellInner>
            </PanelCellWrapper>
          );
        })}
    </PanelColumnWrapper>
  );
};

export default PanelColumn;
