import React, { useState, useEffect, useRef } from "react";
import { useNavigate, useLocation } from "react-router-dom";
import "../../assets/css/login.css";
import { LoginEnvironment } from "./LoginEnviornment";

/**
 * Register Component - Handles user registration
 * Provides a multi-step registration process with:
 * 1. Email verification with captcha
 * 2. OTP verification
 * 3. Full registration form
 * 
 * Features include:
 * - Email validation and verification
 * - Captcha generation and validation
 * - OTP sending and verification
 * - Form validation
 * - API integration
 */
const Register = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const captchaRef = useRef(null);
  
  // State for form fields
  const [first_name, setfirst_name] = useState("");
  const [last_name, setlast_name] = useState("");
  const [email, setEmail] = useState("");
  const [mob_no, setmob_no] = useState("");
  const [date_of_birth, setdate_of_birth] = useState("");
  const [gender, setGender] = useState("");
  const [new_password, setPassword] = useState("");
  const [confirm_password, setConfirmPassword] = useState("");
  const [agreeTerms, setAgreeTerms] = useState(false);
  const [error, setError] = useState("");
  const [successMessage, setSuccessMessage] = useState("");

  // State for multi-step registration
  const [isEmailChecking, setIsEmailChecking] = useState(false);
  const [isVerifyingOtp, setIsVerifyingOtp] = useState(false);
  const [captchaValue, setCaptchaValue] = useState("");
  const [userCaptchaInput, setUserCaptchaInput] = useState("");
  const [isCaptchaValid, setIsCaptchaValid] = useState(false);
  const [otp, setOtp] = useState("");
  const [registrationStep, setRegistrationStep] = useState("verification"); // verification, otp, registration
  const [isApiAvailable, setIsApiAvailable] = useState(true);
  const [isSubmitting, setIsSubmitting] = useState(false);

  // Check if email was passed from login page
  useEffect(() => {
    if (location.state && location.state.email) {
      console.log("Email received from login page:", location.state.email);
      setEmail(location.state.email);
    }
  }, [location]);

  // Check API availability on component mount
  useEffect(() => {
    console.log("Checking API availability...");
    checkApiStatus();
  }, []);

  // Generate a random captcha on component mount
  useEffect(() => {
    console.log("Generating initial captcha...");
    generateCaptcha();
  }, []);

  /**
   * Check if the API is available
   * Makes a request to the status endpoint to verify connectivity
   */
  const checkApiStatus = async () => {
    try {
<<<<<<< HEAD
      console.log("Making API status request to http://localhost:9292/auth/status");
      const response = await fetch("http://localhost:9292/auth/status", {
=======
      console.log("Making API status request to ${process.env.REACT_APP_API_URL}auth/status");
      const response = await fetch(`${process.env.REACT_APP_API_URL}auth/status`, {
>>>>>>> 1c0592d (commit new code)
        method: "GET",
      }).catch(() => {
        console.log("API status request failed");
        return { ok: false };
      });

      setIsApiAvailable(response.ok);
      
      if (!response.ok) {
        console.warn("API appears to be unavailable or requires authentication");
        setIsApiAvailable(false);
      } else {
        console.log("API is available");
      }
    } catch (error) {
      console.error("API status check error:", error);
      setIsApiAvailable(false);
    }
  };

  /**
   * Generate a random captcha string
   * Creates a 6-character alphanumeric string for verification
   */
  const generateCaptcha = () => {
    const chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    let captcha = "";
    for (let i = 0; i < 6; i++) {
      captcha += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    console.log("New captcha generated:", captcha);
    setCaptchaValue(captcha);
    setUserCaptchaInput("");
    setIsCaptchaValid(false);
  };

  /**
   * Check captcha validity on input change
   * Compares user input with generated captcha value
   * 
   * @param {Event} e - Input change event
   */
  const handleCaptchaInputChange = (e) => {
    const input = e.target.value;
    setUserCaptchaInput(input);
    const isValid = input === captchaValue;
    setIsCaptchaValid(isValid);
    console.log("Captcha validation:", isValid ? "valid" : "invalid", "Input:", input);
  };

  /**
   * Check if email already exists and send OTP
   * First step of registration process
   * 
   * @param {Event} e - Form submission event
   */
  const handleVerifyEmail = async (e) => {
    e.preventDefault();
    console.log("Starting email verification for:", email);
    setIsEmailChecking(true);
    setError("");
    setSuccessMessage("");
    
    if (!email) {
      console.log("Email verification failed: Email is empty");
      setError("Please enter an email address");
      setIsEmailChecking(false);
      return;
    }
    
    // Basic email format validation
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(email)) {
      console.log("Email verification failed: Invalid email format");
      setError("Please enter a valid email address");
      setIsEmailChecking(false);
      return;
    }

    // Only proceed with captcha validation if captcha is valid
    if (!isCaptchaValid) {
      console.log("Email verification failed: Invalid captcha");
      setError("Please enter the correct captcha");
      setIsEmailChecking(false);
      return;
    }
    
    try {
      console.log("Making API request to send OTP email");
      // API call to verify email and send OTP
<<<<<<< HEAD
      const response = await fetch(`http://localhost:9292/token/user/send_email`, {
=======
      const response = await fetch(`${process.env.REACT_APP_API_URL}token/user/send_email `, {
>>>>>>> 1c0592d (commit new code)
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email }),
      });
      
      // Check if the request was successful (status 200-299)
      if (response.ok) {
        const data = await response.json();
        console.log("Email verification successful, OTP sent:", data);
        setSuccessMessage("OTP sent to your email. Please check your inbox.");
        setRegistrationStep("otp");
      } else {
        // Request was not successful
        const errorData = await response.json();
        console.error("Email verification failed:", errorData);
        
        // Check for specific error message pattern
        if (errorData.message && errorData.message.includes("already exist")) {
          console.log("Email already exists in the system");
          setError("This email is already registered. Please use a different email or sign in.");
        } else {
          setRegistrationStep("otp");
          setError(errorData.message || "Failed to verify email. Please try again.");
        }
      }
      
    } catch (error) {
      console.error("Email verification error:", error);
      setError("Could not connect to the server. Please try again later.");
    } finally {
      setIsEmailChecking(false);
    }
  };

  /**
   * Verify OTP
   * Second step of registration process
   * 
   * @param {Event} e - Form submission event
   */
  const handleVerifyOtp = async (e) => {
    e.preventDefault();
    console.log("Starting OTP verification for email:", email);
    setError("");
    setSuccessMessage("");
    setIsVerifyingOtp(true);
    
    if (!otp) {
      console.log("OTP verification failed: OTP is empty");
      setError("Please enter the OTP");
      setIsVerifyingOtp(false);
      return;
    }
    
    try {
      console.log("Making API request to verify OTP:", otp);
      // API call to verify OTP
<<<<<<< HEAD
      const response = await fetch(`http://localhost:9292/token/user/otp_verification?email=${email}&otp=${otp}`, {
=======
      const response = await fetch(`${process.env.REACT_APP_API_URL}token/user/otp_verification?email=${email}&otp=${otp}`, {
>>>>>>> 1c0592d (commit new code)
        method: "POST",
        headers: { "Content-Type": "application/json" },
      });

      // Check if the request was successful
      if (response.ok) {
      const data = await response.json();
        console.log("OTP verification successful:", data);
        setSuccessMessage("Email verified successfully!");
        setRegistrationStep("registration");
      } else {
        // Request was not successful
        const errorData = await response.json();
        console.error("OTP verification failed:", errorData);
        setError(errorData.message || "Invalid OTP. Please try again.");
      }
    } catch (error) {
      console.error("OTP verification error:", error);
      setError("Could not connect to the server. Please try again later.");
    } finally {
      setIsVerifyingOtp(false);
    }
  };

  /**
   * Handle registration form submission
   * Final step of registration process
   * 
   * @param {Event} e - Form submission event
   */
  const handleSubmit = async (e) => {
    e.preventDefault();
    console.log("Starting final registration submission");
    setError("");
    setSuccessMessage("");
    setIsSubmitting(true);

    // Validate passwords match
    if (new_password !== confirm_password) {
      console.log("Registration validation failed: Passwords do not match");
      setError("Passwords do not match");
      setIsSubmitting(false);
      return;
    }

    // Validate fields
    if (!first_name || !last_name || !mob_no || !date_of_birth || !gender) {
      console.log("Registration validation failed: Missing required fields");
      setError("Please fill in all required fields");
      setIsSubmitting(false);
      return;
    }

    // Validate mobile number format
    const mobileRegex = /^[0-9]{10}$/;
    if (!mobileRegex.test(mob_no)) {
      console.log("Registration validation failed: Invalid mobile number format");
      setError("Please enter a valid 10-digit mobile number");
      setIsSubmitting(false);
      return;
    }

    // Validate terms agreement
    if (!agreeTerms) {
      console.log("Registration validation failed: Terms not agreed");
      setError("You must agree to the Terms and Conditions");
      setIsSubmitting(false);
      return;
    }

    try {
      // Prepare the registration data
      const account_id = "1"; 
      const usrGrpId = "41";
      const registrationData = {
        account_id,
        usrGrpId,
        first_name,
        last_name,
        email,
        mob_no,
        date_of_birth,
        gender,
        new_password,
        confirm_password
      };
      
      console.log("Submitting registration data:", JSON.stringify(registrationData, null, 2));
      
      // Make the registration request
<<<<<<< HEAD
      const response = await fetch("http://localhost:9292/token/addOneAppUser", {
=======
      const response = await fetch(`${process.env.REACT_APP_API_URL}token/addOneAppUser`, {
>>>>>>> 1c0592d (commit new code)
        method: "POST",
        headers: { 
          "Content-Type": "application/json",
        },
        body: JSON.stringify(registrationData),
      });

      // Try to parse the response as JSON
      let data;
      try {
        data = await response.json();
        console.log("Registration response data:", data);
      } catch (jsonError) {
        // If response is not JSON, get the text instead
        const textResponse = await response.text();
        console.error("Non-JSON response from registration API:", textResponse);
        
        // Check if this is the authentication error message
        if (textResponse.includes("Full authentication is required")) {
          console.log("Registration system requires authentication");
          setError("Registration system is currently under maintenance. Please try again later or contact support.");
          setIsApiAvailable(false);
        } else {
          setError(textResponse || "Server returned an invalid response");
        }
        setIsSubmitting(false);
        return;
      }

      if (response.ok) {
        console.log("Registration successful, redirecting to login");
        setSuccessMessage("Account created successfully!");
        // Redirect to login after successful registration
        setTimeout(() => {
          navigate("/auth/login");
        }, 2000);
      } else {
        console.log("Registration failed with status:", response.status);
        // Handle specific error messages
        if (response.status === 401 || response.status === 403) {
          // Authentication or authorization error
          console.log("Registration authorization failure");
          setError("Registration system is currently under maintenance. Please try again later.");
          setIsApiAvailable(false);
        } else if (data.message) {
          setError(data.message);
        } else {
          setError("Failed to create account. Please try again.");
        }
      }
    } catch (error) {
      console.error("Registration error:", error);
      setError("An error occurred. Please try again later.");
    } finally {
      setIsSubmitting(false);
    }
  };

  /**
   * Navigate to login page
   * 
   * @param {Event} e - Click event
   */
  const handleLoginClick = (e) => {
    e.preventDefault();
    console.log("Navigating to login page");
    navigate("/auth/login");
  };

  /**
   * Render email verification step with captcha
   * First step of the registration process
   * 
   * @returns {JSX.Element} The verification step UI
   */
  const renderVerificationStep = () => (
    <div className="step-transition animate-fade">
      <div className="welcome-text">
        <h1 className="welcome-title">CREATE ACCOUNT</h1>
        <p className="welcome-subtitle">Enter your email and complete the captcha to get started.</p>
      </div>
      
      {/* Error or success message display */}
      {error && (
        <div className="alert-message alert-error">{error}</div>
      )}
      
      {successMessage && (
        <div className="alert-message alert-success">{successMessage}</div>
      )}
      
      {/* Email verification form */}
      <form onSubmit={handleVerifyEmail}>
        <label className="form-label" htmlFor="email">Email</label>
        <input
          id="email"
          className="form-input"
          type="email"
          placeholder="Enter your email"
          // value={email}
          onChange={(e) => setEmail(e.target.value)}
          required
        />
        
        {/* Captcha verification */}
        <div className="captcha-container">
          <div ref={captchaRef} className="captcha-text">
            {captchaValue}
          </div>
          <button 
            type="button" 
            onClick={generateCaptcha}
            className="captcha-refresh"
          >
            ↻
          </button>
        </div>
        
        <label className="form-label" htmlFor="captcha">Enter Captcha</label>
        <input
          id="captcha"
          className="form-input"
          type="text"
          placeholder="Enter the characters above"
          value={userCaptchaInput}
          onChange={handleCaptchaInputChange}
          required
        />
        
        {/* Submit button - disabled when checking or captcha invalid */}
        <button 
          type="submit" 
          className="login-btn signin-btn"
          disabled={isEmailChecking || !isCaptchaValid}
        >
          {isEmailChecking ? 'Checking...' : 'Verify & Send OTP'}
        </button>
      </form>
      
      {/* Link to login page */}
      <div className="signup-link-container">
        Already have an account?
        <a href="#" className="signup-link" onClick={handleLoginClick}>
          Sign in
        </a>
      </div>
    </div>
  );

  /**
   * Render OTP verification step
   * Second step of the registration process
   * 
   * @returns {JSX.Element} The OTP verification step UI
   */
  const renderOtpStep = () => (
    <div className="step-transition animate-fade">
      <div className="welcome-text">
        <h1 className="welcome-title">VERIFY OTP</h1>
        <p className="welcome-subtitle">Enter the verification code sent to your email.</p>
        </div>

      {/* Error or success message display */}
          {error && (
        <div className="alert-message alert-error">{error}</div>
      )}
      
      {successMessage && (
        <div className="alert-message alert-success">{successMessage}</div>
      )}
      
      {/* OTP verification form */}
      <form onSubmit={handleVerifyOtp}>
        <label className="form-label" htmlFor="otp">OTP Code</label>
        <input
          id="otp"
          className="form-input"
          type="text"
          placeholder="Enter the 6-digit code"
          value={otp}
          onChange={(e) => setOtp(e.target.value)}
          required
          maxLength={6}
        />
        
        {/* Submit button - disabled when verifying */}
        <button 
          type="submit" 
          className="login-btn signin-btn"
          disabled={isVerifyingOtp}
        >
          {isVerifyingOtp ? 'Verifying...' : 'Verify OTP'}
        </button>
      </form>
      
      {/* Navigation back to first step */}
      <div className="signup-link-container">
        <a href="#" className="back-link" onClick={(e) => {
          e.preventDefault();
          console.log("Returning to email verification step");
          setRegistrationStep("verification");
          setSuccessMessage("");
          setError("");
        }}>
          Back to verification
        </a>
      </div>
      
      {/* OTP resend option */}
      <div className="signup-link-container" style={{ marginTop: "10px" }}>
        Didn't receive the code?
        <a href="#" className="signup-link" onClick={async (e) => {
          e.preventDefault();
          console.log("Attempting to resend OTP to:", email);
          setSuccessMessage("");
          setError("");
          
          try {
<<<<<<< HEAD
            const response = await fetch(`http://localhost:9292/token/user/resend_otp?email=${email}`, {
=======
            const response = await fetch(`${process.env.REACT_APP_API_URL}token/user/resend_otp?email=${email}`, {
>>>>>>> 1c0592d (commit new code)
              method: "POST",
              headers: { "Content-Type": "application/json" },
              body: JSON.stringify({ email }),
            });
            
            const data = await response.json();
            console.log("OTP resend response:", data);
            
            if (response.ok) {
              setSuccessMessage("OTP resent to your email. Please check your inbox.");
            } else {
              setError("Failed to resend OTP. Please try again.");
            }
          } catch (error) {
            console.error("OTP resending error:", error);
            setError("Could not resend OTP. Please try again.");
          }
        }}>
          Resend OTP
        </a>
      </div>
    </div>
  );

  /**
   * Render registration form step
   * Final step of the registration process
   * 
   * @returns {JSX.Element} The registration form UI
   */
  const renderRegistrationStep = () => (
    <div className="step-transition animate-fade">
      <div className="welcome-text">
        <h1 className="welcome-title">CREATE ACCOUNT</h1>
        <p className="welcome-subtitle">Please fill in your details to get started.</p>
            </div>
      
      {/* Error or success message display */}
      {error && (
        <div className="alert-message alert-error">{error}</div>
          )}
      
          {successMessage && (
        <div className="alert-message alert-success">{successMessage}</div>
      )}
      
      {/* API availability warning */}
      {!isApiAvailable && !error && !successMessage && (
        <div className="alert-message alert-warning">
          Note: The registration system appears to be in maintenance mode. 
          Please try again later or contact support.
            </div>
          )}

      {/* Registration form container */}
      <div className="registration-form-container">
        <form onSubmit={handleSubmit} className="registration-form">
          {/* Name fields (first and last name) */}
          <div className="form-row">
            <div className="form-group">
              <label className="form-label" htmlFor="first_name">First Name</label>
              <input
                id="first_name"
                className="form-input"
                type="text"
                placeholder="Enter your first name"
                value={first_name}
                onChange={(e) => setfirst_name(e.target.value)}
                required
              />
            </div>
            
            <div className="form-group">
              <label className="form-label" htmlFor="last_name">Last Name</label>
              <input
                id="last_name"
                className="form-input"
                  type="text"
                placeholder="Enter your last name"
                value={last_name}
                onChange={(e) => setlast_name(e.target.value)}
                required
              />
            </div>
          </div>
          
          {/* Mobile number field */}
          <label className="form-label" htmlFor="mob_no">Mobile Number</label>
          <input
            id="mob_no"
            className="form-input"
            type="tel"
            placeholder="Enter your 10-digit mobile number"
            value={mob_no}
            onChange={(e) => setmob_no(e.target.value.replace(/[^0-9]/g, ''))}
            maxLength={10}
                  required
                />
          
          {/* Date of birth field */}
          <label className="form-label" htmlFor="date_of_birth">Date of Birth</label>
          <input
            id="date_of_birth"
            className="form-input"
            type="date"
            value={date_of_birth}
            onChange={(e) => setdate_of_birth(e.target.value)}
                  required
                />
          
          {/* Gender selection */}
          <label className="form-label" htmlFor="gender">Gender</label>
          <select
            id="gender"
            className="form-input"
            value={gender}
            onChange={(e) => setGender(e.target.value)}
            required
          >
            <option value="" disabled>Select gender</option>
            <option value="male">Male</option>
            <option value="female">Female</option>
            <option value="other">Other</option>
          </select>
          
          {/* Password fields */}
          <label className="form-label" htmlFor="new_password">Password</label>
          <input
            id="new_password"
            className="form-input"
                  type="password"
            placeholder="Create a password"
            value={new_password}
                  onChange={(e) => setPassword(e.target.value)}
                  required
                />
          
          <label className="form-label" htmlFor="confirm_password">Confirm Password</label>
          <input
            id="confirm_password"
            className="form-input"
                  type="password"
            placeholder="Confirm your password"
            value={confirm_password}
                  onChange={(e) => setConfirmPassword(e.target.value)}
                  required
                />

          {/* Terms and conditions checkbox */}
          <div className="remember-me" style={{ marginBottom: "0.8rem" }}>
                  <input
                    type="checkbox"
              id="terms"
              className="remember-checkbox"
              checked={agreeTerms}
              onChange={() => setAgreeTerms(!agreeTerms)}
                    required
                  />
            <label htmlFor="terms">
              I agree to the <a href="#" style={{ color: "#e94a4a" }}>Terms and Conditions</a>
                  </label>
                </div>

          {/* Submit button - disabled when submitting */}
          <button 
              type="submit"
            className="login-btn signin-btn"
            disabled={isSubmitting}
          >
            {isSubmitting ? 'Creating Account...' : 'Create Account'}
          </button>
        </form>
      </div>
      
      {/* Navigation back to OTP step */}
      <div className="signup-link-container">
        <a href="#" className="back-link" onClick={(e) => {
          e.preventDefault();
          console.log("Returning to OTP verification step");
          setRegistrationStep("otp");
          setError("");
        }}>
          Back to verification
        </a>
      </div>
    </div>
  );

   {/* Right side - Image */}
   const renderImage = () => {
    // Get the image URL from LoginEnvironment
    return (
      <div className="login-image-container">
        <div className="login-image" style={{
          backgroundColor: '#f5f5f5',
          backgroundImage: `url(${LoginEnvironment.loginImageURL})`,
          backgroundSize: 'cover',
          backgroundPosition: 'center'
        }}></div>
      </div>
    );
  };


  // Main component return - conditional rendering based on current step
  return (
    <div className="login-container">
      {LoginEnvironment.templateNo==="Template 1"?(
        <>
        {/* Left side - Registration Form */}
      <div className="login-form-container">
        {registrationStep === "verification" && renderVerificationStep()}
        {registrationStep === "otp" && renderOtpStep()}
        {registrationStep === "registration" && renderRegistrationStep()}
      </div>
      {renderImage()}
        </>
      ):(
        <>
        {renderImage()}
        {/* Left side - Registration Form */}
      <div className="login-form-container">
        {registrationStep === "verification" && renderVerificationStep()}
        {registrationStep === "otp" && renderOtpStep()}
        {registrationStep === "registration" && renderRegistrationStep()}
      </div>
        </>
      )}
      
      
    </div>
  );
};

export default Register;