'use client';

import React, { useState, FormEvent } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { useAuth } from '@/contexts/AuthContext';

export default function LoginPage() {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState<string | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const { login, isAuthenticated, user } = useAuth();
  const router = useRouter();

  const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    if (!username || !password) {
      setError('用户名和密码不能为空');
      return;
    }

    setIsLoading(true);
    setError(null);

    try {
      await login(username, password);
      // 登录成功后，AuthContext会更新状态，下面useEffect会处理跳转
      // 或者在这里直接根据角色跳转
      // const targetPath = response.data.data.role === 'admin' ? '/admin/dashboard' : '/dashboard';
      // router.push(targetPath);
    } catch (err: any) {
      setError(typeof err === 'string' ? err : '登录时发生错误，请检查凭据或网络连接。');
    } finally {
      setIsLoading(false);
    }
  };

  // 如果用户已认证，则重定向到对应的主页
  React.useEffect(() => {
    if (isAuthenticated && user) {
      const targetPath = user.role === 'admin' ? '/admin/dashboard' : '/dashboard';
      console.log(`User already authenticated (${user.username}, ${user.role}). Redirecting to ${targetPath}...`);
      router.replace(targetPath); // 使用replace避免用户回退到登录页
    }
  }, [isAuthenticated, user, router]);

  // 如果仍在加载认证状态或已经认证通过（等待跳转），可以显示加载中
  // if (isLoadingInitialAuth || isAuthenticated) { 
  //   return <div className="flex justify-center items-center min-h-screen">加载中...</div>;
  // }

  return (
    <div className="flex min-h-screen flex-col items-center justify-center bg-gray-100 p-4">
      <div className="w-full max-w-md rounded-lg bg-white p-8 shadow-md">
        <h1 className="mb-6 text-center text-3xl font-bold text-blue-600">
          MQTT 智能充电桩
        </h1>
        <form onSubmit={handleSubmit} className="space-y-6">
          <div>
            <label
              htmlFor="username"
              className="block text-sm font-medium text-gray-700"
            >
              用户名
            </label>
            <input
              id="username"
              name="username"
              type="text"
              autoComplete="username"
              required
              value={username}
              onChange={(e) => setUsername(e.target.value)}
              className="mt-1 block w-full rounded-md border border-gray-300 px-3 py-2 placeholder-gray-400 shadow-sm focus:border-blue-500 focus:outline-none focus:ring-blue-500 sm:text-sm"
              placeholder="请输入用户名"
            />
          </div>

          <div>
            <label
              htmlFor="password"
              className="block text-sm font-medium text-gray-700"
            >
              密码
            </label>
            <input
              id="password"
              name="password"
              type="password"
              autoComplete="current-password"
              required
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              className="mt-1 block w-full rounded-md border border-gray-300 px-3 py-2 placeholder-gray-400 shadow-sm focus:border-blue-500 focus:outline-none focus:ring-blue-500 sm:text-sm"
              placeholder="请输入密码"
            />
          </div>

          {error && (
            <p className="text-center text-sm text-red-600">{error}</p>
          )}

          <div>
            <button
              type="submit"
              disabled={isLoading}
              className={`flex w-full justify-center rounded-md border border-transparent ${isLoading ? 'bg-blue-300' : 'bg-blue-600 hover:bg-blue-700'} py-2 px-4 text-sm font-medium text-white shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 transition duration-150 ease-in-out`}
            >
              {isLoading ? (
                <svg className="animate-spin -ml-1 mr-3 h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                  <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                  <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                </svg>
              ) : null}
              {isLoading ? '登录中...' : '登 录'}
            </button>
          </div>
        </form>

        <p className="mt-6 text-center text-sm text-gray-600">
          还没有账户？{' '}
          <Link href="/register" className="font-medium text-blue-600 hover:text-blue-500">
            立即注册
          </Link>
        </p>
      </div>
    </div>
  );
} 