// LoginView.tsx
import React, {useEffect, useState} from 'react';
import { useNavigate } from 'react-router-dom';
import {AuthService, OpenAPI} from '../../openapi'; // Adjust import path

const containerStyle = {
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
    height: '100vh',
    background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
};

const cardStyle = {
    padding: '50px',
    width: '350px',
    backgroundColor: '#fff',
    boxShadow: '0 15px 30px rgba(0, 0, 0, 0.1)',
    borderRadius: '8px',
    textAlign: 'center' as const,
    animation: 'fadeIn 1s ease-in-out',
};

const inputStyle = {
    width: '100%',
    padding: '15px',
    margin: '10px 0',
    borderRadius: '30px',
    border: '1px solid #ddd',
    fontSize: '16px',
    transition: 'border-color 0.3s ease',
};

const buttonStyle = {
    width: '100%',
    padding: '15px',
    margin: '20px 0',
    borderRadius: '30px',
    backgroundColor: '#764ba2',
    color: '#fff',
    border: 'none',
    fontSize: '16px',
    cursor: 'pointer',
    transition: 'background 0.3s ease',
};

const errorStyle = {
    color: 'red',
    marginTop: '20px',
    fontWeight: 'bold',
};

const LoginView: React.FC = () => {
    const [username, setUsername] = useState('');
    const [password, setPassword] = useState('');
    const [error, setError] = useState('');
    const navigate = useNavigate();

    useEffect(() => {
        // Detect the current environment
        const mode = import.meta.env.MODE;

        // Dynamically set `OpenAPI.BASE` based on the mode
        OpenAPI.BASE =
            mode === 'test'
                ? import.meta.env.VITE_OPENAPI_BASE_TEST
                : mode === 'prod'
                    ? import.meta.env.VITE_OPENAPI_BASE_PROD
                    : import.meta.env.VITE_OPENAPI_BASE_DEV;

        // Log warning if `OpenAPI.BASE` is unresolved
        if (!OpenAPI.BASE) {
            console.error('OpenAPI.BASE is not set. Falling back to a default value.');
            OpenAPI.BASE = 'https://default-url.com'; // Use a consistent fallback
        }

        // Debug for mode and resolved `BASE`
        console.log('Environment Mode:', mode);
        console.log('Resolved OpenAPI.BASE:', OpenAPI.BASE);
    }, []);

    const handleLogin = async (e: React.FormEvent) => {
        e.preventDefault();

        try {
            const response = await AuthService.loginAuthTokenLoginPost({
                grant_type: 'password',
                username: username,
                password: password,
            });

            // Save the token
            localStorage.setItem('token', response.access_token);
            OpenAPI.TOKEN = response.access_token;

            // Decode token to extract user data (e.g., pgroups)
            const decodedToken = JSON.parse(atob(response.access_token.split('.')[1])); // Decode JWT payload
            const userData = {
                username: decodedToken.sub,
                pgroups: decodedToken.pgroups || [], // Ensure pgroups is an array
            };
            localStorage.setItem('user', JSON.stringify(userData)); // Save user data in localStorage

            console.log("Token updated successfully:", response.access_token);
            console.log("User data saved:", userData);

            navigate('/'); // Redirect after successful login
        } catch (err) {
            setError('Login failed. Please check your credentials.');
            console.error("Error during login:", err);
        }
    };

    return (
        <div style={containerStyle}>
            <form style={cardStyle} onSubmit={handleLogin}>
                <h2>Welcome Back!</h2>
                <input
                    style={{
                        ...inputStyle,
                        borderColor: username ? '#764ba2' : '#ddd',
                    }}
                    type="text"
                    placeholder="Username"
                    value={username}
                    onChange={(e) => setUsername(e.target.value)}
                    required
                />
                <input
                    style={{
                        ...inputStyle,
                        borderColor: password ? '#764ba2' : '#ddd',
                    }}
                    type="password"
                    placeholder="Password"
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    required
                />
                <button
                    style={{
                        ...buttonStyle,
                        backgroundColor: '#764ba2',
                    }}
                    type="submit"
                    onMouseOver={(e) =>
                        (e.currentTarget.style.backgroundColor = '#6a3a89')
                    }
                    onMouseOut={(e) =>
                        (e.currentTarget.style.backgroundColor = '#764ba2')
                    }
                >
                    Login
                </button>
                {error && <p style={errorStyle}>{error}</p>}
            </form>
        </div>
    );
};

export default LoginView;