'use client';

import { useState, useEffect, Suspense } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import Link from 'next/link';
import { useAuth } from '@/lib/auth';

// Separate component for message handling to isolate useSearchParams
function MessageHandler({ setMessage }: { setMessage: (message: { type: string, content: string }) => void }) {
  const searchParams = useSearchParams();
  
  useEffect(() => {
    const messageParam = searchParams.get('message');
    if (messageParam) {
      setMessage({ type: 'info', content: messageParam });
    }
  }, [searchParams, setMessage]);
  
  return null;
}

export default function LoginPage() {
  const router = useRouter();
  const { signIn, user } = useAuth();
  
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [message, setMessage] = useState({ type: '', content: '' });
  
  // 如果用户已登录，重定向到首页
  useEffect(() => {
    if (user) {
      router.push('/');
    }
  }, [user, router]);
  
  const handleEmailSignIn = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!email || !password) {
      setMessage({ 
        type: 'error', 
        content: 'Please enter both email and password' 
      });
      return;
    }
    
    try {
      setIsLoading(true);
      setMessage({ type: '', content: '' });
      
      const { error } = await signIn(email, password);
      
      if (error) {
        throw new Error(error.message);
      }
      
      // 登录成功后，会通过 useEffect 重定向
    } catch (error) {
      console.error('Login error:', error);
      setMessage({ 
        type: 'error', 
        content: error instanceof Error ? error.message : 'Failed to sign in' 
      });
      setIsLoading(false);
    }
  };
  
  return (
    <div className="flex items-center justify-center min-h-screen bg-gray-100">
      {/* Wrap the component using useSearchParams in Suspense */}
      <Suspense fallback={null}>
        <MessageHandler setMessage={setMessage} />
      </Suspense>
      
      <div className="w-full max-w-md p-8 space-y-8 bg-white rounded-lg shadow-md">
        <div className="text-center">
          <h1 className="text-2xl font-bold text-gray-900">Login</h1>
          <p className="mt-2 text-sm text-gray-600">
            Sign in to your account to access analytics
          </p>
          <div className="mt-2 text-xs text-gray-500">
            Welcome to ShortURL Analytics
          </div>
        </div>
        
        {/* Message display */}
        {message.content && (
          <div className={`p-4 mb-4 text-sm rounded-lg ${
            message.type === 'error' 
              ? 'text-red-700 bg-red-100 border border-red-200'
              : 'text-blue-700 bg-blue-50 border border-blue-200'
          }`}>
            {message.type === 'error' ? (
              <span className="font-medium">Error: </span>
            ) : (
              <span className="font-medium">Notice: </span>
            )}
            {message.content}
          </div>
        )}
        
        <form onSubmit={handleEmailSignIn} className="mt-8 space-y-6">
          <div>
            <label htmlFor="email" className="block text-sm font-medium text-gray-700">
              Email address
            </label>
            <input
              id="email"
              name="email"
              type="email"
              autoComplete="email"
              required
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm placeholder-gray-400 focus:outline-none focus:ring-blue-500 focus:border-blue-500"
              placeholder="your@email.com"
              disabled={isLoading}
            />
          </div>
          
          <div>
            <label htmlFor="password" className="block text-sm font-medium text-gray-700">
              Password
            </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 px-3 py-2 border border-gray-300 rounded-md shadow-sm placeholder-gray-400 focus:outline-none focus:ring-blue-500 focus:border-blue-500"
              placeholder="••••••••"
              disabled={isLoading}
            />
          </div>
          
          <div>
            <button
              type="submit"
              disabled={isLoading}
              className="w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
            >
              {isLoading ? 'Signing in...' : 'Sign in'}
            </button>
          </div>
        </form>
        
        <p className="text-sm mt-6 text-gray-600">
          Don&apos;t have an account?{' '}
          <Link href="/register" className="font-medium text-blue-600 hover:text-blue-500">
            Register
          </Link>
        </p>
      </div>
    </div>
  );
} 