'use client';

import { useState } from 'react';
import Link from 'next/link';
import Image from 'next/image';
import { useRouter } from 'next/navigation';
import { toast } from '@/components/common';
import { useAppDispatch } from '@/store/redux/hooks';
import { setCredentials } from '@/store/redux/slices/authSlice';
import { isValidEmail, isValidPassword } from '@/utils/validators';
import apiClient from '@/infrastructure/api/client';
import { API_ENDPOINTS } from '@/infrastructure/api/endpoints';
import styles from './login.module.scss';

/**
 * 登录页面组件
 * 基于 UIPro Figma 设计实现
 */
export default function LoginPage() {
  const router = useRouter();
  const dispatch = useAppDispatch();
  const [loading, setLoading] = useState(false);
  const [formData, setFormData] = useState({
    email: '',
    password: '',
  });
  const [errors, setErrors] = useState({
    email: '',
    password: '',
  });

  // 表单验证
  const validateForm = (): boolean => {
    const newErrors = {
      email: '',
      password: '',
    };

    if (!formData.email) {
      newErrors.email = '请输入邮箱';
    } else if (!isValidEmail(formData.email)) {
      newErrors.email = '请输入有效的邮箱地址';
    }

    if (!formData.password) {
      newErrors.password = '请输入密码';
    } else if (!isValidPassword(formData.password)) {
      newErrors.password = '密码长度应为6-20位';
    }

    setErrors(newErrors);
    return !newErrors.email && !newErrors.password;
  };

  // 表单提交处理
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!validateForm()) return;

    setLoading(true);

    const apiUrl = `${process.env.NEXT_PUBLIC_API_BASE_URL}${API_ENDPOINTS.AUTH.LOGIN}`;
    console.log('[Login] 开始登录请求');
    console.log('[Login] API URL:', apiUrl);
    console.log('[Login] 请求数据:', { email: formData.email, password: '***' });

    try {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      const response: any = await apiClient.post(API_ENDPOINTS.AUTH.LOGIN, {
        email: formData.email,
        password: formData.password,
      });

      console.log('[Login] 登录响应:', response);

      // 后端返回格式: { userId, email, nickname, role, accessToken, refreshToken }
      const data = response.data || response;
      const { userId, email, nickname, role, accessToken, refreshToken } = data;

      if (!accessToken) {
        console.error('[Login] 响应中没有 accessToken:', response);
        throw new Error('登录响应缺少 token');
      }

      dispatch(
        setCredentials({
          user: {
            id: userId,
            email: email,
            username: email.split('@')[0],
            nickname: nickname || '管理员',
            avatar: '',
            role: role || 'super_admin',
            status: 'active',
            createdAt: new Date().toISOString(),
            lastLoginAt: new Date().toISOString(),
          },
          token: accessToken,
          refreshToken: refreshToken,
          permissions: ['*'],
        })
      );

      console.log('[Login] 登录成功，跳转到 /dashboard');
      toast.success('登录成功');
      router.push('/dashboard');
    } catch (error: unknown) {
      console.error('[Login] 登录失败:', error);

      // 详细记录错误信息
      if (error && typeof error === 'object' && 'response' in error) {
        const axiosError = error as { response?: { status?: number; data?: unknown }; message?: string };
        console.error('[Login] 错误状态码:', axiosError.response?.status);
        console.error('[Login] 错误响应:', axiosError.response?.data);
        console.error('[Login] 错误消息:', axiosError.message);

        const errorMessage =
          (axiosError.response?.data as { message?: string })?.message ||
          axiosError.message ||
          '登录失败，请检查账号密码';
        toast.error(errorMessage);
      } else {
        toast.error('登录失败，请检查网络连接');
      }
    } finally {
      setLoading(false);
    }
  };

  // 输入变更处理
  const handleInputChange = (field: 'email' | 'password') => (
    e: React.ChangeEvent<HTMLInputElement>
  ) => {
    setFormData((prev) => ({ ...prev, [field]: e.target.value }));
    if (errors[field]) {
      setErrors((prev) => ({ ...prev, [field]: '' }));
    }
  };

  return (
    <div className={styles.login}>
      {/* 品牌 Logo 区域 */}
      <div className={styles.login__header}>
        <div className={styles.login__logo}>
          <Image
            src="/images/Container.svg"
            width={36}
            height={44}
            alt="RWADurian Logo"
            priority
          />
        </div>
        <h3 className={styles.login__brandName}>榴莲认种管理后台</h3>
      </div>

      {/* 登录表单卡片 */}
      <section className={styles.login__card}>
        <div className={styles.login__titleWrapper}>
          <h1 className={styles.login__title}>欢迎回来</h1>
        </div>

        <form className={styles.login__form} onSubmit={handleSubmit}>
          {/* 输入框组 */}
          <div className={styles.login__inputGroup}>
            {/* 邮箱输入字段 */}
            <div className={styles.login__fieldWrapper}>
              <div
                className={`${styles.login__inputWrapper} ${
                  errors.email ? styles['login__inputWrapper--error'] : ''
                }`}
              >
                <input
                  className={styles.login__input}
                  placeholder="电子邮件"
                  type="email"
                  value={formData.email}
                  onChange={handleInputChange('email')}
                  aria-label="电子邮件"
                  autoComplete="email"
                />
              </div>
              {errors.email && (
                <span className={styles.login__error}>{errors.email}</span>
              )}
            </div>

            {/* 密码输入字段 */}
            <div className={styles.login__fieldWrapper}>
              <div
                className={`${styles.login__inputWrapper} ${
                  errors.password ? styles['login__inputWrapper--error'] : ''
                }`}
              >
                <input
                  className={styles.login__input}
                  placeholder="密码"
                  type="password"
                  value={formData.password}
                  onChange={handleInputChange('password')}
                  aria-label="密码"
                  autoComplete="current-password"
                />
              </div>
              {errors.password && (
                <span className={styles.login__error}>{errors.password}</span>
              )}
            </div>
          </div>

          {/* 忘记密码链接 */}
          <div className={styles.login__options}>
            <Link href="/forgot-password" className={styles.login__link}>
              忘记密码？
            </Link>
          </div>

          {/* 登录按钮 */}
          <button
            className={styles.login__button}
            type="submit"
            disabled={loading}
            aria-label="登录"
          >
            {loading && <span className={styles.login__spinner} />}
            <b className={styles.login__buttonText}>
              {loading ? '登录中...' : '登录'}
            </b>
          </button>
        </form>

      </section>
    </div>
  );
}
