import React, {useEffect, useRef, useState} from 'react';
import {View} from 'react-native';
import {useTranslation} from 'react-i18next';
import {RenderSceneProps, Tabs, TabsRef} from '@components';
import i18n, {Language} from '@config/i18n';
import {Navigation} from '@interfaces/navigation';
import {PathsTab, PathStatus} from '@modules/learning/interfaces';
import {SearchHeader} from '@modules/learning/components/SearchHeader';
import {useUser, useInstanceId, useModuleNames} from '@redux/selectors';
import {useTheme} from '@shared/theme';
import {logAmplitudeEvent} from '@shared/utils/logs';
import {AMPLITUDE_EVENTS, Screens} from '@shared/constants';
import {capitalize} from '@shared/utils';

import PathList from './screens/PathList';
import {styles} from './styles';

function Paths({navigation}: Navigation<Screens.PATHS>) {
  const tabsRef = useRef<Nullable<TabsRef>>(null);
  const {theme} = useTheme();
  const {t} = useTranslation();
  const moduleNames = useModuleNames();
  const moduleName =
    capitalize(moduleNames?.[i18n.language as Language]?.PATHS, false) ||
    t('learning.path.title_long');

  useEffect(() => {
    navigation.setOptions({
      title: moduleName,
    });
  }, [moduleName, navigation]);

  const user = useUser();
  const instanceId = useInstanceId();
  const [searchText, setSearchText] = useState('');
  useEffect(() => {
    logAmplitudeEvent(AMPLITUDE_EVENTS.PATH_MINIAPP_ENTERED, {
      userId: user.id,
      instanceId,
    });
  }, [user.id, instanceId]);

  const routes = [
    {
      key: PathsTab.All,
      label: t('learning.path.tabs.all'),
    },
    {
      key: PathsTab.Pending,
      label: t('learning.path.tabs.pending'),
    },
    {
      key: PathsTab.Ongoing,
      label: t('learning.path.tabs.in_progress'),
    },
    {
      key: PathsTab.Finished,
      label: t('learning.path.tabs.finished'),
    },
  ];

  const renderScene = ({route: {key}}: RenderSceneProps) => {
    const commonProps = {
      searchText,
    };
    switch (key) {
      case PathsTab.All:
        return <PathList {...commonProps} />;
      case PathsTab.Pending:
        return <PathList type={PathStatus.PENDING} {...commonProps} />;
      case PathsTab.Ongoing:
        return <PathList type={PathStatus.IN_PROGRESS} {...commonProps} />;
      case PathsTab.Finished:
        return <PathList type={PathStatus.FINISHED} {...commonProps} />;
      default:
        return null;
    }
  };

  return (
    <View
      style={[
        styles.container,
        {backgroundColor: theme.background.layout.tertiary},
      ]}>
      <SearchHeader
        searchValue={searchText}
        onSearch={setSearchText}
        placeholder={t('learning.path.search')}
        style={styles.searchContainer}
      />
      <Tabs ref={tabsRef} routes={routes} renderScene={renderScene} />
    </View>
  );
}

export default Paths;
