import { COLORS } from '@rn-ui-lib/colors';
import ProgressBar from './ProgressBar';
import React, { forwardRef, useImperativeHandle, useState } from 'react';
import { View, StyleSheet } from 'react-native';
import { DownloadProgress } from 'react-native-code-push';
import ModalWrapperForAlfredV2 from '@common/ModalWrapperForAlfredV2';
import LottieView from 'lottie-react-native';
import Text from '@rn-ui-lib/components/Text';
import NaviLogoWithTextIcon from '@rn-ui-lib/icons/NaviLogoWithTextIcon';
import { GenericStyles } from '@rn-ui-lib/styles';
import lottieJson from './loader.json';

export interface CodePushLoadingModalRef {
  show: () => void;
  hide: () => void;
  updateProgress: (progress: DownloadProgress) => void;
}

const CodePushLoadingModal = forwardRef<CodePushLoadingModalRef>((_, ref) => {
  const [visible, setVisible] = useState(false);
  const [progress, setProgress] = useState<DownloadProgress>();

  useImperativeHandle(ref, () => ({
    show: () => setVisible(true),
    hide: () => setVisible(false),
    updateProgress: (downloadProgress: DownloadProgress) => setProgress(downloadProgress),
  }));

  const getInMb = (progress: number) => {
    if (progress) return `${(progress / 1024 / 1024).toFixed(2)} MB`;
    return '-';
  };

  return (
    <ModalWrapperForAlfredV2 visible={visible} animationType="fade">
      <View style={styles.modalContainer}>
        <View style={styles.modalContent}>
          <View style={styles.LottieContainerStyles}>
            <LottieView style={styles.LottieStyles} source={lottieJson} autoPlay loop />
          </View>

          {progress ? (
            <View>
              <Text style={styles.header}>Updating to a newer version...</Text>
              <ProgressBar progress={progress?.receivedBytes / progress?.totalBytes} />
              <Text style={styles.progressText}>
                {getInMb(progress?.receivedBytes)} / {getInMb(progress?.totalBytes)}
              </Text>
            </View>
          ) : null}
        </View>
        <View style={GenericStyles.alignCenter}>
          <NaviLogoWithTextIcon />
        </View>
      </View>
    </ModalWrapperForAlfredV2>
  );
});

const styles = StyleSheet.create({
  LottieContainerStyles: {
    alignItems: 'center',
    marginBottom: 24,
  },
  LottieStyles: {
    height: 140,
    width: 140,
  },
  header: {
    color: COLORS.TEXT.BLACK_24,
    fontSize: 14,
    paddingBottom: 6,
    paddingTop: 24,
  },
  modalContainer: {
    flex: 1,
    padding: 20,
  },
  modalContent: {
    flex: 1,
    justifyContent: 'center',
  },
  progressBar: {
    height: 2,
    marginTop: 10,
    width: '100%',
  },
  progressText: {
    color: COLORS.TEXT.BLACK_24,
    fontSize: 14,
    fontWeight: '700',
    marginTop: 6,
  },
});

CodePushLoadingModal.displayName = 'codepush-loading-modal';
export default CodePushLoadingModal;
