import React, { useState } from 'react';
import { GoogleLogin } from '@react-oauth/google';
import { jwtDecode } from 'jwt-decode';
import ThalosTokenConnector from '../auth/ThalosTokenConnector';
import { useAuth } from '../context/AuthContext';
import { Box, Paper, Typography } from '@mui/material';
import { useNavigate } from 'react-router-dom';

export default function LoginPage() {
    const [googleIdToken, setGoogleIdToken] = useState(null);
    const [googleProfile, setGoogleProfile] = useState(null);
    const { login } = useAuth();
    const navigate = useNavigate();

    return (
        <Box display="flex" justifyContent="center" alignItems="center" height="100vh">
            <Paper sx={{ p: 4, borderRadius: 2, boxShadow: 3, textAlign: 'center' }}>

                <Box mb={2}>
                    <Typography variant="h5" mb={2}>Login</Typography>
                    <img
                        src="/Logo.png"
                        alt="Dream Views"
                        style={{ width: '200px', height: 'auto' }}
                    />
                </Box>
                <GoogleLogin
                    onSuccess={(cred) => {
                        const idToken = cred?.credential;
                        if (!idToken) return;

                        const decoded = jwtDecode(idToken);
                        setGoogleIdToken(idToken);
                        setGoogleProfile({
                            name: decoded?.name || '',
                            email: decoded?.email || '',
                            picture: decoded?.picture || '',
                        });
                    }}
                    onError={() => console.error('Google login failed')}
                />

                {googleIdToken && (
                    <ThalosTokenConnector
                        googleIdToken={googleIdToken}
                        onSuccess={(payload) => {
                            login({
                                ...googleProfile,
                                idToken: googleIdToken,
                                thalosToken: payload?.token || '',
                            });
                            navigate('/', { replace: true });
                        }}
                        onError={(err) => {
                            console.error('Thalos exchange failed:', err);
                            localStorage.removeItem('thalosToken');
                        }}
                    />
                )}

                <Box mt={4}>
                    <p>By</p>
                    <img
                        src="https://imaageq.com/images/Imaageq%20black-no%20slogan.webp"
                        alt="ImaageQ"
                        style={{ width: '72px', height: 'auto', opacity: 0.8 }}
                    />
                </Box>
            </Paper>
        </Box>
    );
}
