import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useAuth } from '../context/AuthContext'
import LetterGlitch from '../components/LetterGlitch'

export default function LoginPage() {
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')
  const [error, setError] = useState('')
  const [loading, setLoading] = useState(false)
  
  const { login } = useAuth()
  const navigate = useNavigate()

  const handleSubmit = async (e) => {
    e.preventDefault()
    setError('')
    setLoading(true)

    try {
      const result = await login(email, password)
      
      if (result.success) {
        navigate('/tickets')
      } else {
        // Bessere Fehlermeldungen
        let errorMessage = result.error || 'Login fehlgeschlagen'
        
        if (errorMessage.includes('Invalid credentials') || errorMessage.includes('401')) {
          errorMessage = 'Ungültige Email oder Passwort. Bitte überprüfe deine Eingaben.'
        } else if (errorMessage.includes('Email/Password') || errorMessage.includes('auth')) {
          errorMessage = 'Email/Password Authentifizierung ist möglicherweise nicht aktiviert. Bitte überprüfe deine Appwrite-Konfiguration.'
        }
        
        setError(errorMessage)
      }
    } catch (err) {
      setError('Ein unerwarteter Fehler ist aufgetreten: ' + (err.message || 'Unbekannter Fehler'))
    } finally {
      setLoading(false)
    }
  }

  return (
    <div style={{ 
      position: 'relative',
      minHeight: '100vh', 
      width: '100%',
      overflow: 'hidden'
    }}>
      {/* LetterGlitch Hintergrund */}
      <div style={{ 
        position: 'absolute',
        top: 0,
        left: 0,
        width: '100%',
        height: '100%',
        zIndex: 0
      }}>
        <LetterGlitch
          glitchSpeed={50}
          centerVignette={true}
          outerVignette={false}
          smooth={true}
        />
      </div>

      {/* Login-Formular */}
      <div style={{ 
        position: 'relative',
        zIndex: 1,
        minHeight: '100vh', 
        display: 'flex', 
        alignItems: 'center', 
        justifyContent: 'center'
      }}>
        <div style={{ 
          width: '400px', 
          boxShadow: '0 10px 40px rgba(0,0,0,0.5)',
          backdropFilter: 'blur(10px)',
          WebkitBackdropFilter: 'blur(10px)',
          background: 'transparent',
          border: '1px solid rgba(255, 255, 255, 0.2)',
          borderRadius: '8px',
          marginBottom: '16px'
        }}>
          <div style={{ 
            padding: '12px 16px',
            background: 'transparent',
            color: '#fff',
            fontWeight: 'bold',
            borderBottom: '1px solid rgba(255, 255, 255, 0.2)',
            textAlign: 'center'
          }}>
            <h2>Webklar WOMS 2.0</h2>
          </div>
          <div style={{ padding: '16px', color: '#e2e8f0' }}>
            <form onSubmit={handleSubmit}>
              {error && (
                <div className="bg-red text-white p-1 mb-2" style={{ borderRadius: '4px' }}>
                  {error}
                </div>
              )}

              <div className="form-group">
                <label className="form-label">Email</label>
                <input
                  type="email"
                  className="form-control"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  required
                  placeholder="deine@email.com"
                />
              </div>

              <div className="form-group">
                <label className="form-label">Password</label>
                <input
                  type="password"
                  className="form-control"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  required
                  placeholder="••••••••"
                  minLength={8}
                />
              </div>

              <button 
                type="submit" 
                className="btn btn-green"
                style={{ width: '100%' }}
                disabled={loading}
              >
                {loading ? 'Login läuft...' : 'Login'}
              </button>
            </form>
          </div>
        </div>
      </div>
    </div>
  )
}
