'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 RegisterPage() {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [checkPassword, setCheckPassword] = useState('');
  const [error, setError] = useState<string | null>(null);
  const [successMessage, setSuccessMessage] = useState<string | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const { register } = useAuth();
  const router = useRouter();

  const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    if (!username || !password || !checkPassword) {
      setError('所有字段均为必填项');
      setSuccessMessage(null);
      return;
    }
    if (password !== checkPassword) {
      setError('两次输入的密码不一致');
      setSuccessMessage(null);
      return;
    }
    // 可选：添加更复杂的密码策略校验
    if (password.length < 6) {
        setError('密码长度不能少于6位');
        setSuccessMessage(null);
        return;
    }

    setIsLoading(true);
    setError(null);
    setSuccessMessage(null);

    try {
      await register(username, password, checkPassword);
      setSuccessMessage('注册成功！正在跳转到登录页面...');
      // 注册成功后延迟跳转到登录页
      setTimeout(() => {
        router.push('/login');
      }, 2000); // 延迟2秒
    } catch (err: any) {
      setError(typeof err === 'string' ? err : '注册时发生错误，请稍后重试或联系管理员。');
    } finally {
      setIsLoading(false);
    }
  };

  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">
          创建新账户
        </h1>
        <form onSubmit={handleSubmit} className="space-y-4">
          <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="new-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="请输入至少6位密码"
            />
          </div>
          
          <div>
            <label
              htmlFor="checkPassword"
              className="block text-sm font-medium text-gray-700"
            >
              确认密码
            </label>
            <input
              id="checkPassword"
              name="checkPassword"
              type="password"
              autoComplete="new-password"
              required
              value={checkPassword}
              onChange={(e) => setCheckPassword(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>
          )}
          {successMessage && (
            <p className="text-center text-sm text-green-600">{successMessage}</p>
          )}

          <div>
            <button
              type="submit"
              disabled={isLoading || !!successMessage} // 成功后也禁用按钮
              className={`flex w-full justify-center rounded-md border border-transparent ${isLoading || successMessage ? 'bg-blue-300 cursor-not-allowed' : '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 mt-2`}
            >
              {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="/login" className="font-medium text-blue-600 hover:text-blue-500">
            返回登录
          </Link>
        </p>
      </div>
    </div>
  );
} 