'use client';

import { useState, useCallback, useEffect } from 'react';
import './style/login.css';
import VantaHaloBackground from '@/components/vanta-halo-background';
import { useRouter, useSearchParams } from 'next/navigation';
import React from 'react';
import Link from 'next/link';
import { signInWithGoogle, loginUser } from '@/lib/auth';

export default function Login() {
  const [isLoaded, setIsLoaded] = useState(false);
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [formError, setFormError] = useState('');
  const [successMessage, setSuccessMessage] = useState('');
  const router = useRouter();
  const searchParams = useSearchParams();

  // Check for registered=true parameter
  useEffect(() => {
    const registered = searchParams?.get('registered');
    if (registered === 'true') {
      setSuccessMessage('注册成功！请使用您的新帐号登录。');
    }
    
    const error = searchParams?.get('error');
    if (error) {
      if (error === 'google_oauth') {
        setFormError('Google登录失败，请重试。');
      } else if (error === 'auth_failed') {
        setFormError('身份验证失败，请重试。');
      }
    }
  }, [searchParams]);

  const handleBackgroundLoaded = useCallback(() => {
    setIsLoaded(true);
  }, []);

  const handleGoogleSignIn = () => {
    signInWithGoogle();
  };

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setIsSubmitting(true);
    setFormError('');
    setSuccessMessage('');
    
    try {
      await loginUser(email, password);
      // 登录成功后跳转到首页
      router.push('/');
    } catch (error: any) {
      console.error('Login failed:', error);
      
      // 根据错误类型显示不同的错误消息
      if (error.message) {
        setFormError(error.message);
      } else if (error.msg) {
        setFormError(error.msg);
      } else {
        setFormError('登录失败，请检查您的凭据后重试。');
      }
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <div className="main-container login-page relative">
      {/* logo Movie Flow */}
      <div className='login-logo'>
        <span className="logo-heart">Movie Flow</span>
      </div>

      <div className="left-panel">
        <VantaHaloBackground onLoaded={handleBackgroundLoaded} />
      </div>
      <div className={`right-panel ${isLoaded ? 'fade-in' : 'invisible'}`}>
        <div className="auth-container">
          <div className="auth-header">
            <h2>登录</h2>
            <p>输入您的凭据以访问您的账户</p>
          </div>

          <form onSubmit={handleSubmit} className="">
            {successMessage && (
              <div className="bg-green-500/20 text-green-300 p-3 mb-4 rounded-lg border border-green-500/20">
                {successMessage}
              </div>
            )}
            
            <div className="mb-3">
              <label className="form-label">用户名</label>
              <input 
                placeholder="请输入用户名" 
                required 
                className="form-control" 
                type="text" 
                value={email}
                onChange={(e) => setEmail(e.target.value)}
              />
            </div>
            <div className="mb-3">
              <label className="form-label">密码</label>
              <input 
                placeholder="请输入密码" 
                required 
                className="form-control" 
                type="password" 
                value={password}
                onChange={(e) => setPassword(e.target.value)}
              />
              <div className="d-flex justify-content-end mt-1">
                <a className="auth-link small" href="/forgot-password" data-discover="true">忘记密码？</a>
              </div>
            </div>
            
            {formError && (
              <div className="bg-red-500/20 text-red-300 p-3 mb-4 rounded-lg border border-red-500/20">
                {formError}
              </div>
            )}
            
            <button 
              type="submit" 
              className="w-full mt-4 btn btn-primary"
              disabled={isSubmitting}
            >
              {isSubmitting ? '登录中...' : '登录'}
            </button>
            
            <div className="my-4 relative flex items-center">
              <div className="flex-grow border-t border-gray-500/30"></div>
              <span className="flex-shrink mx-4 text-gray-400">或</span>
              <div className="flex-grow border-t border-gray-500/30"></div>
            </div>
            
            <button 
              type="button"
              onClick={handleGoogleSignIn}
              className="w-full flex items-center justify-center gap-2 py-3 border border-white/20 rounded-lg bg-black/30 hover:bg-black/50 backdrop-blur-sm transition-all"
            >
              <img src="https://www.gstatic.com/firebasejs/ui/2.0.0/images/auth/google.svg" className="w-5 h-5" alt="Google" />
              <span>Continue with Google</span>
            </button>
            
            <div className="text-center mt-3">
              <p style={{ color: "rgba(255, 255, 255, 0.6)" }}>
                还没有账户？ <Link href="/signup" className="auth-link">注册</Link>
              </p>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
}