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('');

  const [selectedPlugins, setSelectedPlugins] = React.useState<string[]>([]);

  const togglePlugin = (name: string, isChecked: boolean) => {
    setSelectedPlugins((prev) => {
      const next = new Set(prev);
      if (isChecked) next.add(name);
      else next.delete(name);
      return Array.from(next);
    });
  };
  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({
    container: {
      paddingHorizontal: 16,
      paddingBottom: 16,
      paddingTop: 64,
    },
    input: {
      height: 40,
      margin: 12,
      borderWidth: 1,
      padding: 10,
    },
    btn: { marginVertical: 8 },
  });

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

  const onCreateMetaPlugin = () => {
    createMetaPlugin(URL, USERNAME, API_KEY, [CERT_BASE64], 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 style={styles.container}>
      <StatusBar />
      <View>
        <View>
          <View>
            <BouncyCheckbox
              isChecked={selectedPlugins.includes('AutoIdOnServer')}
              onPress={(isChecked: boolean) =>
                togglePlugin('AutoIdOnServer', isChecked)
              }
            />
            <Text>AutoIdOnServer</Text>
          </View>
          <View>
            <BouncyCheckbox
              isChecked={selectedPlugins.includes('PayOnServer')}
              onPress={(isChecked: boolean) =>
                togglePlugin('PayOnServer', isChecked)
              }
            />
            <Text>PayOnServer</Text>
          </View>
          <View>
            <BouncyCheckbox
              isChecked={selectedPlugins.includes('VideoId')}
              onPress={(isChecked: boolean) =>
                togglePlugin('VideoId', isChecked)
              }
            />
            <Text>VideoId</Text>
          </View>
          <View>
            <BouncyCheckbox
              isChecked={selectedPlugins.includes('EIdOnServer')}
              onPress={(isChecked: boolean) =>
                togglePlugin('EIdOnServer', isChecked)
              }
            />
            <Text>EIdOnServer</Text>
          </View>
        </View>

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