import React, { useState, useRef, useLayoutEffect } from 'react';
import cn from 'classnames';

type Item = {
  id: string;
  title: string;
  children: React.ReactNode;
};

type Props = {
  items: Item[];
};

export const Tabs: React.FC<Props> = ({ items }: Props) => {
  const [activeTab, setActiveTab] = useState<number>();
  const tabsRef = useRef<HTMLDivElement>();
  const sliderRef = useRef<HTMLDivElement>();

  const changeTab = (i: number) => {
    let leftOffset = 0;
    let sliderWidth = 0;
    tabsRef.current
      .querySelectorAll('.bfo-tabs__item-wrapper')
      .forEach((tab, index) => {
        if (index < i) {
          const { width } = tab.getBoundingClientRect();
          leftOffset += width;
        }
        if (index === i) {
          const { width } = tab
            .querySelector('.bfo-tabs__item')
            .getBoundingClientRect();
          sliderWidth = width;
        }
      });

    sliderRef.current.style.width = `${sliderWidth}px`;
    sliderRef.current.style.left = `${leftOffset}px`;
    setActiveTab(i);
  };

  useLayoutEffect(() => {
    setTimeout(() => {
      changeTab(0);
    }, 100);
  }, []);

  const tabs = items.map((item, i) => {
    const isActive = activeTab === i;
    return (
      <div
        className="bfo-tabs__item-wrapper"
        key={item.id}
        role="button"
        tabIndex={0}
        onClick={() => changeTab(i)}
        onKeyUp={() => changeTab(i)}
      >
        <h3
          className={cn('bfo-tabs__item', {
            'bfo-tabs__item--active': isActive,
          })}
        >
          {item.title}
        </h3>
      </div>
    );
  });

  const content = items.map((item, i) => (
    <div
      key={item.id}
      className={cn('bfo-tabs__panel', {
        'bfo-tabs__panel--active': activeTab === i,
      })}
    >
      {item.children}
    </div>
  ));
  return (
    <div className="bfo-tabs">
      <div className="bfo-tabs__wrapper" ref={tabsRef}>
        {tabs}
        <div className="bfo-tabs__slider" ref={sliderRef} />
      </div>
      <div className="bfo-tabs__content-wrapper">{content}</div>
    </div>
  );
};
