'use client';

import React, { useState, FormEvent } from 'react';
import { useRouter } from 'next/navigation';
import Image from 'next/image';
import { useAuth } from '@/lib/auth-context';

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

  // 已登录则跳转
  if (isAuthenticated) {
    router.replace('/dashboard');
    return null;
  }

  const handleSubmit = async (e: FormEvent) => {
    e.preventDefault();
    setError('');
    setLoading(true);
    try {
      await login(email, password);
      router.replace('/dashboard');
    } catch (err: unknown) {
      const msg =
        (err as { response?: { data?: { message?: string } } })?.response?.data
          ?.message || '登录失败，请检查账号密码';
      setError(msg);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={styles.wrapper}>
      <div style={styles.card}>
        <div style={styles.logoRow}>
          <Image src="/logo.svg" alt="Genex" width={40} height={40} />
          <span style={styles.brand}>Genex Admin</span>
        </div>
        <h1 style={styles.title}>管理后台登录</h1>

        <form onSubmit={handleSubmit} style={styles.form}>
          <label style={styles.label}>邮箱 / 手机号</label>
          <input
            style={styles.input}
            type="text"
            placeholder="admin@gogenex.com"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            required
            autoFocus
          />

          <label style={styles.label}>密码</label>
          <input
            style={styles.input}
            type="password"
            placeholder="请输入密码"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            required
          />

          {error && <p style={styles.error}>{error}</p>}

          <button type="submit" style={styles.btn} disabled={loading}>
            {loading ? '登录中...' : '登录'}
          </button>
        </form>

        <p style={styles.footer}>Genex 管理后台 &copy; 2025</p>
      </div>
    </div>
  );
}

/* ---------- inline styles (no extra CSS file) ---------- */
const styles: Record<string, React.CSSProperties> = {
  wrapper: {
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
    minHeight: '100vh',
    background: 'linear-gradient(135deg, #F3F1FF 0%, #E8E5FF 50%, #F8F9FC 100%)',
  },
  card: {
    width: 400,
    padding: '40px 36px',
    borderRadius: 16,
    background: '#fff',
    boxShadow: '0 8px 32px rgba(108,92,231,0.10)',
  },
  logoRow: {
    display: 'flex',
    alignItems: 'center',
    gap: 10,
    marginBottom: 8,
  },
  brand: {
    fontSize: 20,
    fontWeight: 700,
    color: '#6C5CE7',
  },
  title: {
    fontSize: 24,
    fontWeight: 600,
    color: '#262B3A',
    margin: '16px 0 28px',
  },
  form: {
    display: 'flex',
    flexDirection: 'column' as const,
    gap: 12,
  },
  label: {
    fontSize: 14,
    fontWeight: 500,
    color: '#5C6478',
  },
  input: {
    padding: '10px 14px',
    fontSize: 15,
    border: '1px solid #E4E7F0',
    borderRadius: 8,
    outline: 'none',
    transition: 'border-color 0.2s',
  },
  error: {
    fontSize: 13,
    color: '#FF4757',
    margin: 0,
  },
  btn: {
    marginTop: 8,
    padding: '12px 0',
    fontSize: 16,
    fontWeight: 600,
    color: '#fff',
    background: '#6C5CE7',
    border: 'none',
    borderRadius: 8,
    cursor: 'pointer',
    transition: 'opacity 0.2s',
  },
  footer: {
    textAlign: 'center' as const,
    marginTop: 28,
    fontSize: 12,
    color: '#A0A8BE',
  },
};
