'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { signIn } from 'next-auth/react';
import Link from 'next/link';

export default function LoginPage() {
  const router = useRouter();
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);

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

    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 }),
      });

      const validateData = await validateRes.json();

      if (!validateRes.ok) {
        // Show the actual error message from backend
        setError(validateData.message || 'Invalid email or password');
        setLoading(false);
        return;
      }

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

      setLoading(false);

      if (result?.error) {
        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') => {
    signIn(provider, { callbackUrl: '/' });
  };

  return (
    <>
      {/* Login Heading */}
      <div className="text-center mb-6">
        <h2 className="text-[30px] font-normal text-[#00293d] mb-3">Login</h2>
        <p className="text-sm text-[#00293d] px-4 leading-relaxed">
          Sign in to your account to access your real estate dashboard and manage your properties
        </p>
      </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-[20px] text-sm">
            {error}
          </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-[20px] text-[#00293d] text-sm font-light 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-[20px] text-[#00293d] text-sm font-light 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-sm font-light hover:underline">
            Forgot 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-sm rounded-[20px] transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
        >
          {loading ? 'Signing in...' : 'Login'}
        </button>
      </form>

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

      {/* Divider */}
      <div className="flex items-center my-6">
        <div className="flex-1 h-px bg-[#00293d]/20"></div>
        <span className="px-4 text-sm text-[#00293d] font-light">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>

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