import * as React from 'react';
import {
  SafeAreaView,
  StatusBar,
  Button,
  Alert,
  View,
  TextInput,
  StyleSheet,
  Text,
} from 'react-native';
import {
  webIdEventEmitter,
  start,
  createMetaPlugin,
  verifyActionId,
  WebIdSdkEvent,
  parseJSONToType,
  type ProductPluginResultFailed,
  type ProductPluginResultSuccess,
  type iOSTheme,
} from 'react-native-web-id-meta-plugin';
import { URL, USERNAME, API_KEY, CERT_BASE64 } from '@env';
import BouncyCheckbox from 'react-native-bouncy-checkbox';

export default function App() {
  const [actionId, onChangeActionId] = React.useState('');
  var selectedPlugins: Set<string> = new Set();

  webIdEventEmitter.addListener(WebIdSdkEvent.finishedFailed, (eventData) => {
    let result = parseJSONToType<ProductPluginResultFailed>(eventData);
    if (result != undefined) {
      console.log(
        'received failed event with result code: ',
        result.genericResultCode
      );
    }
  });

  webIdEventEmitter.addListener(WebIdSdkEvent.finishedSuccess, (eventData) => {
    let result = parseJSONToType<ProductPluginResultSuccess>(eventData);
    if (result != undefined) {
      console.log(
        'received failed event with process finished: ',
        result.processFinished
      );
    }
  });

  const styles = StyleSheet.create({
    input: {
      height: 40,
      margin: 12,
      borderWidth: 1,
      padding: 10,
    },
  });

  const showAlert = (title: string, message: string) => {
    Alert.alert(title, message, [{ text: 'OK', onPress: () => {} }], {
      cancelable: false,
    });
  };

  const onCreateMetaPlugin = () => {
    createMetaPlugin(
      URL,
      USERNAME,
      API_KEY,
      [CERT_BASE64],
      Array.from(selectedPlugins)
    )
      .then((data) => {
        showAlert('Success', data);
      })
      .catch((error) => {
        showAlert('Error!', error.code + '\n' + error.message);
        console.log(error.code + '\n' + error.message);
      });
  };

  const onVerifyActionId = () => {
    verifyActionId(actionId)
      .then((verifyActionResult) => {
        console.log(verifyActionResult);
        showAlert(
          'Success',
          verifyActionResult.userAction.userActionStatus.identState
        );
      })
      .catch((error) => {
        showAlert('Error!', error.code + '\n' + error.message);
        console.log(error.code + '\n' + error.message);
      });
  };

  const onStart = () => {
    let iOSLightTheme: iOSTheme = {
      Background: '#AABBFF',
      PrimaryColor: '#AA0000',
      primaryButtonTextCase: 'upper',
      primaryButtonBorderWidth: 12,
    };
    let iOSDarkTheme: iOSTheme = {
      Background: '#AABBBFF',
      PrimaryColor: '#AA0000',
      primaryButtonTextCase: 'upper',
      primaryButtonBorderWidth: 12,
    };

    start(iOSLightTheme, iOSDarkTheme)
      .then((message) => {
        showAlert('Success', message);
      })
      .catch((error) => {
        showAlert('Error!', error.code + '\n' + error.message);
        console.log(error.code + '\n' + error.message);
      });
  };

  return (
    <SafeAreaView>
      <StatusBar />
      <View>
        <View>
          <View>
            <BouncyCheckbox
              isChecked={selectedPlugins.has('AutoIdOnServer')}
              onPress={(isChecked: boolean) =>
                isChecked === true
                  ? selectedPlugins.add('AutoIdOnServer')
                  : selectedPlugins.delete('AutoIdOnServer')
              }
            />
            <Text>AutoIdOnServer</Text>
          </View>
          <View>
            <BouncyCheckbox
              isChecked={selectedPlugins.has('PayOnServer')}
              onPress={(isChecked: boolean) =>
                isChecked === true
                  ? selectedPlugins.add('PayOnServer')
                  : selectedPlugins.delete('PayOnServer')
              }
            />
            <Text>PayOnServer</Text>
          </View>
          <View>
            <BouncyCheckbox
              isChecked={selectedPlugins.has('VideoId')}
              onPress={(isChecked: boolean) =>
                isChecked === true
                  ? selectedPlugins.add('VideoId')
                  : selectedPlugins.delete('VideoId')
              }
            />
            <Text>VideoId</Text>
          </View>
          <View>
            <BouncyCheckbox
              isChecked={selectedPlugins.has('EIdOnServer')}
              onPress={(isChecked: boolean) =>
                isChecked === true
                  ? selectedPlugins.add('EIdOnServer')
                  : selectedPlugins.delete('EIdOnServer')
              }
            />
            <Text>EIdOnServer</Text>
          </View>
        </View>

        <Button title="Create Meta Plugin" onPress={onCreateMetaPlugin} />
        <TextInput
          style={styles.input}
          onChangeText={onChangeActionId}
          value={actionId}
          placeholder="Action Id"
        />
        <Button title="Verify Action Id" onPress={onVerifyActionId} />
        <Button title="Start" onPress={onStart} />
      </View>
    </SafeAreaView>
  );
}
