import { useState, useEffect, useContext } from 'react';
import { Form, Button,Container } from 'react-bootstrap';
import { Navigate } from 'react-router-dom';
import Swal from 'sweetalert2';
import UserContext from '../UserContext';

export default function Login(props) {

	// Allows us to consume the User context object and it's properties to use for user validation
	const { user, setUser } = useContext(UserContext);

	const [email, setEmail] = useState("");
	const [password, setPassword] = useState("");

	const [isActive, setIsActive] = useState(false)

	function authenticate(e){
		e.preventDefault();

		fetch(`${process.env.REACT_APP_API_URL}/users/login`, {
			method: "POST",
			headers: {
				"Content-Type": "application/json"
			},
			body: JSON.stringify({
				email: email,
				password: password
			})
		})
		.then(res => res.json())
		.then(data => {

			console.log(data);

			// If no user information is found, the "access" property will not be available and will return undefined.
			if(typeof data.access !== "undefined"){

				// Set the token of the authenticated user in the local storage
				// Syntax:
					// locaStorage.setItem('propertyName', value)
				localStorage.setItem('token', data.access);

				// Set the global state "user" to the token received from loggin in.
				// setUser({
				// 	token: localStorage.getItem('token')
				// });

				// function for retrieving user details
				retrieveUserDetails(data.access);

				// alert('You are now logged in');
				Swal.fire({
					title: "Login Successful",
					icon: "success",
					text: "Welcome to !"
				})

			} else {
				// alert(`${email} does not exist`);
				Swal.fire({
					title: "Authentication failed",
					icon: "error",
					text: "Check your login details and try again."
				})
			}
		});

		// Clear input fields after submission
		setEmail('');
		setPassword('');

	}

	const retrieveUserDetails = (token) => {

		fetch(`${process.env.REACT_APP_API_URL}/users/userdetail`, {
			headers: {
				Authorization: `Bearer ${token}`
			}
		})
		.then(res => res.json())
		.then(data => {
			console.log(data);

			// Changes the global "user" state to store the "id" and the "isAdmin" properties of the user which will be used for validation across the whole application
			setUser({
				id: data._id,
				isAdmin: data.isAdmin
			})

		})

	}



	useEffect(() => {

		if(email !== "" && password !== ""){
			setIsActive(true)
		} else {
			setIsActive(false)
		}

	}, [email, password]);

	return (
		(user.id !== null) ?
			<Navigate to="/products" />
		:

		<Container className="d-flex justify-content-center align-items-center vh-100 image-my">

			<Form onSubmit={(e) => authenticate(e)}style={{
					    margin: 'auto',
					    maxWidth: '500px',
					    padding: '50px',
					    backgroundImage: `url('./images/wave.jpeg')`, // Specify the path to your image
					    backgroundSize: 'cover',
					    backgroundPosition: 'center',
					    borderRadius: '10px',
					    textAlign: 'center',
					    width: '500px'
					}}>

				<h1 className="my-5 text-center text-opazity">Login</h1>
				<Form.Group controlId="userEmail">
					<Form.Label>Email address</Form.Label>
					<Form.Control 
						type="email" 
						placeholder="Enter email" 
						required
						value={email}
						onChange={(e) => setEmail(e.target.value)}
						className="custom-input mb-3"
						style={{ borderBottom: '1px solid grey', background: 'transparent' }}
					/>
				</Form.Group>

				<Form.Group controlId="password">
					<Form.Label>Password</Form.Label>
					<Form.Control 
						type="password" 
						placeholder="Password" 
						required
						value={password}
						onChange={(e) => setPassword(e.target.value)}
						style={{ marginBottom: '10px' }}
						className="custom-input mb-3"
						style={{ borderBottom: '1px solid grey', background: 'transparent' }}
					/>
				</Form.Group>
				<>
				<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
				{isActive ?
					<Button variant="primary" type="submit" id="submitBtn"
					style={{marginBottom: '10px' }}>
						Submit
					</Button>
					:
					<Button 
					  variant="transparent" 
					  type="submit" 
					  id="submitBtn" 
					  style={{ marginBottom: '10px' }}
					  disabled={user.id !== null} // Disable the button if user is logged in
					>
					  Submit
					</Button>

				}
				<div className="d-flex align-items-center">
				  <p className="m-0">Don't have an account?</p>
				  <Button onClick={() => props.onFormSwitch('register')} className="custom-input mt-0" style={{ background: 'transparent' }}>
				    Register here
				  </Button>
				</div>


				</div>
				</>

			</Form>  
		</Container>     
	)
}