import React, { useState } from "react";
import styles from './Auth.module.scss';
import { ReactComponent as LogoIcon } from '../../assets/icons/anamnesis.svg';
import { ReactComponent as EyeOffIcon } from '../../assets/icons/eye-off-outline.svg';
import { ReactComponent as EyeIcon } from '../../assets/icons/eye-outline.svg';
import { NavLink } from "react-router-dom";
import axios from 'axios';
import { SERVER_URL } from "../../App";
import { authenticateCredentials } from "./Login";


const registerUser = async (name: string, username: string, password: string) => {
    return await axios.post(SERVER_URL + '/auth/register/', {
        name: name,
        email: username,
        password: password
    });
}

const requestVerification = async (email: string) => {
    return await axios.post(SERVER_URL + '/auth/request-verification/', {
        email: email,
    });
}

const verifyUser = async (email: string, otp: string) => {
    return await axios.post(SERVER_URL + '/auth/verify-user/', {
        email: email,
        otp: otp
    });
}


export const Signup: React.FC = () => {
    const [showPassowrd, setShowPassword] = useState<boolean>(true);
    const [fullName, setFullName] = useState<string>('');
    const [userName, setUsername] = useState<string>('');
    const [password, setPassword] = useState<string>('');
    const [otp, setOtp] = useState<string>('');
    const [viewState, setViewState] = useState<'REGISTER' | 'VERIFY'>('REGISTER');

    function register() {
        registerUser(fullName, userName, password).then(() => {
            window.alert("Registered your email, please wait while we redirect you to verify...");

            setTimeout(() => {
                requestVerification(userName).then(() => {
                    setViewState('VERIFY');
                }, () => {
                    window.alert("Couldn't send Verfication request");
                });
            }, 1000);

        }, (e) => {
            window.alert(e.toString());
        });
    }

    function verify() {
        verifyUser(userName, otp).then(() => {
            window.alert("Verified user!, Logging you in....");

            authenticateCredentials(userName, password).then((response: any) => {
                localStorage.anamnesisToken = response.data.token;
                window.location.assign('/home');
            }, () => {
                window.alert("Please check your credentials");
            });

        }, () => window.alert("Failed Verification, please try again"))
    }

    return <section className="page">
        <header className={styles.pageHeader}>
            <LogoIcon />
        </header>

        { viewState === 'REGISTER' && <section className={styles.form}>

            <div className={styles.inputHolder}>
                <input defaultValue={fullName} onInput={(e) => setFullName(e.currentTarget.value)} 
                type="text" placeholder="Full Name" />
            </div>

            <div className={styles.inputHolder}>
                <input defaultValue={userName} onInput={(e) => setUsername(e.currentTarget.value)} 
                type="email" placeholder="Email ID" />
            </div>

            <div className={styles.inputHolder}>
                <input defaultValue={password} onInput={(e) => setPassword(e.currentTarget.value)} 
                type={ showPassowrd ? "text" : "password" } placeholder="Password" />
                <button className={styles.rightButton} onClick={() => setShowPassword(!showPassowrd)}>
                    { showPassowrd ? <EyeOffIcon /> : <EyeIcon /> }
                </button>
            </div>

            <button className={styles.submitButton} onClick={() => register()}>
                Next Step (Verification)
            </button>

            <NavLink className={styles.otherLinks} to="/login"> Login? </NavLink>

        </section> }

        { viewState === 'VERIFY' && <section className={styles.form}>

            <div className={styles.inputHolder}>
                <input defaultValue={otp} onInput={(e) => setOtp(e.currentTarget.value)} 
                type="tel" placeholder="Enter OTP sent to your Mail ID" />
            </div>

            <button className={styles.submitButton} onClick={() => verify()}>
                Verify
            </button>

        </section> }

    </section>
};