'use client';

import { useState, useEffect } from 'react';
import { signIn } from 'next-auth/react';
import { useSearchParams } from 'next/navigation';
import Link from 'next/link';
import { authService, AuthService, RegisterRequest, agentsService, AgentType } from '@/services';
import { resetLogoutState } from '@/services/api';

type UserType = 'USER' | 'AGENT';

interface ValidationError {
  field: string;
  errors: string[];
}

export default function SignUpPage() {
  const searchParams = useSearchParams();
  const [userType, setUserType] = useState<UserType>('USER');
  const [firstName, setFirstName] = useState('');
  const [lastName, setLastName] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [error, setError] = useState('');
  const [fieldErrors, setFieldErrors] = useState<ValidationError[]>([]);
  const [loading, setLoading] = useState(false);
  const [registrationSuccess, setRegistrationSuccess] = useState(false);
  const [agentTypes, setAgentTypes] = useState<AgentType[]>([]);
  const [selectedAgentTypeId, setSelectedAgentTypeId] = useState('');
  const [loadingAgentTypes, setLoadingAgentTypes] = useState(false);

  // Surface errors passed via ?error= (e.g. from social signup callback)
  useEffect(() => {
    const errorParam = searchParams.get('error');
    if (errorParam) {
      setError(decodeURIComponent(errorParam));
    }
  }, [searchParams]);

  // Clear logout flags and fetch agent types on mount
  useEffect(() => {
    localStorage.removeItem('isLoggingOut');
    resetLogoutState();

    const fetchAgentTypes = async () => {
      setLoadingAgentTypes(true);
      try {
        const types = await agentsService.getAgentTypes();
        setAgentTypes(types);
      } catch (err) {
        console.error('Failed to fetch agent types:', err);
      } finally {
        setLoadingAgentTypes(false);
      }
    };
    fetchAgentTypes();
  }, []);

  const getFieldError = (fieldName: string): string | null => {
    const fieldError = fieldErrors.find((e) => e.field === fieldName);
    return fieldError ? fieldError.errors[0] : null;
  };

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

    // Validate agent type if registering as agent
    if (userType === 'AGENT' && !selectedAgentTypeId) {
      setError('Please select an agent type');
      setLoading(false);
      return;
    }

    try {
      const registerData: RegisterRequest = {
        firstName,
        lastName,
        email,
        password,
        role: userType,
        ...(userType === 'AGENT' && selectedAgentTypeId && { agentTypeId: selectedAgentTypeId }),
      };

      await authService.register(registerData);

      // Show success message - user must verify email before logging in
      setRegistrationSuccess(true);
    } catch (err) {
      // Get field errors
      const errors = AuthService.getFieldErrors(err);
      if (errors.length > 0) {
        setFieldErrors(errors);
        setError('Please fix the errors below');
      } else {
        setError(AuthService.getErrorMessage(err));
      }
    } finally {
      setLoading(false);
    }
  };

  const handleSocialLogin = (provider: 'google' | 'facebook' | 'twitter') => {
    // If agent, require agent type selection
    if (userType === 'AGENT' && !selectedAgentTypeId) {
      setError('Please select an agent type before signing up');
      return;
    }
    // Set cookies with mode, role and agent type so server-side auth callback can read them
    document.cookie = `socialAuthMode=signup;path=/;max-age=300;SameSite=Lax`;
    document.cookie = `socialAuthRole=${userType};path=/;max-age=300;SameSite=Lax`;
    if (userType === 'AGENT' && selectedAgentTypeId) {
      document.cookie = `socialAuthAgentTypeId=${selectedAgentTypeId};path=/;max-age=300;SameSite=Lax`;
    }
    signIn(provider, { callbackUrl: '/' });
  };

  // Registration Success Message
  if (registrationSuccess) {
    return (
      <div className="bg-white rounded-[20px] p-8 shadow-sm">
        <div className="text-center">
          <div className="mb-6">
            <svg className="w-16 h-16 mx-auto text-green-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
          </div>
          <h2 className="text-[24px] font-normal text-[#00293d] font-fractul mb-3">Check Your Email</h2>
          <p className="text-[14px] text-[#00293d]/70 font-serif mb-6">
            We've sent a verification link to <strong>{email}</strong>. Please check your inbox and click the link to verify your account before logging in.
          </p>
          <Link
            href="/login"
            className="inline-block w-full py-4 bg-[#e58625] hover:bg-[#d47a1f] text-[#00293d] font-bold text-[14px] font-fractul rounded-[7px] transition-colors text-center"
          >
            Go to Login
          </Link>
          <p className="text-xs text-[#00293d]/50 mt-4">
            Didn't receive the email? Check your spam folder or contact support.
          </p>
        </div>
      </div>
    );
  }

  return (
    <>
      {/* Sign Up Heading */}
      <div className="text-center mb-6">
        <h2 className="text-[30px] font-normal text-[#00293d] font-fractul mb-3">Sign Up</h2>
        <p className="text-[14px] text-[#00293d] px-4 leading-[20px] font-fractul">
          Sign in or create an account to showcase your skills & expertise to millions of people starting their real estate journey today
        </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-medium 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-medium rounded-[15px] transition-all duration-200 font-serif ${
              userType === 'AGENT'
                ? 'bg-[#00293d] text-[#f0f5fc] border border-[#00293d]'
                : 'text-[#00293d]'
            }`}
          >
            Agent
          </button>
        </div>
      </div>

      {/* Sign Up 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}
          </div>
        )}

        {/* First Name & Last Name */}
        <div className="flex gap-4">
          <div className="flex-1">
            <input
              type="text"
              placeholder="First Name"
              value={firstName}
              onChange={(e) => setFirstName(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 ${
                getFieldError('firstName') ? 'ring-2 ring-red-400' : ''
              }`}
            />
            {getFieldError('firstName') && (
              <p className="text-red-500 text-xs mt-1 ml-2">{getFieldError('firstName')}</p>
            )}
          </div>
          <div className="flex-1">
            <input
              type="text"
              placeholder="Last Name"
              value={lastName}
              onChange={(e) => setLastName(e.target.value)}
              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 ${
                getFieldError('lastName') ? 'ring-2 ring-red-400' : ''
              }`}
            />
            {getFieldError('lastName') && (
              <p className="text-red-500 text-xs mt-1 ml-2">{getFieldError('lastName')}</p>
            )}
          </div>
        </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 ${
              getFieldError('email') ? 'ring-2 ring-red-400' : ''
            }`}
          />
          {getFieldError('email') && (
            <p className="text-red-500 text-xs mt-1 ml-2">{getFieldError('email')}</p>
          )}
        </div>

        {/* Password Input */}
        <div>
          <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 ${
                getFieldError('password') ? 'ring-2 ring-red-400' : ''
              }`}
            />
            <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>
          {getFieldError('password') && (
            <p className="text-red-500 text-xs mt-1 ml-2">{getFieldError('password')}</p>
          )}
          <p className="text-[#00293d]/60 text-xs mt-2 ml-2 font-serif">
            Min 8 chars, 1 uppercase, 1 lowercase, 1 number, 1 special character
          </p>
        </div>

        {/* Agent Type Selection - Only for Agents */}
        {userType === 'AGENT' && (
          <div>
            <select
              value={selectedAgentTypeId}
              onChange={(e) => setSelectedAgentTypeId(e.target.value)}
              required
              disabled={loadingAgentTypes}
              className={`w-full px-6 py-6 bg-[#f0f5fc] rounded-[7px] text-[#00293d] text-[14px] font-light font-serif focus:outline-none focus:ring-2 focus:ring-[#00293d]/20 transition-all appearance-none cursor-pointer ${
                !selectedAgentTypeId ? 'text-[#00293d]/60' : ''
              } ${getFieldError('agentTypeId') ? 'ring-2 ring-red-400' : ''}`}
              style={{
                backgroundImage: `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24' stroke='%2300293d'%3E%3Cpath stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='M19 9l-7 7-7-7'/%3E%3C/svg%3E")`,
                backgroundRepeat: 'no-repeat',
                backgroundPosition: 'right 1.5rem center',
                backgroundSize: '1.25rem',
              }}
            >
              <option value="">Select Professional Role</option>
              {agentTypes.map((type) => (
                <option key={type.id} value={type.id}>
                  {type.name}
                </option>
              ))}
            </select>
            {getFieldError('agentTypeId') && (
              <p className="text-red-500 text-xs mt-1 ml-2">{getFieldError('agentTypeId')}</p>
            )}
          </div>
        )}

        {/* Sign Up 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 ? 'Creating Account...' : 'Sign Up'}
        </button>
      </form>

      {/* Already Have Account */}
      <div className="text-center mt-8">
        <span className="text-[#00293d] text-[14px] font-serif">Already Have An Account ? </span>
        <Link href="/login" className="text-[#00293d] font-bold text-[14px] font-fractul hover:underline">
          Login
        </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-[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>
    </>
  );
}
