import React, {useEffect} from 'react';
import {View} from 'react-native';
import {useTranslation} from 'react-i18next';
import {useSafeAreaInsets} from 'react-native-safe-area-context';
import {IconCertificate} from '@tabler/icons-react-native';
import {Button, RenderSceneProps, Tabs} from '@components';
import {Navigation} from '@interfaces/navigation';
import {TabDetails} from '@modules/learning/interfaces';
import type {PathItem as PathItemType} from '@modules/learning/interfaces';
import {DETAIL_TAB_ROUTES} from '@modules/learning/constants';
import PathDetailSk from '@modules/learning/screens/Path/screens/PathDetail/components/PathDetailSk';
import PathContentSk from '@modules/learning/screens/Path/screens/PathContent/components/PathContentSk';
import {useGetPath} from '@modules/learning/hooks/useGetPath';
import {setPathId} from '@modules/learning/store/usePathIdStore';
import useGetCertificate from '@modules/learning/hooks/useGetCertificate';
import {useUser, useInstanceId} from '@redux/selectors';
import {useTheme} from '@shared/theme';
import {AMPLITUDE_EVENTS, Screens} from '@shared/constants';
import {logAmplitudeEvent} from '@shared/utils/logs';

import PathDetail from './screens/PathDetail';
import PathContent from './screens/PathContent';
import {styles} from './styles';

function Path({
  navigation,
  route: {
    params: {pathId},
  },
}: Navigation<Screens.PATH>) {
  const {bottom: paddingBottom} = useSafeAreaInsets();
  const {t} = useTranslation();

  const user = useUser();
  const instanceId = useInstanceId();

  useEffect(() => {
    logAmplitudeEvent(AMPLITUDE_EVENTS.PATH_DETAILS_VIEWED, {
      userId: user.id,
      instanceId,
      pathId,
      openReason: 'random',
    });
  }, [user.id, instanceId, pathId]);

  const {theme, spacing} = useTheme();

  const {data, isLoading} = useGetPath({pathId});

  const {getCertificate, isLoading: certificateLoading} = useGetCertificate({
    id: pathId,
    title: data?.title,
    type: 'path',
    data,
  });

  const showCertificate = data?.issueCertificate && data.status === 'FINISHED';

  useEffect(() => {
    if (data?.title) {
      navigation.setOptions({
        headerTitle: data?.title,
        headerTitleAlign: 'center',
      });
      setPathId(pathId);
    }
  }, [navigation, data, pathId]);

  const onButtonPress = () => {
    if (data?.courses?.length) {
      const firstAvailableCourse = data.courses.find(
        course =>
          course.status === 'PENDING' || course.status === 'IN_PROGRESS',
      );

      if (firstAvailableCourse) {
        navigation.navigate(Screens.COURSE, {
          courseId: firstAvailableCourse.id,
        });
        return;
      }
      navigation.navigate(Screens.COURSE, {courseId: data.courses[0].id});
    }
  };

  const onCoursePress = (id: number) => {
    navigation.navigate(Screens.COURSE, {courseId: id});
  };

  const renderScene = (key: string, path: PathItemType) => {
    switch (key) {
      case TabDetails.Detail:
        return <PathDetail {...path} />;
      case TabDetails.Content:
        return (
          <PathContent
            courses={path.courses}
            onCoursePress={onCoursePress}
            isSequential={path.isSequential}
          />
        );
      default:
        return null;
    }
  };

  const statusLabel =
    data?.status === 'PENDING'
      ? 'general.start'
      : data?.status === 'IN_PROGRESS'
      ? 'general.continue'
      : 'learning.path.view';

  const generalRenderScene = ({route: {key}}: RenderSceneProps) => {
    return isLoading ? (
      key === TabDetails.Detail ? (
        <PathDetailSk />
      ) : (
        <PathContentSk />
      )
    ) : (
      <View
        style={[
          styles.flex,
          {backgroundColor: theme.background.layout.default},
        ]}>
        {data && renderScene(key, data)}
        <View
          style={[
            styles.buttonContainer,
            {
              backgroundColor: theme.background.layout.tertiary,
              paddingBottom: paddingBottom + spacing.x2,
              shadowColor: theme.shadow.inverted,
            },
          ]}>
          {showCertificate && (
            <Button
              IconLeft={IconCertificate}
              variant="primary"
              text={t('learning.common.view_certificate')}
              onPress={getCertificate}
              style={styles.button}
              isLoading={certificateLoading}
            />
          )}
          {!!data?.courses?.length && (
            <Button
              variant={showCertificate ? 'secondary' : 'primary'}
              text={t(`${statusLabel}`)}
              onPress={onButtonPress}
              style={styles.button}
              isLoading={isLoading}
            />
          )}
        </View>
      </View>
    );
  };

  return (
    <View
      style={[styles.flex, {backgroundColor: theme.background.layout.default}]}>
      <Tabs routes={DETAIL_TAB_ROUTES} renderScene={generalRenderScene} lazy />
    </View>
  );
}

export default Path;
