import React, {useEffect} from 'react';
import {ScrollView, View, FlatList} from 'react-native';
import {useTranslation} from 'react-i18next';
import {useSafeAreaInsets} from 'react-native-safe-area-context';
import {useNavigation} from '@react-navigation/native';
import {Pressable} from '@components';
import i18n, {Language} from '@config/i18n';
import {useLearning} from '@modules/learning/hooks/useLearning';
import CourseTile from '@modules/learning/components/CourseTile';
import PathItem from '@modules/learning/screens/Learning/components/PathItem';
import {
  LearningCourseItem,
  LearningPathItem,
  LearningSession,
} from '@modules/learning/interfaces';
import NoResults from '@modules/learning/screens/Learning/components/NoResults';
import {
  useInstanceId,
  useModuleNames,
  usePermissions,
  useUser,
} from '@redux/selectors';
import {Typography} from '@shared/components';
import {SPACING, useTheme} from '@shared/theme';
import {AMPLITUDE_EVENTS, Screens, windowDimensions} from '@shared/constants';
import {logAmplitudeEvent} from '@shared/utils/logs';
import {capitalize} from '@shared/utils';

import {HomeLearningSk} from './components/HomeLearningSk';
import {styles} from './styles';
import SessionItem from '../Sessions/screens/SessionsList/components/SessionItem';
import {LEARNING_HOME_CARD_WIDTH} from '../../constants';

