import React from 'react';
import { View, ScrollView, TouchableOpacity, Image } from 'react-native';

import { Loading, Label, scaleUtils } from '@widergy/mobile-ui';
import { BluetoothState } from '../../bluetooth/constants';
import type { BluetoothContextType } from '../../bluetooth/context';
import BluetoothImage from '../assets/bonding/bluetooth.png';
import BluetoothInError from '../assets/bonding/bluetoothInError.png';
import Device from '../assets/bonding/device.png';
import DeviceList from '../assets/bonding/deviceList.png';
import Check from '../assets/bonding/check.png';
import DeviceConnected from '../assets/bonding/deviceConnected.png';

import styles from './styles';
import StepProbeLinkage from '../StepProbeLinkage';
import Colors from '../Colors';
import type { ProbePairingTranslations } from './types';

export const configForState = ({
  bluetoothContext,
  closeProbeLinkage,
  selectedDevice,
  setSelectedDevice,
  translations,
  onSetTargetDevice,
}: {
  bluetoothContext: BluetoothContextType;
  closeProbeLinkage: any;
  selectedDevice: any;
  setSelectedDevice: any;
  translations: ProbePairingTranslations;
  onSetTargetDevice: Function;
}) => {
  const SIZE_LOADING = scaleUtils.moderateHorizontalScale(164);
  const error = bluetoothContext.scanError || bluetoothContext.connectionError;
  const map = {
    [BluetoothState.UNAVAILABLE]: {
      renderContent: () => {
        return (
          <StepProbeLinkage
            sourceImage={BluetoothImage}
            title={translations.unavailableTitle}
            description={translations.unavailableDescription}
            bluetoothContext={bluetoothContext}
          />
        );
      },
    },
    [BluetoothState.IDLE]: {
      renderContent: () =>
        error ? (
          <StepProbeLinkage
            sourceImage={BluetoothInError}
            title={bluetoothContext.error2Message(error)}
            description={String(error.code)}
            bluetoothContext={bluetoothContext}
            buttons={[
              {
                title: translations.idleTextButtonExit,
                onPress: () => {
                  closeProbeLinkage();
                  bluetoothContext.stopScan();
                },
                key: 'exit',
              },
            ]}
          />
        ) : (
          <StepProbeLinkage
            sourceImage={Device}
            title={translations.idleTitle}
            description={translations.idleDescription}
            bluetoothContext={bluetoothContext}
            instantNextStep={() => bluetoothContext.startScan()}
            buttons={[
              {
                title: translations.idleTextButtonContinue,
                onPress: () => {
                  bluetoothContext.startScan();
                },
                key: 'scan',
              },
            ]}
          />
        ),
    },
    [BluetoothState.SCANNING]: {
      renderContent: () => {
        return bluetoothContext.scannedDevices.length > 0 ? (
          <StepProbeLinkage
            title={translations.chooseDeviceTitle}
            description={translations.chooseDeviceDescription}
            bluetoothContext={bluetoothContext}
            buttons={[
              {
                title: translations.scanningTextButtonContinue,
                onPress: () => {
                  if (selectedDevice) {
                    bluetoothContext.connect(selectedDevice, onSetTargetDevice).catch(err => {
                      console.log({ err });
                    });
                    setSelectedDevice(null);
                  }
                },
                disabled: !selectedDevice,
                key: 'next',
              },
            ]}
          >
            <ScrollView style={styles.scrollViewDevice}>
              {bluetoothContext.scannedDevices.map(device => (
                <TouchableOpacity
                  onPress={() => {
                    if (selectedDevice !== device) {
                      setSelectedDevice(device);
                    } else {
                      setSelectedDevice(null);
                    }
                  }}
                  key={device.id}
                >
                  <View
                    style={[
                      styles.deviceBox,
                      selectedDevice && selectedDevice === device && { backgroundColor: Colors.primary01 },
                    ]}
                  >
                    <Image source={DeviceList} style={styles.imageDeviceList} />
                    <Label big semiBold color={Colors.dark01}>
                      {device.name}
                    </Label>
                    {selectedDevice === device && <Image source={Check} style={styles.selectedDeviceList} />}
                  </View>
                </TouchableOpacity>
              ))}
            </ScrollView>
          </StepProbeLinkage>
        ) : (
          <StepProbeLinkage
            title={translations.scanningTitle}
            description={translations.scanningDescription}
            bluetoothContext={bluetoothContext}
            buttons={[
              {
                title: translations.scanningTextButtonExit,
                onPress: () => {
                  closeProbeLinkage();
                  bluetoothContext.stopScan();
                },
                key: 'cancel',
                secondary: true,
              },
            ]}
          >
            <Loading style={styles.loader} color={Colors.primary04} thickness={8.25} size={SIZE_LOADING} />
          </StepProbeLinkage>
        );
      },
    },
    [BluetoothState.CONNECTING]: {
      renderContent: () => {
        return (
          <StepProbeLinkage
            title={translations.connectingTitle}
            description={translations.connectingDescription}
            bluetoothContext={bluetoothContext}
            buttons={[
              {
                title: translations.connectingTextButtonExit,
                onPress: () => {
                  bluetoothContext.stopScan();
                },
                key: 'cancel',
              },
            ]}
          >
            <Loading style={styles.loader} color={Colors.primary04} thickness={8.25} size={SIZE_LOADING} />
          </StepProbeLinkage>
        );
      },
    },
    [BluetoothState.CONNECTED]: {
      renderContent: () => (
        <StepProbeLinkage
          sourceImage={DeviceConnected}
          title={translations.connectedTitle}
          bluetoothContext={bluetoothContext}
          buttons={[
            {
              title: translations.connectedTextButtonSuccess,
              onPress: () => {
                closeProbeLinkage();
              },
              key: 'success',
            },
          ]}
        >
          <View style={styles.connectedContainer}>
            <Label big semiBold color={Colors.gray02} style={styles.textConnectedDevice}>
              {bluetoothContext.connectedDevice.name}
            </Label>
          </View>
        </StepProbeLinkage>
      ),
    },
  };

  return map[bluetoothContext.bluetoothState];
};
