import React from 'react';
import {View} from 'react-native';
import {useTranslation} from 'react-i18next';
import {useSafeAreaInsets} from 'react-native-safe-area-context';
import {
  IconCheck,
  IconCertificate,
  IconSchool,
} from '@tabler/icons-react-native';
import Confetti from '@assets/learning/confetti.svg';
import HuIcon from '@assets/hu.svg';
import {
  Button,
  CardContainer,
  Skeleton,
  Spinner,
  Typography,
  Image,
  PressableCardContainer,
} from '@components';
import {queryClient} from '@config/queryClient';
import {useSafeAreaBottomPadding} from '@hooks/useSafeAreaBottomPadding';
import LessonHeader from '@modules/learning/components/LessonHeader';
import {PathCourse, PathItem} from '@modules/learning/interfaces';
import useGetCertificate from '@modules/learning/hooks/useGetCertificate';
import {QUERY_KEYS} from '@modules/learning/constants';
import {useGetPathId} from '@modules/learning/hooks/useGetPathId';
import {useUser} from '@redux/selectors';
import {useTheme} from '@shared/theme';
import {isAndroid} from '@shared/utils';

import {styles} from './styles';

interface EndOfCourseWithPathProps {
  title: string;
  isCourseFinished: boolean;
  isPathFinished: boolean;
  onClose: () => void;
  onPressNextCourse: () => void;
  nextCourse: PathCourse | null;
  canGetCertificate: boolean;
}

function EndOfCourseWithPath({
  title,
  onPressNextCourse,
  isCourseFinished,
  isPathFinished,
  onClose,
  nextCourse,
  canGetCertificate,
}: EndOfCourseWithPathProps) {
  const {t} = useTranslation();
  const user = useUser();
  const learningPathId = useGetPathId();
  const pathData = queryClient.getQueryData<PathItem>(
    QUERY_KEYS.path(learningPathId!),
  );

  const {getCertificate, isLoading: pathCertificateLoading} = useGetCertificate(
    {
      id: learningPathId!,
      title: pathData?.title,
      type: 'path',
      data: pathData,
    },
  );

  const firstName = user?.firstName;
  const {theme, iconSizes, spacing} = useTheme();
  const {top, bottom} = useSafeAreaInsets();
  const paddingBottom = useSafeAreaBottomPadding();

  const defaultCourseCover = (
    <View
      style={[
        styles.defaultImageContainer,
        styles.defaultImageContent,
        {backgroundColor: theme.background.layout.brand},
      ]}>
      <IconSchool size={iconSizes.x9} color={theme.graphics.hugo[400]} />
    </View>
  );

  const translations = isPathFinished
    ? {
        title: {
          translation: 'learning.course.completed.title',
          params: {userName: firstName},
        },
        body: {
          translation: 'learning.path.finish.description_without_certificate',
          params: {title},
        },
      }
    : {
        title: {
          translation: 'learning.course.completed.title',
          params: {userName: firstName},
        },
        body: {
          translation: 'learning.course.completed.description',
          params: {courseName: title},
        },
      };

  return (
    <View style={styles.flex}>
      <View
        style={[
          styles.flex,
          {
            paddingTop: top,
            backgroundColor: theme.background.layout.tertiary,
          },
        ]}>
        <LessonHeader hideProgressBar title={title} onClose={onClose} />
        <View
          style={[
            styles.body,
            !isCourseFinished && styles.bodyCentered,
            {backgroundColor: theme.background.layout.default},
          ]}>
          {isCourseFinished && <Confetti />}
          <View style={styles.title}>
            {!isCourseFinished && (
              <View
                style={[
                  styles.iconContainer,
                  {backgroundColor: theme.background.feedback.success},
                ]}>
                <IconCheck
                  color={theme.text.feedback.success}
                  size={iconSizes.x9}
                />
              </View>
            )}
            <Typography weight="semiBold" align="center" numberOfLines={2}>
              {t(translations.title.translation, translations.title.params)}
            </Typography>
            <Typography align="center">
              {t(translations.body.translation, translations.body.params)}
            </Typography>
          </View>
          {isPathFinished && !canGetCertificate && (
            <Button
              size="sm"
              text={t('learning.path.go_back_to_paths')}
              onPress={onClose}
            />
          )}
          {canGetCertificate && (
            <View style={styles.cardContainer}>
              <CardContainer
                footer={{
                  primaryText: t('learning.common.view_certificate'),
                  onPrimaryPress: getCertificate,
                  primaryVariant: 'tertiary',
                }}>
                {pathCertificateLoading ? (
                  <View style={styles.spinnerContainer}>
                    <Spinner />
                  </View>
                ) : (
                  <View style={styles.cardContainerBody}>
                    <IconCertificate
                      size={iconSizes.x9}
                      color={theme.text.neutral.brand}
                    />
                    <Typography align="center" color={theme.text.neutral.brand}>
                      {t('learning.common.your_certificate')}
                    </Typography>
                    <Skeleton.Item height={spacing.x2} width="80%" />
                    <Skeleton.Item height={spacing.x2} width="60%" />
                    <HuIcon />
                  </View>
                )}
              </CardContainer>
            </View>
          )}
        </View>
      </View>
      {!isPathFinished && nextCourse ? (
        <View
          style={[
            styles.footer,
            {
              backgroundColor: theme.background.layout.brand,
              paddingBottom: bottom,
            },
          ]}>
          <View
            style={[
              styles.bottomContainer,
              isAndroid ? {paddingBottom} : styles.noPadding,
            ]}>
            <Typography align="center" variant="s" weight="semiBold">
              {t('learning.path.continue')}
            </Typography>
            <PressableCardContainer
              style={styles.pathContainer}
              onPress={onPressNextCourse}>
              {nextCourse.pictureUrl ? (
                <Image
                  source={{uri: nextCourse.pictureUrl}}
                  style={[
                    styles.pathImage,
                    {backgroundColor: theme.background.layout.brand},
                  ]}
                  containerStyle={styles.pathImageContainer}
                  loaderType="spinner"
                  renderError={defaultCourseCover}
                />
              ) : (
                defaultCourseCover
              )}
              <Typography
                style={styles.titleCard}
                variant="s"
                weight="semiBold"
                numberOfLines={2}>
                {nextCourse.title}
              </Typography>
            </PressableCardContainer>
            <Button
              variant="tertiary"
              text={t('learning.path.go_back_to_paths')}
              onPress={onClose}
            />
          </View>
        </View>
      ) : (
        canGetCertificate && (
          <View
            style={[
              styles.bottomRow,
              {
                paddingBottom: bottom,
                backgroundColor: theme.background.layout.tertiary,
              },
            ]}>
            <View
              style={[
                styles.bottomContainer,
                isAndroid ? {paddingBottom} : styles.noPadding,
              ]}>
              <Button
                text={t('learning.path.go_back_to_paths')}
                variant="secondary"
                onPress={onClose}
              />
            </View>
          </View>
        )
      )}
    </View>
  );
}

export default EndOfCourseWithPath;
