import React, { useEffect, useRef, useState } from 'react';
import { Text, View, StyleSheet, Image } from 'react-native';
import { TextInput, Button, HelperText } from 'react-native-paper';
import API from './../API.js';
import { useNavigation, useRoute } from '@react-navigation/native';
import i18n from "../i18nMessages.js";


let LoginForm = () => {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const [tries, setTries] = useState(0);
  const [tokenLinkSending, setTokenLinkSending] = useState(false);
  const [tokenLoginLoading, setTokenLoginLoading] = useState(false);
  const [tokenLoginError, setTokenLoginError] = useState('');
  const navigation = useNavigation();
  const route = useRoute();
  const handledTokenRef = useRef('');
  const resetPasswordBol = tries > 2;

  const resetPassword = async () => {
    await API.resetPassword(email);
    alert("We sent you instructions to your email!")
  }

  const loginCall = async () => {
    let r = await API.logIn(email.trim(), password);
    if (r.status === "ok") return navigation.reset({
      index: 0,
      routes: [{ name: 'MainNavigation' }],
    });
    //console.log(r)
    setError(r.status);
    if (r.status === 'incorrect password') {
      if (resetPasswordBol) {
        await resetPassword();
        setTries(0);
      } else {
        setTries(tries + 1);
      }
    } else {
      setTries(0);
    }
    //alert(i18n.t('message.wrongInformation'))
  };

  const requestOneTimeLink = async () => {
    if (!email.trim()) return;
    setTokenLinkSending(true);
    setTokenLoginError('');
    try {
      await API.resetPassword(email.trim());
      alert("If this account exists, we sent a one-time sign-in link to your email.");
    } finally {
      setTokenLinkSending(false);
    }
  };

  useEffect(() => {
    const token = typeof route?.params?.token === "string" ? route.params.token.trim() : "";
    if (!token) return;
    if (handledTokenRef.current === token) return;
    handledTokenRef.current = token;
    let cancelled = false;
    const consumeToken = async () => {
      setTokenLoginLoading(true);
      setTokenLoginError('');
      const r = await API.logInWithPasswordToken(token);
      if (cancelled) return;
      setTokenLoginLoading(false);
      if (r?.status === "ok") {
        return navigation.reset({
          index: 0,
          routes: [{ name: 'MainNavigation' }],
        });
      }
      setTokenLoginError(r?.status || "Invalid or expired token");
    };
    consumeToken();
    return () => {
      cancelled = true;
    };
  }, [route?.params?.token]);

  return (
    <View style={styles.mainView}>
      <TextInput
        style={styles.input}
        onChangeText={text => setEmail(text)}
        defaultValue={email}
        placeholder={i18n.t("message.email")}
        label={i18n.t("message.email")}
        autoCapitalize='none'
        autoComplete='email'
        autoCorrect={false}
        mode="outlined"
        keyboardType='email-address'
      />
      {error !== '' && error !== 'incorrect password' ? <HelperText type="error" visible={true}>
        {i18n.t("message.invalidEmail")}
      </HelperText> : <></>}
      <TextInput
        style={styles.input}
        onChangeText={text => setPassword(text)}
        defaultValue={password}
        placeholder={i18n.t("message.password")}
        textContentType="password"
        label={i18n.t("message.password")}
        secureTextEntry={true}
        autoCapitalize='none'
        autoComplete='email'
        autoCorrect={false}
        mode="outlined"
      />
      {error === 'incorrect password' ? <HelperText type="error" visible={true}>
        {i18n.t("message.reviewPassword")}
      </HelperText> : <></>}
      {tokenLoginLoading ? <HelperText type="info" visible={true}>
        Signing you in from email link...
      </HelperText> : <></>}
      {tokenLoginError ? <HelperText type="error" visible={true}>
        {tokenLoginError}
      </HelperText> : <></>}
      <View style={{ flexDirection: "row" }}>
        <Button
          style={styles.button}
          onPress={async () => {
            await loginCall();
          }}
        >
          {resetPasswordBol ? i18n.t("message.resetPassword") : i18n.t("message.submit")}
        </Button>
        {
          resetPasswordBol ? <Button
            style={styles.button}
            onPress={async () => {
              setTries(0);
            }}
          >
            {i18n.t("message.cancel")}
          </Button> : <></>
        }
      </View>
      <Button
        style={styles.button}
        disabled={!email.trim() || tokenLinkSending}
        onPress={requestOneTimeLink}
      >
        {tokenLinkSending ? "Sending..." : "Email me a one-time sign-in link"}
      </Button>
    </View>
  );
}

export default LoginForm;

const styles = StyleSheet.create({
  mainView: {
    width: "100%",
    alignContent: 'center',
    alignItems: 'center',
  },
  input: {
    backgroundColor: 'white',
    width: "80%"
  },
  button: {
    marginTop: 10,

  }
});
