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';

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={{ alignItems: 'center', marginBottom: 24 }}>
            <LottieView
              style={{ width: 140, height: 140 }}
              source={require('./loader.json')}
              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={{ alignItems: 'center' }}>
          <NaviLogoWithTextIcon />
        </View>
      </View>
    </ModalWrapperForAlfredV2>
  );
});

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

export default CodePushLoadingModal;
