import React, { useContext, useState } from 'react';
import validator from 'validator';
import './LoginScreen.css';
import { useNavigate } from 'react-router-dom';
import { ROLES, SERVER_URL } from '../../constants.js';
import { fetchData } from '../../fetching/Fetch.js';
import { UserContext } from '../../context/UserContext.jsx';
import { clearSession, setSession } from '../../utils/session.js';

const ADMIN_ROLES = [ROLES.ROLE_SUPER_ADMIN, ROLES.ROLE_BRANCH_ADMIN];

function hasAdminAccess(userData) {
    const roles = Array.isArray(userData?.roles) ? userData.roles : [];
    return roles.some((role) => ADMIN_ROLES.includes(role));
}

export default function LoginScreen() {
    const navigate = useNavigate();
    const { setUser } = useContext(UserContext);

    const [username, setUsername] = useState('');
    const [password, setPassword] = useState('');
    const [error, setError] = useState('');

    const handleSubmit = async (event) => {
        event.preventDefault();

        if (!username.trim()) {
            setError('Username is required');
            return;
        }

        if (!validator.isEmail(username) && !validator.isMobilePhone(username, 'any')) {
            setError('Invalid username format. Please enter a valid email or phone number.');
            return;
        }

        if (!password.trim()) {
            setError('Password is required.');
            return;
        }

        try {
            const url = `${SERVER_URL}/api/v1/auth/login`;
            const { data, success } = await fetchData(url, 'POST', {
                email: username,
                password: password
            });

            if (!success || !data) {
                setError('Your credentials are incorrect.');
                return;
            }

            const userData = data.userData ?? data;
            const token = data.token;

            if (!hasAdminAccess(userData)) {
                clearSession();
                setUser(null);
                setError(
                    'This account is a regular user (ROLE_USER) and cannot access the admin app. Create an admin via Manage administrators.'
                );
                return;
            }

            if (!token) {
                setSession({ userData, isTfa: true });
                setUser(userData);
                navigate('/loginauth', { replace: true });
                return;
            }

            if (!userData?.tenantCode) {
                setError('Login succeeded but tenant information is missing.');
                return;
            }

            setSession({
                userData,
                token,
                isTfa: false,
            });
            setUser(userData);
            navigate(`/${userData.tenantCode}/home`, { replace: true });
        } catch (error) {
            console.error('Error:', error);
            setError('An error occurred. Please try again.');
        }
    };

    const handleUsernameChange = (event) => {
        setUsername(event.target.value);
        setError('');
    };

    const handlePasswordChange = (event) => {
        setPassword(event.target.value);
        setError('');
    };

    return (
        <div id="login-form">
            <h1>LOGIN</h1>
            <form onSubmit={handleSubmit}>
                <div className="form-group">
                    <label htmlFor="username">Email or phone number:</label>
                    <input
                        type="text"
                        id="username"
                        name="username"
                        value={username}
                        onChange={handleUsernameChange}
                    />
                    {error && !error.includes('Password') && <p className="error">{error}</p>}
                </div>
                <div className="form-group">
                    <label htmlFor="password">Password:</label>
                    <input
                        type="password"
                        id="password"
                        name="password"
                        value={password}
                        onChange={handlePasswordChange}
                    />
                    {error && error.includes('Password') && <p className="error">{error}</p>}
                </div>
                <input type="submit" value="Submit" />
                <div style={{
                    display: 'flex',
                    justifyContent: 'center'
                }}>
                </div>
            </form>
        </div>
    );
};
