import { Loading, scaleUtils } from '@widergy/mobile-ui';
import React, { Fragment, useCallback, useEffect, useMemo, useState } from 'react';
import { View } from 'react-native';
import { useBluetoothContext } from '../../../../bluetooth/useBluetoothContext';
import { BluetoothState } from '../../../../bluetooth/constants';
import Colors from '../../../Colors';
import GeneralStep from '../../../GeneralStep';
import ProbeReadingToRead from '../../../assets/probeReading/probeReadingToRead.png';
import MeterFamilyTypeBadge from '../MeterFamilyTypeBadge';
import styles from './styles';
import { resetToZero } from '../../../../bluetooth/reset/resetToZero';
import { COMMUNICATION_INTERVAL_PER_PROBE_IN_MS } from '../../../../bluetooth/constants';

const InteractionWithProbe = ({
  children,
  onClose,
  loadingCurrentDevice,
  meterFamilyType,
  mockCode,
  onSuccess,
  readingTimeouts,
  readStrategy,
  timeoutRef,
  translations,
  showFamilyBadgeLibrary,
}) => {
  const SIZE_LOADING = scaleUtils.moderateHorizontalScale(164);
  const [beginResetting, setBeginResetting] = useState(false);
  const bluetoothContext = useBluetoothContext();

  const onBeginResetting = useCallback(() => {
    if (readingTimeouts?.probeReadingTimeoutInMilliseconds) {
      clearTimeout(timeoutRef.current);
      timeoutRef.current = setTimeout(() => {
        onClose({ message: translations.timeoutError });
      }, readingTimeouts?.probeReadingTimeoutInMilliseconds);
    }
    setBeginResetting(true);
  }, [onClose, readingTimeouts?.probeReadingTimeoutInMilliseconds, timeoutRef, translations.timeoutError]);

  const disabledStep = !bluetoothContext.isConnected() || bluetoothContext.batteryPercentage == null;
  const resetError = useMemo(
    () => (translations?.resetError ? { message: translations?.resetError } : undefined),
    [translations?.resetError],
  );

  useEffect(() => {
    let subscription: { unsubscribe: any };
    if (!disabledStep) {
      setTimeout(() => {
        subscription = resetToZero({
          bluetoothContext,
          mockCode,
          onBeginResetting,
          onClose,
          onSuccess,
          readStrategy,
          resetError,
        });
      }, COMMUNICATION_INTERVAL_PER_PROBE_IN_MS);
    }
    return () => {
      subscription?.unsubscribe?.();
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [disabledStep]);

  useEffect(() => {
    if (
      bluetoothContext.connectionError ||
      (bluetoothContext.bluetoothState === BluetoothState.IDLE &&
        !loadingCurrentDevice &&
        !bluetoothContext.targetDevice)
    )
      onClose();
  }, [
    bluetoothContext.bluetoothState,
    bluetoothContext.connectionError,
    loadingCurrentDevice,
    bluetoothContext.targetDevice,
    onClose,
  ]);

  return (
    <Fragment>
      {!beginResetting ? (
        <GeneralStep
          sourceImage={ProbeReadingToRead}
          title={translations.readyToResetTitle}
          description={translations.readyToResetDescription}
          buttons={[
            {
              title: translations.cancelResetTextButton,
              onPress: () => {
                onClose();
              },
              key: 'exit',
              secondary: true,
              disabled: disabledStep,
            },
          ]}
          withOpacity={disabledStep}
        >
          <Fragment>
            {children && children}
            {showFamilyBadgeLibrary && (
              <MeterFamilyTypeBadge
                meterFamilyTypePreposition={translations.meterFamilyTypePrepositionBadge}
                meterFamilyType={meterFamilyType}
              />
            )}
          </Fragment>
        </GeneralStep>
      ) : (
        <GeneralStep
          title={translations.resettingToZeroTitle}
          description={translations.resettingToZeroDescription}
          buttons={[
            {
              title: translations.cancelResetTextButton,
              onPress: () => {
                onClose();
              },
              key: 'exit',
              secondary: true,
            },
          ]}
        >
          <View style={styles.container}>
            <Loading style={styles.loader} color={Colors.primary04} thickness={8.25} size={SIZE_LOADING} />
            {children && children}
            {showFamilyBadgeLibrary && (
              <MeterFamilyTypeBadge
                meterFamilyTypePreposition={translations.meterFamilyTypePrepositionBadge}
                meterFamilyType={meterFamilyType}
              />
            )}
          </View>
        </GeneralStep>
      )}
    </Fragment>
  );
};

export default InteractionWithProbe;
