import { ExternalLink, User } from '@tamagui/lucide-icons'
import React, {useState} from 'react'
import {Button, Anchor,H1, H6, Input, Paragraph, XStack, YStack } from 'tamagui'
import { ToastControl } from 'app/CurrentToast'
import {useAuth, register} from "./../contexts/authcontext"
import { useRouter } from 'expo-router'
import {showToast} from "./../components/toastwrapper"
import { base64ToBigInt, bigIntToBase64, generatePrivateKey, calculatePublicKey, computeSharedSecret, generateNonce, chacha20Encrypt, chacha20Decrypt } from "./../components/crypto";
import {initializeDatabase, addClient,getClient, closeDatabase} from "./../components/dbconnector"


export default function Register() {
    const [username, setUsername] = useState("")
    const [password, setpassword] = useState("")
    const [email, setemail] = useState("")
    const [err, seterr] = useState("")
    const [showpassword, setshowpassword] = useState(false)
    const router = useRouter()
    const {isloggedin } = useAuth()

    const handleLogin = async () => {
      seterr('');
      console.log(email, username, password);
      const clientPrivKey = generatePrivateKey();
      const clientPubKey = calculatePublicKey(clientPrivKey);
      

      try {
        const loginSuccess = await register(email, username, password, bigIntToBase64(clientPubKey));
        if (loginSuccess) 
          {
            let storedPrivateKeys =JSON.parse(localStorage.getItem("Keys")) || []
            const existingUser = storedPrivateKeys.find(user => user.username === username);
            if (existingUser) {
              console.error("User already exists");
              return;
            }
            const private64 = bigIntToBase64(clientPrivKey)
            const public64 = bigIntToBase64(clientPubKey)
            storedPrivateKeys.push({username,private64,public64})
            localStorage.setItem("privateKeys", JSON.stringify(storedPrivateKeys))
            // Initialize the database and add the client
            //await initializeDatabase();
            //await addClient(username, clientPubKey, clientPrivKey);
            //closeDatabase();
            showToast("success", "successfully registered", "go to the login page and login")
            setTimeout(() => {
            router.replace("/login")
          }, 3000)
        }else {
          setUsername("")
          setpassword("")
          setemail("")
        }
        
      } catch (err) {
        console.error(err);
        seterr('An error occurred while logging in');
      }
    };

  return (
    <YStack f={1} ai="center" gap="$2" px="$10" pt="$5" bg="$background">
      <H1 pt="5%" fontSize={45}>Register</H1>
        <XStack px="$1" py="$2">
            <H6 fontSize={15}>
                Username
            </H6>
        </XStack>

        <XStack ai="center"  px="$1" pb="$8" style={{color:"white"}} bg=""  >
            <Input bg="white" color={'black'}
            placeholder='Username'
            value={username}
            onChangeText={setUsername}
            ></Input>


        </XStack>
        <XStack px="$1" py="$2">
            <H6 px="$1">
                Email
            </H6>
        </XStack>

        <XStack ai="center"  px="$1" pb="$1" style={{color:"white"}} bg=""  >
            <Input bg="white" color={'black'}
            placeholder='Email'
            value={email}
            onChangeText={setemail}
            ></Input>
        </XStack>
        <XStack>
            <Paragraph>Password</Paragraph>
        </XStack>
        <XStack>
        <Input px="$4" bg="white" color={"black"}
            placeholder='Password'
            value ={password}
            onChangeText={setpassword}
            secureTextEntry = {!showpassword}

            ></Input>
            <Button
            marginTop={12}
          size="$1"
          bg="white"
          color={'black'}
          onPress={() => setshowpassword((prev) => !prev)}
        >{showpassword ? "hide":"show"}</Button>
        </XStack>
        <XStack>
            <Button onPress={handleLogin}>Login</Button>
        </XStack>

        <XStack>
            <Anchor hoverStyle={{color:"red"}} href='/forgot'>Forgot password?</Anchor>
        </XStack>

        

      <XStack ai="center" jc="center" fw="wrap" gap="$1.5" pos="absolute" b="$2">
        <Paragraph fos="$5">Add</Paragraph>

        <Paragraph fos="$1" px="$2" py="$1" col="$blue10" bg="$blue5">
          tamagui.config.ts
        </Paragraph>

        <Paragraph fos="$5">to root and follow the</Paragraph>

        <XStack
          ai="center"
          gap="$1.5"
          px="$2"
          py="$1"
          br="$3"
          bg="$purple5"
          hoverStyle={{ bg: '$purple6' }}
          pressStyle={{ bg: '$purple4' }}
        >
          <Anchor
            href="https://tamagui.dev/docs/core/configuration"
            textDecorationLine="none"
            col="$purple10"
            fos="$5"
          >
            Configuration guide
          </Anchor>
          <ExternalLink size="$1" col="$purple10" />
        </XStack>

        <Paragraph fos="$5" ta="center">
          to configure your themes and tokens.
        </Paragraph>
      </XStack>
    </YStack>
  )
}