const Learning = () => {
  const {t} = useTranslation();
  const {theme} = useTheme();
  const navigation = useNavigation();
  const {VIEW_LEARNING_SESSIONS, VIEW_COURSES, VIEW_PATHS} = usePermissions();
  const moduleNames = useModuleNames();
  const {bottom: paddingBottom} = useSafeAreaInsets();
  const user = useUser();
  const instanceId = useInstanceId();
  const {data, isLoading} = useLearning();
  const {lastCourseVisited, courses} = data || {
    lastCourseVisited: null,
    courses: [],
  };

  useEffect(() => {
    logAmplitudeEvent(AMPLITUDE_EVENTS.LEARNING_MINIAPP_ENTERED, {
      userId: user.id,
      instanceId,
    });
  }, [user.id, instanceId]);

  const moduleName =
    capitalize(moduleNames?.[i18n.language as Language]?.LEARNING, false) ||
    t('learning.learning.title');

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

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

  const onViewAllCourses = () => {
    navigation.navigate(Screens.COURSES);
  };

  const onViewAllPaths = () => {
    navigation.navigate(Screens.PATHS);
  };

  const onViewAllSessions = () => {
    navigation.navigate(Screens.LEARNING_SESSIONS);
  };

  const renderCourseItem = ({item}: {item: LearningCourseItem}) => (
    <View style={styles.cardItem}>
      <CourseTile
        id={item.id}
        title={item.title}
        pictureUrl={item.pictureUrl}
        dueDate={item.dueDate}
        lessonsCompleted={item.lessonsCompleted}
        totalLessons={item.totalLessons}
        category={item.category}
        onCoursePress={onCoursePress}
        showFooter={false}
        status={item.status}
        progress={item.progress}
        isObligatory={item.isObligatory}
      />
    </View>
  );

  const onPathItemPress = (pathId: number) => () => {
    navigation.navigate(Screens.PATH, {pathId});
  };

  const renderLearningSessionItem = ({item}: {item: LearningSession}) => (
    <SessionItem session={item} />
  );
  const renderPathItem = ({item}: {item: LearningPathItem}) => {
    let width = LEARNING_HOME_CARD_WIDTH;
    if (data?.learningPaths.length === 1) {
      width = windowDimensions.width - SPACING.x4;
    }

    return (
      <View style={{width}}>
        <PathItem path={item} onPress={onPathItemPress(item.id)} />
      </View>
    );
  };

  const hasLearningSessions =
    VIEW_LEARNING_SESSIONS && !!data?.learningSessions?.length;
  const hasCourses = VIEW_COURSES && !!data?.courses?.length;
  const hasLearningPaths = VIEW_PATHS && !!data?.learningPaths?.length;

  if (isLoading) {
    return <HomeLearningSk />;
  }

  const isEmpty =
    !hasLearningPaths &&
    !hasCourses &&
    !hasLearningSessions &&
    !lastCourseVisited;

  if (isEmpty) {
    return <NoResults />;
  }

  return (
    <ScrollView
      showsVerticalScrollIndicator={false}
      style={[
        styles.container,
        {backgroundColor: theme.background.layout.default},
      ]}
      contentContainerStyle={[
        {paddingBottom},
        {backgroundColor: theme.background.layout.default},
      ]}>
      {lastCourseVisited && (
        <View
          style={[
            styles.firstSection,
            {
              backgroundColor: theme.background.elements.brand,
            },
          ]}>
          <Typography variant="xxs" style={styles.subHeader}>
            {t('learning.common.hi_user', {user: user.firstName})}
          </Typography>
          <View style={styles.sectionHeader}>
            <Typography weight="semiBold" variant="s">
              {t('learning.learning.continue')}
            </Typography>
          </View>
          <View style={styles.lastCourseVisitedContainer}>
            <CourseTile
              id={lastCourseVisited.id}
              title={lastCourseVisited.title}
              pictureUrl={lastCourseVisited.pictureUrl}
              dueDate={lastCourseVisited.dueDate}
              lessonsCompleted={lastCourseVisited.lessonsCompleted}
              totalLessons={lastCourseVisited.totalLessons}
              category={lastCourseVisited.category}
              status={lastCourseVisited.status}
              progress={lastCourseVisited.progress}
              isObligatory={lastCourseVisited.isObligatory}
              onCoursePress={onCoursePress}
              secondaryText={`${t(
                'learning.course.lesson.finished_lessons',
              )}: ${lastCourseVisited.lessonsCompleted}/${
                lastCourseVisited.totalLessons
              }`}
            />
          </View>
        </View>
      )}
      {hasCourses && (
        <View
          style={[
            styles.section,
            {backgroundColor: theme.background.layout.default},
          ]}>
          <View style={styles.sectionHeader}>
            <Typography weight="semiBold">
              {t('learning.course.title_yours')}
            </Typography>
            <Pressable onPress={onViewAllCourses}>
              <Typography
                variant="xs"
                color={theme.text.neutral.brand}
                weight="semiBold">
                {t('learning.courses.view_all')}
              </Typography>
            </Pressable>
          </View>
          <FlatList
            data={courses}
            renderItem={renderCourseItem}
            style={styles.list}
            contentContainerStyle={styles.listContent}
            horizontal
            showsHorizontalScrollIndicator={false}
          />
        </View>
      )}
      {hasLearningPaths && (
        <View
          style={[
            styles.section,
            {backgroundColor: theme.background.layout.default},
          ]}>
          <View style={styles.sectionHeader}>
            <Typography weight="semiBold">
              {t('learning.path.title_yours')}
            </Typography>
            <Pressable onPress={onViewAllPaths}>
              <Typography
                variant="xs"
                color={theme.text.neutral.brand}
                weight="semiBold">
                {t('learning.path.view_all')}
              </Typography>
            </Pressable>
          </View>
          <FlatList
            data={data?.learningPaths}
            renderItem={renderPathItem}
            style={styles.list}
            contentContainerStyle={styles.listContent}
            horizontal
            showsHorizontalScrollIndicator={false}
          />
        </View>
      )}
      {hasLearningSessions && (
        <View
          style={[
            styles.section,
            {backgroundColor: theme.background.layout.default},
          ]}>
          <View style={styles.sectionHeader}>
            <Typography weight="semiBold">
              {t('learning.session.title_yours')}
            </Typography>
            <Pressable onPress={onViewAllSessions}>
              <Typography
                variant="xs"
                color={theme.text.neutral.brand}
                weight="semiBold">
                {t('learning.path.view_all')}
              </Typography>
            </Pressable>
          </View>
          <FlatList
            data={data?.learningSessions}
            renderItem={renderLearningSessionItem}
            style={styles.list}
            contentContainerStyle={styles.sessionList}
            horizontal
            showsHorizontalScrollIndicator={false}
          />
        </View>
      )}
    </ScrollView>
  );
};

export default Learning;
