import { useState } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import { useAuth } from '../context/AuthContext';
import Logo from '../components/Logo';

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 { user } = await login(email, password);
      navigate(user.onboarding_complete ? '/' : '/onboarding');
    } catch (err) {
      setError(err.message);
    }
    setLoading(false);
  };

  return (
    <div className="auth-page">
      <div className="auth-card">
        <Logo />
        <h1 className="auth-title">Logga in</h1>
        <p className="auth-tagline">Din personliga träningspartner</p>
        {error && <div className="error auth-error">{error}</div>}
        <form onSubmit={handleSubmit}>
          <input type="email" placeholder="E-post" value={email} onChange={e => setEmail(e.target.value)} required />
          <input type="password" placeholder="Lösenord" value={password} onChange={e => setPassword(e.target.value)} required />
          <button type="submit" disabled={loading}>{loading ? 'Loggar in...' : 'Logga in'}</button>
        </form>
        <p className="auth-link">Inget konto? <Link to="/register">Skapa konto</Link></p>
      </div>
    </div>
  );
}
