import React, { FC, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
  Tab,
  TabList,
  TabPanel,
  TabPanels,
  Tabs,
  Text,
} from '@chakra-ui/react';

import { mockReview } from '../../../../mocks/landing';
import { Review } from '../../../../models';

import { ReviewCard } from './ReviewCard';

const SLIDE_CHANGE_INTERVAL = 5000;

export const ReviewsSlider: FC = () => {
  const { i18n } = useTranslation();
  const mockReviews: Review.View[] = mockReview.getReviewsByLocale(i18n.language);
  const reviewsCount = mockReviews.length;

  const [activeTab, setActiveTab] = useState(0);
  const [isSlideShowStopped, setIsSlideShowStopped] = useState(false);

  useEffect(() => {
    const timer = setInterval(() => {
      const newActiveTab = (activeTab + 1) % reviewsCount;
      setActiveTab(newActiveTab);
    }, SLIDE_CHANGE_INTERVAL);

    if (isSlideShowStopped) {
      clearInterval(timer);
    }

    return () => {
      clearInterval(timer);
    };
  }, [activeTab]);

  return (
    <Tabs
      index={activeTab}
      onChange={(selectedTab) => {
        setIsSlideShowStopped(true);
        setActiveTab(selectedTab);
      }}
      display='flex'
      flexDir='column'
      alignItems='center'
      variant='soft-rounded'
      colorScheme='gray'
    >
      <TabList gap={2}>
        {mockReviews.map(({ id }, i) => (
          <Tab
            key={id}
            w={4}
            h={4}
            p={0}
            bg='gray.100'
            _selected={{
              bg: 'secondary.100',
            }}
          >
            <Text visibility='hidden'>{i}</Text>
          </Tab>
        ))}
      </TabList>
      <TabPanels>
        {mockReviews.map(({ id, ...reviewProps }) => (
          <TabPanel key={id}>
            <ReviewCard {...reviewProps} />
          </TabPanel>
        ))}
      </TabPanels>
    </Tabs>
  );
};
