import { useNavigate } from 'react-router-dom';
import { useState } from 'react';
import { setItem } from '../../../utils/localStorage'
import { appConstants } from '../../../utils/AppConstants';
import Input from '../../Base/Input/Index'
import Button from '../../Base/Button/Index';
import styles from './styles.module.css';

const Login = () => {
    const navigate = useNavigate();
    const [email, setEmail] = useState('');

    const handleSubmit = (e) => {
        e.preventDefault();
        login();
    }


    const login = async () => {
        const response = await fetch(`${appConstants.API_URL_USERS}`)
        const data = await response.json();
        const user = data.find((e) => e.email == email);
        if (user) {
            setItem("user", user.id)
            setItem("modal", true)
            navigate("/")
        } else {
            const response = await fetch(`${appConstants.API_URL_USERS}`, {
                method: "POST",
                body: JSON.stringify({
                    email: email
                })
            })
            const data = await response.json();
            navigate("/")
            setItem("user", data.id)
            setItem("modal", true)
        }
    }

    const onEmailChange = (e) => {
        setEmail(e.target.value)
    }
    return (
        <div className={styles.bg}>
            <section className={styles.container}>
                <div className={styles.contentWrapper}>
                    <div className={styles.title}>Welcome Back!</div>
                    <div className={styles.desc}>Login with email and passoword to book seats.</div>
                </div>
                <form className={styles.formWrapper} onSubmit={handleSubmit}>
                    <Input
                        label="Email"
                        name="email"
                        type="email"
                        placeholder='Enter email'
                        onChange={onEmailChange}
                    />
                    <Button size={"md"}>Confirm</Button>
                </form>
            </section>
        </div>


    )
}

export default Login