import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import bgImage from '../../media/bg_image.jpeg';
import { useAuth } from '../../hooks/useAuth';

export default function Login() {
    const [formData, setFormData] = useState({ email: '', password: '' });
    const [error, setError] = useState('');
    const [isLoading, setIsLoading] = useState(false);
    const [passwordVisible, setPasswordVisible] = useState(false);
    const navigate = useNavigate();
    const { login } = useAuth();

    const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const { name, value } = e.target;
        setFormData(prev => ({ ...prev, [name]: value }));
    };

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        setError('');
        setIsLoading(true);

        try {
            const response = await fetch(`${import.meta.env.VITE_BACKEND_URL}/api/login`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(formData),
            });

            let data: any;
            let text: string;
            try {
                text = await response.text();
                data = JSON.parse(text);
            } catch (jsonErr) {
                // If the response is not JSON, show a generic error
                throw new Error('Unexpected server response. Please try again later.');
            }

            if (!response.ok) throw new Error(data.error || 'Login failed');
            if (!data.token) throw new Error('Authentication token missing');

            login(
                data.token,
                {
                    id: data.user.id,
                    email: data.user.email,
                    name: data.profile?.name || '',
                    isAdmin: data.user.is_admin
                },
                data.profile || {}
            );

            navigate('/navigation');
        } catch (err) {
            const message = err instanceof Error ? err.message : 'Login failed';
            setError(message);
            console.error('Login error:', err);
        } finally {
            setIsLoading(false);
        }
    };

    return (
        <div
            className="login-container"
            style={{
                backgroundImage: `url(${bgImage})`,
                minHeight: '100vh',
                backgroundSize: 'cover',
                backgroundPosition: 'center',
                display: 'flex',
                justifyContent: 'center',
                alignItems: 'center',
                padding: '20px'
            }}
        >
            <div
                className="login-card"
                style={{
                    backgroundColor: 'rgba(255, 255, 255, 0.9)',
                    borderRadius: '12px',
                    padding: '2rem',
                    width: '100%',
                    maxWidth: '400px',
                    boxShadow: '0 4px 20px rgba(0, 0, 0, 0.1)'
                }}
            >
                <div
                    className="login-header"
                    style={{
                        textAlign: 'center',
                        marginBottom: '2rem'
                    }}
                >
                    <i
                        className="bi bi-person-circle"
                        style={{
                            fontSize: '3rem',
                            color: '#4a6bff'
                        }}
                    ></i>
                    <h4 style={{ marginTop: '0.5rem', fontWeight: '600' }}>
                        LOGIN<span className="text-warning">#</span>
                    </h4>
                </div>

                {error && (
                    <div
                        className="alert alert-danger"
                        style={{
                            marginBottom: '1.5rem',
                            padding: '0.75rem',
                            borderRadius: '8px'
                        }}
                    >
                        {error}
                    </div>
                )}

                <form onSubmit={handleSubmit}>
                    <div
                        className="mb-3 formFieldsEmail"
                        style={{ marginBottom: '1.5rem' }}
                    >
                        <label
                            htmlFor="email"
                            className="form-label"
                            style={{
                                display: 'block',
                                marginBottom: '0.5rem',
                                fontWeight: '500'
                            }}
                        >
                            Email
                        </label>
                        <input
                            id="email"
                            name="email"
                            type="email"
                            className="form-control"
                            placeholder="Enter your email"
                            value={formData.email}
                            onChange={handleChange}
                            required
                            style={{
                                width: '100%',
                                padding: '0.75rem',
                                borderRadius: '8px',
                                border: '1px solid #ddd',
                                fontSize: '1rem',
                                boxSizing: 'border-box'
                            }}
                            autoComplete="email"
                            inputMode="email"
                        />
                    </div>

                    <div
                        className="mb-4 formFields"
                        style={{ marginBottom: '1.5rem', position: 'relative' }}
                    >
                        <label
                            htmlFor="password"
                            className="form-label"
                            style={{
                                display: 'block',
                                marginBottom: '0.5rem',
                                fontWeight: '500'
                            }}
                        >
                            Password
                        </label>
                        <input
                            id="password"
                            name="password"
                            type={passwordVisible ? 'text' : 'password'}
                            className="form-control"
                            placeholder="Enter your password"
                            value={formData.password}
                            onChange={handleChange}
                            required
                            style={{
                                width: '100%',
                                padding: '0.75rem',
                                borderRadius: '8px',
                                border: '1px solid #ddd',
                                fontSize: '1rem',
                                boxSizing: 'border-box',
                                paddingRight: '40px'
                            }}
                            autoComplete="current-password"
                        />
                        <button
                            type="button"
                            onClick={() => setPasswordVisible(!passwordVisible)}
                            style={{
                                position: 'absolute',
                                right: '10px',
                                top: '38px',
                                background: 'transparent',
                                border: 'none',
                                cursor: 'pointer',
                                color: '#666'
                            }}
                            aria-label={passwordVisible ? 'Hide password' : 'Show password'}
                        >
                            <i className={`bi ${passwordVisible ? 'bi-eye-slash' : 'bi-eye'}`}></i>
                        </button>
                    </div>

                    <button
                        type="submit"
                        className="btn btn-login w-100"
                        disabled={isLoading}
                        style={{
                            width: '100%',
                            padding: '0.75rem',
                            borderRadius: '8px',
                            backgroundColor: '#4a6bff',
                            color: 'white',
                            border: 'none',
                            fontSize: '1rem',
                            fontWeight: '500',
                            cursor: 'pointer',
                            transition: 'background-color 0.2s',
                            marginTop: '0.5rem'
                        }}
                        onMouseOver={(e) => e.currentTarget.style.backgroundColor = '#3a5bef'}
                        onMouseOut={(e) => e.currentTarget.style.backgroundColor = '#4a6bff'}
                    >
                        {isLoading ? (
                            <>
                                <span
                                    className="spinner-border spinner-border-sm"
                                    role="status"
                                    aria-hidden="true"
                                    style={{ marginRight: '8px' }}
                                ></span>
                                Logging in...
                            </>
                        ) : 'ENTER'}
                    </button>
                </form>

                
            </div>
        </div>
    );
}