import './css/login.css'
import React, { useState } from 'react';
import { useAppContext } from '../app';
import { flash } from '../toast';
import { Link } from 'react-router-dom';
import Logo from '../components/logo';
import Container from '../components/container';
import Spinner from '../components/spinner';
import Button from '../components/button';

const Login: React.FC<{}> = () => {
    const [submitting, setSubmitting] = useState(false);
    const { request, setState, redirect } = useAppContext() as any;
    const [username, setUsername] = useState('');
    const [password, setPassword] = useState('');
    const [showPassword, setShowPassword] = useState(false);

    const handleTogglePassword = () => setShowPassword(!showPassword);

    const handleSubmit = (event: React.FormEvent) => {
        event.preventDefault();
        if (!username.trim()) {
            flash('Please enter a username');
            return;
        }
        if (!password) {
            flash('Please enter a password');
            return;
        }
        if (!username || !password) {
            flash('Please enter both username and password');
            return;
        }
        setSubmitting(true);
        request('/login', 'POST', { username, password }, false)
            .then((result: { token: string; key: string; iv: string }) => {
                localStorage.setItem('token', JSON.stringify({ token: result.token, key: result.key, iv: result.iv }));
                setState({ token: result.token, key: result.key, iv: result.iv });
                redirect('/');
            })
            .catch((error: any) => {
                flash('An error occurred');
                console.error(error);
            })
            .finally(() => {
                setSubmitting(false);
            });
    };

    return (
        <Container>
            <Logo />
            <h1>Login</h1>
            {submitting ? (
                <Container>
                    <h3>Submitting...</h3>
                    <Spinner />
                </Container>
            ) : (
                <>
                    <form className="login-form gap-2 flex flex-col" onSubmit={handleSubmit}>
                        <div>
                            <label htmlFor="username">Username:</label>
                            <input
                                value={username}
                                onChange={(e) => setUsername(e.target.value)}
                                type="text"
                                id="username"
                                name="username"
                            />
                        </div>
                        <div className="relative">
                            <label htmlFor="password">Password:</label>
                            <input
                                value={password}
                                onChange={(e) => setPassword(e.target.value)}
                                type={showPassword ? "text" : "password"}
                                id="password"
                                name="password"
                            />
                            <button
                                type="button"
                                onClick={handleTogglePassword}
                                className="absolute inset-y-0 right-0 pr-3 flex items-center"
                            >
                                {showPassword ? "Hide" : "Show"}
                            </button>
                        </div>
                        <Button type="submit">Submit</Button>
                    </form>
                    <div className="flex flex-col mt-4 gap-2 items-start justify-start">
                        <Link to="/sign-up">
                            <Button className="strong">Sign up</Button>
                        </Link>
                        <Link to="/reset-password">
                            <Button className="strong">Forgot your password</Button>
                        </Link>
                    </div>
                </>
            )}
        </Container>
    );
}

export default Login;