import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { motion } from 'framer-motion';
import { useAuthStore } from '../../store/authStore';
import { api } from '../lib/apiClient';
import styles from './LoginPage.module.css';

/**
 * LoginPage
 * Clean, branded login. Email + password → JWT → AuthStore → /command.
 * No "register" link. No "forgot password" noise. Single intent.
 */
export function LoginPage() {
  const navigate = useNavigate();
  const { setSession } = useAuthStore();
  const [email, setEmail]       = useState('');
  const [password, setPassword] = useState('');
  const [error, setError]       = useState('');
  const [loading, setLoading]   = useState(false);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!email || !password) return;
    setLoading(true);
    setError('');

    try {
      const { access_token } = await api.post<{ access_token: string }>(
        '/auth/login',
        { email, password }
      );

      const userProfile = await fetch('/api/auth/me', {
        headers: { Authorization: `Bearer ${access_token}` }
      }).then(r => r.json());

      const user = {
        id: userProfile.user_id,
        name: userProfile.full_name,
        email: userProfile.email,
        role: userProfile.role,
        avatarUrl: userProfile.avatar_url
      };

      setSession(user, access_token);
      navigate('/command', { replace: true });
    } catch (err: any) {
      setError('Invalid credentials. Please try again.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className={styles.root}>
      {/* Ambient gradient background */}
      <div className={styles.bg} aria-hidden />

      <motion.div
        className={`${styles.card} glass-heavy`}
        initial={{ opacity: 0, y: 24, scale: 0.96 }}
        animate={{ opacity: 1, y: 0, scale: 1 }}
        transition={{ duration: 0.45, ease: [0.4, 0, 0.2, 1] }}
      >
        {/* Logomark */}
        <div className={styles.logo}>
          <div className={styles.logoMark}>V</div>
          <span className={styles.logoLabel}>Velocity-OS</span>
        </div>

        <h1 className={styles.title}>Welcome back.</h1>
        <p className={styles.subtitle}>Sign in to your workspace.</p>

        <form className={styles.form} onSubmit={handleSubmit} noValidate>
          <div className={styles.field}>
            <label className={styles.label} htmlFor="email">Email</label>
            <input
              id="email"
              type="email"
              className={styles.input}
              value={email}
              onChange={e => setEmail(e.target.value)}
              placeholder="you@desineuron.in"
              autoComplete="email"
              disabled={loading}
              required
            />
          </div>

          <div className={styles.field}>
            <label className={styles.label} htmlFor="password">Password</label>
            <input
              id="password"
              type="password"
              className={styles.input}
              value={password}
              onChange={e => setPassword(e.target.value)}
              placeholder="••••••••"
              autoComplete="current-password"
              disabled={loading}
              required
            />
          </div>

          {error && (
            <motion.p
              className={styles.error}
              initial={{ opacity: 0, y: -4 }}
              animate={{ opacity: 1, y: 0 }}
            >
              {error}
            </motion.p>
          )}

          <motion.button
            type="submit"
            className={`btn-primary ${styles.submit}`}
            disabled={loading || !email || !password}
            whileTap={{ scale: 0.98 }}
          >
            {loading ? 'Signing in…' : 'Sign In →'}
          </motion.button>
        </form>
      </motion.div>
    </div>
  );
}
