import React, { FunctionComponent, useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import axios from 'axios';
import style from '../web.module.scss';
import YouTube from 'react-youtube';

import { IGuideItem } from '../models/IGuideItem';

type ComponentProps = {
};

export const Archive: FunctionComponent<ComponentProps> = (props): JSX.Element => {
  const { t } = useTranslation();
  const [guideItems, setGuideItems] = useState<IGuideItem[]>([]);

  useEffect(() => {
    if (guideItems.length === 0) {
      const url = process.env.REACT_APP_API_URL;
      const apiUrl = `${url}api/archive`;
      axios.get(apiUrl)
      .then((response) => {
        if (response.data) {
          setGuideItems(response.data);
        }
      });
    }
  }, [guideItems, setGuideItems]);

  const renderVideo = (): JSX.Element[] => {
    const result: JSX.Element[] = [];
    if (guideItems.length > 0) {
      const opts = {
        height: '195',
        width: '320'
      };
      guideItems.forEach((el: IGuideItem) => {
        result.push(
          <div
            key={`archiveItemsLoop-${el.id}`}
            className={style.characterBlock}
            style={{
              animationDelay:`${el.id*0.2}s`
            }}
          >
            <h4>{el.title}</h4>
            <hr />
            <div className={style.centerVideo}>
              <YouTube
                videoId={el.youtube_id}
                opts={opts}
              />
            </div>
          </div>
        );
      });
    }

    return result;
  };

  return (
    <div className={style.guideBody}>
      <h2>{t('archive')}</h2>
      <hr />
      <br />
      {renderVideo()}
    </div>
  );
};
