import React, { useState } from 'react';
import { ScrollView, View, Alert } from 'react-native';
import { Button, Text, TextInput } from 'react-native-paper';

import { NativeStackScreenProps } from '@react-navigation/native-stack';

import { StackParamsList } from '../types';
import { signMessage } from '../utils';

type SignProps = NativeStackScreenProps<StackParamsList, 'SignMessage'>;

const SignMessage = ({ route }: SignProps) => {
  const network = route.params?.selectedNetwork;
  const account = route.params?.accountInfo;

  const [message, setMessage] = useState<string>('');

  const signMessageHandler = async () => {
    if (network) {
      if (!account){
        throw new Error("Account is not valid");
      }
      const signedMessage = await signMessage(message, network, account.id);
      Alert.alert('Signature', signedMessage);
    }
  };

  return (
    <ScrollView style={{ marginTop: 24, paddingHorizontal: 24 }}>
      <View style={{ marginTop: 24, marginBottom: 30 }}>
        <Text variant="bodyLarge">
          <Text style={{ fontWeight: '700' }}>Address: </Text>
          {account && account.address}
        </Text>
        <Text variant="bodyLarge">
          <Text style={{ fontWeight: '700' }}>Public Key: </Text>
          {account && account.pubKey}
        </Text>
      </View>
      <TextInput
        mode="outlined"
        placeholder="Enter your message"
        onChangeText={text => setMessage(text)}
        value={message}
      />
      <View style={{ marginTop: 20, width: 150, alignSelf: 'center' }}>
        <Button mode="contained" onPress={signMessageHandler}>
          Sign
        </Button>
      </View>
    </ScrollView>
  );
};

export default SignMessage;
