import { useRef, useState, useEffect } from 'react'
import { Container, Grid, Card, Typography, TextField, Button, InputAdornment } from '@mui/material'
import { FaUserCircle, FaLock, FaUser } from 'react-icons/fa'
import classe from '../assets/Login.module.css'
import { useAuthContext } from '../contexts/AuthContext'
import { Link, useNavigate } from 'react-router-dom'
import { ValidationLogin, invalidCredential } from './validation/Login'

const Login = () => {
  const { token, setToken, setUser, isAuthenticated, isLoading } = useAuthContext()
  const navigate = useNavigate()

  const [username, setUsername] = useState('')
  const [password, setPassword] = useState('')
  const [isSubmitting, setIsSubmitting] = useState(false)

  const userNameRef = useRef()
  const passwordRef = useRef()
  const userNameError = useRef()
  const passwordError = useRef()

  // Redirection si déjà authentifié
  useEffect(() => {
    if (!isLoading && isAuthenticated) {
      console.log('Utilisateur déjà authentifié, redirection vers home')
      navigate('/', { replace: true })
    }
  }, [isAuthenticated, isLoading, navigate])

  const formLogin = async (e) => {
    e.preventDefault()
    
    if (isSubmitting) return
    setIsSubmitting(true)

    try {
      const validate = ValidationLogin(
        userNameRef.current,
        passwordRef.current,
        userNameError.current,
        passwordError.current
      )

      if (!validate) {
        setIsSubmitting(false)
        return
      }

      console.log('Tentative de connexion pour:', username)
      
      const response = await window.allUser.login({ username, password })
      console.log('Réponse login:', response)

      if (response.success) {
        // Extraire le token et les données utilisateur
        const userData = response.user
        // Essayer plusieurs sources pour le token
        const userToken = response.user.token || response.token || response.user.access_token || response.access_token

        console.log('Connexion réussie:', { userData, userToken })
        console.log('Structure complète de response:', response)

        if (!userToken) {
          console.error('Aucun token trouvé dans la réponse!')
          // Générer un token temporaire ou utiliser l'ID utilisateur
          const tempToken = `temp_token_${userData.id}_${Date.now()}`
          console.log('Utilisation d\'un token temporaire:', tempToken)
          setUser(userData)
          setToken(tempToken)
        } else {
          // Sauvegarder les données
          setUser(userData)
          setToken(userToken)
        }

        console.log('Redirection vers home...')
        // Forcer la redirection avec un délai
        setTimeout(() => {
          navigate('/', { replace: true })
        }, 100)
        
      } else {
        console.error('Échec de la connexion:', response.error)
        invalidCredential(userNameError.current, response.error || 'Erreur de connexion')
      }
    } catch (error) {
      console.error('Erreur login :', error)
      invalidCredential(userNameError.current, 'Erreur de connexion')
    } finally {
      setIsSubmitting(false)
    }
  }

  // Afficher un loader pendant la vérification initiale
  if (isLoading) {
    return (
      <Container
        maxWidth={false}
        sx={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center' }}
      >
        <Typography>Chargement...</Typography>
      </Container>
    )
  }

  // Ne pas afficher le formulaire si déjà authentifié
  if (isAuthenticated) {
    return null
  }

  return (
    <Container
      maxWidth={false}
      sx={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center' }}
      className={classe.container}
    >
      <Grid container justifyContent="center">
        <Grid item xs={12} md={6} lg={4}>
          <Card className={`p-4 shadow ${classe.cards}`} sx={{ padding: 4, boxShadow: 3 }}>
            <div style={{ textAlign: 'center', marginBottom: '1rem' }}>
              <FaUserCircle size={60} color="dark" className="text-light" />
            </div>
            <Typography variant="h5" align="center" className="text-light" gutterBottom>
              Université de Toamasina
            </Typography>
            <form onSubmit={formLogin} className={classe.formulaireLogin}>
              <TextField
                label="Nom d'utilisateur"
                color="secondary"
                variant="outlined"
                fullWidth
                placeholder="Nom d'utilisateur"
                margin="normal"
                value={username}
                disabled={isSubmitting}
                InputProps={{
                  startAdornment: (
                    <InputAdornment position="start">
                      <FaUser style={{ color: 'white' }} />
                    </InputAdornment>
                  )
                }}
                className={classe.input}
                onChange={(e) => setUsername(e.target.value)}
                inputRef={userNameRef}
                sx={{
                  '& .MuiOutlinedInput-root': {
                    '& fieldset': { borderColor: 'white' },
                    '&:hover fieldset': { borderColor: 'rgb(156, 39, 176)' }
                  }
                }}
              />
              <span className="text-danger" ref={userNameError}></span>

              <TextField
                label="Mot de passe"
                color="secondary"
                variant="outlined"
                type="password"
                fullWidth
                placeholder="Mot de passe"
                margin="normal"
                value={password}
                disabled={isSubmitting}
                className={classe.input}
                InputProps={{
                  startAdornment: (
                    <InputAdornment position="start">
                      <FaLock style={{ color: 'white' }} />
                    </InputAdornment>
                  )
                }}
                onChange={(e) => setPassword(e.target.value)}
                inputRef={passwordRef}
                sx={{
                  '& .MuiOutlinedInput-root': {
                    '& fieldset': { borderColor: 'white' },
                    '&:hover fieldset': { borderColor: 'rgb(156, 39, 176)' }
                  }
                }}
              />
              <span ref={passwordError} className="text-danger"></span>

              <Button 
                variant="contained" 
                color="secondary" 
                type="submit" 
                fullWidth 
                disabled={isSubmitting}
                sx={{ mt: 2 }}
              >
                {isSubmitting ? 'Connexion...' : 'Se connecter'}
              </Button>

              <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: '1rem' }}>
                <Link to="/forgotpassword" className="text-light">
                  Mot de passe oublié ?
                </Link>
              </div>
            </form>
          </Card>
        </Grid>
      </Grid>
    </Container>
  )
}

export default Login