import { Loading, scaleUtils } from '@widergy/mobile-ui';
import React, { Fragment, useCallback, useEffect, 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 { readMeter } from '../../../../bluetooth/readMeter';
import { COMMUNICATION_INTERVAL_PER_PROBE_IN_MS } from '../../../../bluetooth/constants';
import styles from './styles';

const ParcialReading = ({
  onPress,
  translations,
  closeProbeReading,
  meterFamilyType,
  setReadingResult,
  onError,
  mockCode,
  readStrategy,
  loadingCurrentDevice,
  readingDisabled = false,
  recoverMeterNumber,
  children,
  timeoutRef,
  readingTimeouts,
  showFamilyBadgeLibrary,
}) => {
  const SIZE_LOADING = scaleUtils.moderateHorizontalScale(164);
  const [beginReading, setBeginReading] = useState(false);
  const bluetoothContext = useBluetoothContext();

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

  const onSuccess = useCallback(
    arrayResult => {
      if (timeoutRef && timeoutRef.current) {
        clearTimeout(timeoutRef.current);
        timeoutRef.current = null;
      }
      setReadingResult(arrayResult);
    },
    [setReadingResult, timeoutRef],
  );

  const disabledStep =
    !bluetoothContext.isConnected() || bluetoothContext.batteryPercentage == null || readingDisabled;

  useEffect(() => {
    let subscription: { unsubscribe: any };
    if (!disabledStep) {
      setTimeout(() => {
        subscription = readMeter({
          mockCode,
          readStrategy,
          bluetoothContext,
          onBeginReading,
          onSuccess,
          onError,
          recoverMeterNumber,
          onPress,
        });
      }, 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)
    )
      onError();
  }, [
    bluetoothContext.bluetoothState,
    bluetoothContext.connectionError,
    onError,
    loadingCurrentDevice,
    bluetoothContext.targetDevice,
  ]);

  return (
    <Fragment>
      {!beginReading ? (
        <GeneralStep
          sourceImage={ProbeReadingToRead}
          title={translations.probeReadyToReadTitle}
          description={translations.probeReadyToReadDescription}
          buttons={[
            {
              title: translations.probeReadyToReadTextButton,
              onPress: () => {
                closeProbeReading();
              },
              key: 'exit',
              secondary: true,
              disabled: disabledStep,
            },
          ]}
          withOpacity={disabledStep}
        >
          <Fragment>
            {children && children}
            {showFamilyBadgeLibrary && (
              <MeterFamilyTypeBadge
                meterFamilyTypePreposition={translations.meterFamilyTypePrepositionBadge}
                meterFamilyType={meterFamilyType}
              />
            )}
          </Fragment>
        </GeneralStep>
      ) : (
        <GeneralStep
          title={translations.takingReadingTitle}
          description={translations.takingReadingDescription}
          buttons={[
            {
              title: translations.takingReadingTextButton,
              onPress: () => {
                closeProbeReading();
              },
              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 ParcialReading;
