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

const InteractionWithProbe = ({
  translations,
  closeProbeReading,
  meterFamilyType,
  setReadingResult,
  onError,
  mockCode,
  probeCommand,
  loadingCurrentDevice,
  changeDateAndTime,
}) => {
  const SIZE_LOADING = scaleUtils.moderateHorizontalScale(164);
  const [beginReading, setBeginReading] = useState(false);
  const bluetoothContext = useBluetoothContext();

  const onBeginReading = useCallback(() => {
    setBeginReading(true);
  }, [setBeginReading]);

  const onSuccess = useCallback(
    arrayResult => {
      setReadingResult(arrayResult);
    },
    [setReadingResult],
  );

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

  useEffect(() => {
    if (!disabledStep) {
      const subscription = changeDatetime({
        mockCode,
        bluetoothContext,
        onBeginReading,
        onSuccess,
        onError,
        probeCommand,
      });

      return () => {
        subscription?.unsubscribe?.();
      };
    }
    return () => {};
    // 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,
  ]);

  const title = changeDateAndTime ? translations.titleWithDate : translations.titleWithoutDate;

  return (
    <Fragment>
      {!beginReading ? (
        <GeneralStep
          sourceImage={ProbeReadingToRead}
          title={title}
          description={translations.interactionWithProbeDescription}
          buttons={[
            {
              title: translations.interactionWithProbeTextButton,
              onPress: () => {
                closeProbeReading();
              },
              key: 'exit',
              secondary: true,
              disabled: disabledStep,
            },
          ]}
          withOpacity={disabledStep}
        >
          <MeterFamilyTypeBadge
            meterFamilyTypePreposition={translations.meterFamilyTypePrepositionBadge}
            meterFamilyType={meterFamilyType}
          />
        </GeneralStep>
      ) : (
        <GeneralStep
          title={title}
          description={translations.interactionWithProbeDescription}
          buttons={[
            {
              title: translations.interactionWithProbeTextButton,
              onPress: () => {
                closeProbeReading();
              },
              key: 'exit',
              secondary: true,
            },
          ]}
        >
          <View style={styles.container}>
            <Loading style={styles.loader} color={Colors.primary04} thickness={8.25} size={SIZE_LOADING} />
            <MeterFamilyTypeBadge
              meterFamilyTypePreposition={translations.meterFamilyTypePrepositionBadge}
              meterFamilyType={meterFamilyType}
            />
          </View>
        </GeneralStep>
      )}
    </Fragment>
  );
};

export default InteractionWithProbe;
