'use client';

import { useState, useEffect } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { signIn } from 'next-auth/react';
import Link from 'next/link';
import { resetLogoutState } from '@/services/api';

export default function LoginPage() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);
  const [userType, setUserType] = useState<'USER' | 'AGENT'>('USER');
  const [showResendVerification, setShowResendVerification] = useState(false);
  const [resendingVerification, setResendingVerification] = useState(false);
  const [resendSuccess, setResendSuccess] = useState('');

  // Clear logout flags on mount so API calls aren't blocked after redirect from logout
  useEffect(() => {
    localStorage.removeItem('isLoggingOut');
    resetLogoutState();
    // Show error from social login redirect
    const errorParam = searchParams.get('error');
    if (errorParam) {
      setError(errorParam);
    }
  }, [searchParams]);

  const handleResendVerification = async () => {
    if (!email) {
      setError('Please enter your email first');
      return;
    }
    setResendingVerification(true);
    setResendSuccess('');
    try {
      const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/auth/resend-verification-public`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email }),
      });
      const data = await res.json();
      if (res.ok) {
        setResendSuccess(data?.data?.message || 'Verification email sent. Please check your inbox.');
        setError('');
        setShowResendVerification(false);
      } else {
        setError(data?.message || 'Failed to resend verification email');
      }
    } catch {
      setError('Failed to resend verification email');
    } finally {
      setResendingVerification(false);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setError('');
    setResendSuccess('');
    setShowResendVerification(false);

    // Clear logout flags now that user is actively logging in
    localStorage.removeItem('isLoggingOut');
    resetLogoutState();

    try {
      // First, validate credentials with backend to get proper error messages
      const validateRes = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/auth/login`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, password, loginRole: userType }),
      });

      const validateData = await validateRes.json();

      if (!validateRes.ok) {
        const msg = validateData.message || 'Invalid email or password';
        setError(msg);
        // If error is about email verification, show resend button
        if (msg.toLowerCase().includes('verify your email') || msg.toLowerCase().includes('not verified')) {
          setShowResendVerification(true);
        }
        setLoading(false);
        return;
      }

      // Check if 2FA is required (response is wrapped in { success, data })
      if (validateData.data?.requiresTwoFactor) {
        // Redirect to 2FA verification page with tempToken
        const params = new URLSearchParams({
          token: validateData.data.tempToken,
          email: email,
        });
        router.push(`/login/verify-2fa?${params.toString()}`);
        return;
      }

      // Save tokens to localStorage BEFORE signIn to prevent race condition
      // (dashboard components may call API before TokenSync has synced from session)
      if (validateData.data?.accessToken) {
        localStorage.setItem('accessToken', validateData.data.accessToken);
        localStorage.setItem('refreshToken', validateData.data.refreshToken);
      }

      // If validation passed, use NextAuth to create session
      const result = await signIn('credentials', {
        email,
        password,
        redirect: false,
      });

      setLoading(false);

      if (result?.error) {
        // Login failed - clear the tokens we just saved
        localStorage.removeItem('accessToken');
        localStorage.removeItem('refreshToken');
        setError('Login failed. Please try again.');
      } else {
        router.push('/');
        router.refresh();
      }
    } catch (err) {
      setLoading(false);
      setError('An error occurred. Please try again.');
    }
  };

  const handleSocialLogin = (provider: 'google' | 'facebook' | 'twitter') => {
    // Set login mode so backend rejects if user doesn't exist
    document.cookie = `socialAuthMode=login;path=/;max-age=300;SameSite=Lax`;
    signIn(provider, { callbackUrl: '/' });
  };

  return (
    <>
      {/* Login Heading */}
      <div className="text-center mb-6">
        <h2 className="text-[30px] font-normal text-[#00293d] font-fractul mb-3">Login</h2>
        <p className="text-[14px] text-[#00293d] px-4 leading-[20px] font-fractul">
          Login or create an account
        </p>
      </div>

      {/* User Type Toggle */}
      <div className="flex justify-center mb-8">
        <div className="inline-flex bg-[#f0f5fc] rounded-[15px] p-0.5">
          <button
            type="button"
            onClick={() => setUserType('USER')}
            className={`px-10 py-2 text-[14px] font-semibold rounded-[15px] transition-all duration-200 font-serif ${
              userType === 'USER'
                ? 'bg-[#00293d] text-[#f0f5fc] border border-[#00293d]'
                : 'text-[#00293d]'
            }`}
          >
            User
          </button>
          <button
            type="button"
            onClick={() => setUserType('AGENT')}
            className={`px-10 py-2 text-[14px] font-semibold rounded-[15px] transition-all duration-200 font-serif ${
              userType === 'AGENT'
                ? 'bg-[#00293d] text-[#f0f5fc] border border-[#00293d]'
                : 'text-[#00293d]'
            }`}
          >
            Agent
          </button>
        </div>
      </div>

      {/* Login Form */}
      <form onSubmit={handleSubmit} className="space-y-5">
        {error && (
          <div className="bg-red-50 border border-red-200 text-red-600 px-4 py-3 rounded-[7px] text-[14px] font-serif">
            {error}
            {showResendVerification && (
              <button
                type="button"
                onClick={handleResendVerification}
                disabled={resendingVerification}
                className="block mt-2 text-[#e58625] hover:text-[#d47720] underline font-medium disabled:opacity-50"
              >
                {resendingVerification ? 'Sending...' : 'Resend verification email'}
              </button>
            )}
          </div>
        )}
        {resendSuccess && (
          <div className="bg-green-50 border border-green-200 text-green-700 px-4 py-3 rounded-[7px] text-[14px] font-serif">
            {resendSuccess}
          </div>
        )}

        {/* Email Input */}
        <div>
          <input
            type="email"
            placeholder="Email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            required
            className="w-full px-6 py-6 bg-[#f0f5fc] rounded-[7px] text-[#00293d] text-[14px] font-light font-serif placeholder:text-[#00293d] focus:outline-none focus:ring-2 focus:ring-[#00293d]/20 transition-all"
          />
        </div>

        {/* Password Input */}
        <div className="relative">
          <input
            type={showPassword ? 'text' : 'password'}
            placeholder="Password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            required
            className="w-full px-6 py-6 bg-[#f0f5fc] rounded-[7px] text-[#00293d] text-[14px] font-light font-serif placeholder:text-[#00293d] focus:outline-none focus:ring-2 focus:ring-[#00293d]/20 transition-all pr-14"
          />
          <button
            type="button"
            onClick={() => setShowPassword(!showPassword)}
            className="absolute right-5 top-1/2 -translate-y-1/2 text-[#00293d]/60 hover:text-[#00293d] transition-colors"
          >
            {showPassword ? (
              <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
              </svg>
            ) : (
              <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21" />
              </svg>
            )}
          </button>
        </div>

        {/* Forgot Password Link */}
        <div className="text-right">
          <Link href="/forgot-password" className="text-[#00293d] text-[14px] font-light font-serif leading-[24px] hover:underline">
            Forgot Your Password?
          </Link>
        </div>

        {/* Login Button */}
        <button
          type="submit"
          disabled={loading}
          className="w-full py-6 bg-[#e58625] hover:bg-[#d47a1f] text-[#00293d] font-bold text-[20px] font-fractul rounded-[7px] transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
        >
          {loading ? 'Signing in...' : 'Login'}
        </button>
      </form>

      {/* Divider */}
      <div className="flex items-center my-6">
        <div className="flex-1 h-px bg-[#00293d]/20"></div>
        <span className="px-4 text-[14px] text-[#00293d] font-serif">Or</span>
        <div className="flex-1 h-px bg-[#00293d]/20"></div>
      </div>

      {/* Social Login Icons */}
      <div className="flex justify-center items-center gap-8">
        {/* Google */}
        <button
          type="button"
          onClick={() => handleSocialLogin('google')}
          className="w-10 h-10 flex items-center justify-center hover:opacity-70 transition-opacity"
        >
          <img src="/assets/icons/google.svg" alt="Google" className="w-6 h-6" />
        </button>

        {/* X (Twitter) */}
        <button
          type="button"
          onClick={() => handleSocialLogin('twitter')}
          className="w-10 h-10 flex items-center justify-center hover:opacity-70 transition-opacity"
        >
          <img src="/assets/icons/x.svg" alt="X" className="w-6 h-6" />
        </button>
      </div>

      {/* Don't Have Account */}
      <div className="text-center mt-8">
        <span className="text-[#00293d] text-[14px] font-serif">Don&apos;t Have An Account ? </span>
        <Link href="/signup" className="text-[#00293d] font-bold text-[14px] font-fractul hover:underline">
          Sign Up
        </Link>
      </div>
    </>
  );
}
