// File: src/pages/Auth/Register.jsx

import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router";
import { useAuth } from "../../services/Services";
import RegisterService from "../../services/API/RegisterService";

/**
 * Register - User registration page
 *
 * Complete implementation with all required fields for MaplePress backend
 */
function Register() {
  const navigate = useNavigate();
  const { authManager } = useAuth();

  const [formData, setFormData] = useState({
    // User fields
    first_name: "",
    last_name: "",
    email: "",
    password: "",
    confirmPassword: "",

    // Tenant/Organization fields
    tenant_name: "",

    // Consent fields
    agree_terms_of_service: false,
    agree_promotions: false,
    agree_to_tracking_across_third_party_apps_and_services: false,
  });

  const [errors, setErrors] = useState({}); // Field-specific errors
  const [generalError, setGeneralError] = useState(""); // General error message
  const [loading, setLoading] = useState(false);

  const handleInputChange = (e) => {
    const { name, value, type, checked } = e.target;
    setFormData((prev) => ({
      ...prev,
      [name]: type === "checkbox" ? checked : value,
    }));

    // Clear errors when user types
    setErrors((prev) => ({ ...prev, [name]: null }));
    setGeneralError("");
  };

  /**
   * Format field name for display in error messages
   * Converts snake_case to Title Case
   */
  const formatFieldName = (fieldName) => {
    const fieldLabels = {
      first_name: "First Name",
      last_name: "Last Name",
      email: "Email",
      password: "Password",
      confirm_password: "Confirm Password",
      confirmPassword: "Confirm Password",
      tenant_name: "Organization Name",
      agree_terms_of_service: "Terms of Service",
      agree_promotions: "Promotions",
      agree_to_tracking_across_third_party_apps_and_services: "Third-Party Tracking",
    };

    return fieldLabels[fieldName] || fieldName;
  };

  /**
   * Parse backend error (RFC 9457 format)
   * Backend returns structured validation errors in format:
   * {
   *   type: "about:blank",
   *   title: "Validation Error",
   *   status: 400,
   *   detail: "One or more validation errors occurred",
   *   errors: {
   *     email: ["Invalid email format"],
   *     password: ["Password is required", "Password must be at least 8 characters"]
   *   }
   * }
   */
  const parseBackendError = (error) => {
    console.log('[Register] Parsing error:', error);
    console.log('[Register] error.validationErrors:', error.validationErrors);
    console.log('[Register] error.message:', error.message);

    const fieldErrors = {};
    let generalError = null;

    // Map backend field names (snake_case) to frontend field names (camelCase)
    const fieldNameMap = {
      'confirm_password': 'confirmPassword',
      'first_name': 'first_name',
      'last_name': 'last_name',
      'tenant_name': 'tenant_name',
      'agree_terms_of_service': 'agree_terms_of_service',
      'agree_promotions': 'agree_promotions',
      'agree_to_tracking_across_third_party_apps_and_services': 'agree_to_tracking_across_third_party_apps_and_services',
    };

    // Check if error has RFC 9457 validation errors structure
    if (error.validationErrors && typeof error.validationErrors === 'object') {
      console.log('[Register] Found RFC 9457 validation errors');

      // Process each field's errors
      Object.entries(error.validationErrors).forEach(([backendFieldName, errorMessages]) => {
        if (Array.isArray(errorMessages) && errorMessages.length > 0) {
          // Map backend field name to frontend field name
          const frontendFieldName = fieldNameMap[backendFieldName] || backendFieldName;

          // Join multiple error messages for the same field
          fieldErrors[frontendFieldName] = errorMessages.join('; ');
          console.log(`[Register] Field error: ${backendFieldName} -> ${frontendFieldName} = ${fieldErrors[frontendFieldName]}`);
        }
      });

      // Use the detail as general error if available
      if (error.message) {
        generalError = error.message;
      }
    } else {
      console.log('[Register] No RFC 9457 errors found, using fallback');
      // Fallback for non-RFC 9457 errors or legacy format
      generalError = error.message || "An error occurred. Please try again.";
    }

    console.log('[Register] Parsed result:', { fieldErrors, generalError });

    return {
      fieldErrors,
      generalError
    };
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setErrors({});
    setGeneralError("");

    setLoading(true);

    try {
      // Prepare registration data
      // All validation (including password matching) is now handled by backend
      const registrationData = {
        email: formData.email,
        password: formData.password,
        confirmPassword: formData.confirmPassword,
        first_name: formData.first_name,
        last_name: formData.last_name,
        tenant_name: formData.tenant_name,
        timezone: Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC",
        agree_terms_of_service: formData.agree_terms_of_service,
        agree_promotions: formData.agree_promotions,
        agree_to_tracking_across_third_party_apps_and_services: formData.agree_to_tracking_across_third_party_apps_and_services,
      };

      // Register via AuthManager
      await authManager.register(registrationData);

      // Navigate to dashboard on success
      navigate("/dashboard");
    } catch (err) {
      console.log('[Register] Caught error in handleSubmit:', err);
      console.log('[Register] Error type:', typeof err);
      console.log('[Register] Error properties:', Object.keys(err));

      // Parse RFC 9457 error response
      const { fieldErrors, generalError } = parseBackendError(err);

      console.log('[Register] Setting errors:', fieldErrors);
      console.log('[Register] Setting generalError:', generalError);

      setErrors(fieldErrors);
      if (generalError) {
        setGeneralError(generalError);
      }
    } finally {
      setLoading(false);
    }
  };

  const handleLoginClick = () => {
    navigate("/login");
  };

  const handleBackClick = () => {
    navigate("/");
  };

  /**
   * Get className for input field with error highlighting
   */
  const getInputClassName = (fieldName, baseClassName) => {
    const hasError = errors[fieldName];
    if (hasError) {
      return baseClassName.replace('border-gray-300', 'border-red-500') + ' ring-1 ring-red-500';
    }
    return baseClassName;
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50 to-indigo-100 flex items-center justify-center p-4 py-12">
      <div className="max-w-2xl w-full">
        {/* Logo/Brand */}
        <div className="text-center mb-8">
          <div className="inline-flex items-center gap-2 bg-white px-6 py-3 rounded-full shadow-lg mb-4">
            <span className="text-3xl">🍁</span>
            <h1 className="text-2xl font-bold bg-gradient-to-r from-indigo-600 to-blue-600 bg-clip-text text-transparent">
              MaplePress
            </h1>
          </div>
        </div>

        {/* Register Card */}
        <div className="bg-white rounded-2xl shadow-xl p-8 border border-gray-100">
          {/* Header */}
          <div className="mb-6">
            <h2 className="text-2xl font-bold text-gray-900 mb-2">
              Create your account
            </h2>
            <p className="text-gray-600">Get started with MaplePress in minutes</p>
          </div>

          {/* Error Summary Box */}
          {(generalError || Object.entries(errors).filter(([_, msg]) => msg).length > 0) && (
            <div className="mb-6 p-4 bg-red-50 border border-red-200 rounded-lg">
              <div className="flex items-start gap-3">
                <div className="flex-shrink-0 text-red-600 text-xl">⚠️</div>
                <div className="flex-1">
                  <h3 className="text-sm font-semibold text-red-800 mb-2">
                    Please correct the following errors:
                  </h3>
                  <ul className="space-y-1 text-sm text-red-600">
                    {generalError && (
                      <li>• {generalError}</li>
                    )}
                    {Object.entries(errors).filter(([_, message]) => message).map(([field, message]) => (
                      <li key={field}>
                        • <span className="font-medium">{formatFieldName(field)}:</span> {message}
                      </li>
                    ))}
                  </ul>
                </div>
              </div>
            </div>
          )}

          {/* Registration Form */}
          <form onSubmit={handleSubmit} className="space-y-5">
            {/* Personal Information Section */}
            <div className="space-y-4">
              <h3 className="text-sm font-semibold text-gray-900 uppercase tracking-wide">
                Personal Information
              </h3>

              {/* First Name */}
              <div>
                <label
                  htmlFor="first_name"
                  className="block text-sm font-medium text-gray-700 mb-1"
                >
                  First Name *
                </label>
                <input
                  type="text"
                  id="first_name"
                  name="first_name"
                  value={formData.first_name}
                  onChange={handleInputChange}
                  className={getInputClassName("first_name", "w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent transition-colors")}
                  placeholder="John"
                />
                {errors.first_name && (
                  <p className="mt-1 text-sm text-red-600">{errors.first_name}</p>
                )}
              </div>

              {/* Last Name */}
              <div>
                <label
                  htmlFor="last_name"
                  className="block text-sm font-medium text-gray-700 mb-1"
                >
                  Last Name *
                </label>
                <input
                  type="text"
                  id="last_name"
                  name="last_name"
                  value={formData.last_name}
                  onChange={handleInputChange}
                  className={getInputClassName("last_name", "w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent transition-colors")}
                  placeholder="Doe"
                />
                {errors.last_name && (
                  <p className="mt-1 text-sm text-red-600">{errors.last_name}</p>
                )}
              </div>

              {/* Email */}
              <div>
                <label
                  htmlFor="email"
                  className="block text-sm font-medium text-gray-700 mb-1"
                >
                  Email Address *
                </label>
                <input
                  type="text"
                  id="email"
                  name="email"
                  value={formData.email}
                  onChange={handleInputChange}
                  className={getInputClassName("email", "w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent transition-colors")}
                  placeholder="you@example.com"
                />
                {errors.email && (
                  <p className="mt-1 text-sm text-red-600">{errors.email}</p>
                )}
              </div>

              {/* Password */}
              <div>
                <label
                  htmlFor="password"
                  className="block text-sm font-medium text-gray-700 mb-1"
                >
                  Password *
                </label>
                <input
                  type="password"
                  id="password"
                  name="password"
                  value={formData.password}
                  onChange={handleInputChange}
                  className={getInputClassName("password", "w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent transition-colors")}
                  placeholder="••••••••"
                />
                {errors.password ? (
                  <p className="mt-1 text-sm text-red-600">{errors.password}</p>
                ) : (
                  <p className="mt-1 text-xs text-gray-500">
                    Minimum 8 characters
                  </p>
                )}
              </div>

              {/* Confirm Password */}
              <div>
                <label
                  htmlFor="confirmPassword"
                  className="block text-sm font-medium text-gray-700 mb-1"
                >
                  Confirm Password *
                </label>
                <input
                  type="password"
                  id="confirmPassword"
                  name="confirmPassword"
                  value={formData.confirmPassword}
                  onChange={handleInputChange}
                  className={getInputClassName("confirmPassword", "w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent transition-colors")}
                  placeholder="••••••••"
                />
                {errors.confirmPassword && (
                  <p className="mt-1 text-sm text-red-600">{errors.confirmPassword}</p>
                )}
              </div>
            </div>

            {/* Organization Information Section */}
            <div className="space-y-4 pt-4 border-t border-gray-200">
              <h3 className="text-sm font-semibold text-gray-900 uppercase tracking-wide">
                Organization Information
              </h3>

              {/* Organization Name */}
              <div>
                <label
                  htmlFor="tenant_name"
                  className="block text-sm font-medium text-gray-700 mb-1"
                >
                  Organization Name *
                </label>
                <input
                  type="text"
                  id="tenant_name"
                  name="tenant_name"
                  value={formData.tenant_name}
                  onChange={handleInputChange}
                  className={getInputClassName("tenant_name", "w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent transition-colors")}
                  placeholder="Acme Corporation"
                />
                {errors.tenant_name && (
                  <p className="mt-1 text-sm text-red-600">{errors.tenant_name}</p>
                )}
                <p className="mt-1 text-xs text-gray-500">
                  Your organization's URL will be automatically generated
                </p>
              </div>
            </div>

            {/* Terms and Consent Section */}
            <div className="space-y-3 pt-4 border-t border-gray-200">
              {/* Terms of Service */}
              <div>
                <div className="flex items-start">
                  <input
                    type="checkbox"
                    id="agree_terms_of_service"
                    name="agree_terms_of_service"
                    checked={formData.agree_terms_of_service}
                    onChange={handleInputChange}
                    className={`mt-1 h-4 w-4 text-indigo-600 rounded focus:ring-indigo-500 ${errors.agree_terms_of_service ? 'border-red-500' : 'border-gray-300'}`}
                  />
                  <label
                    htmlFor="agree_terms_of_service"
                    className="ml-2 text-sm text-gray-700"
                  >
                    I agree to the{" "}
                    <a
                      href="#"
                      className="text-indigo-600 hover:text-indigo-700 font-medium"
                    >
                      Terms of Service
                    </a>{" "}
                    *
                  </label>
                </div>
                {errors.agree_terms_of_service && (
                  <p className="mt-1 ml-6 text-sm text-red-600">{errors.agree_terms_of_service}</p>
                )}
              </div>

              {/* Promotional Emails (Optional) */}
              <div className="flex items-start">
                <input
                  type="checkbox"
                  id="agree_promotions"
                  name="agree_promotions"
                  checked={formData.agree_promotions}
                  onChange={handleInputChange}
                  className="mt-1 h-4 w-4 text-indigo-600 border-gray-300 rounded
                           focus:ring-indigo-500"
                />
                <label
                  htmlFor="agree_promotions"
                  className="ml-2 text-sm text-gray-700"
                >
                  Send me promotional emails and updates (optional)
                </label>
              </div>

              {/* Third-Party Tracking (Optional) */}
              <div className="flex items-start">
                <input
                  type="checkbox"
                  id="agree_to_tracking_across_third_party_apps_and_services"
                  name="agree_to_tracking_across_third_party_apps_and_services"
                  checked={formData.agree_to_tracking_across_third_party_apps_and_services}
                  onChange={handleInputChange}
                  className="mt-1 h-4 w-4 text-indigo-600 border-gray-300 rounded
                           focus:ring-indigo-500"
                />
                <label
                  htmlFor="agree_to_tracking_across_third_party_apps_and_services"
                  className="ml-2 text-sm text-gray-700"
                >
                  Allow tracking across third-party apps and services for analytics (optional)
                </label>
              </div>
            </div>

            {/* Submit Button */}
            <button
              type="submit"
              disabled={loading}
              className="w-full px-4 py-3 bg-gradient-to-r from-indigo-600 to-blue-600 text-white font-semibold rounded-xl
                       hover:shadow-lg transform hover:-translate-y-0.5 transition-all duration-200
                       disabled:opacity-50 disabled:cursor-not-allowed disabled:transform-none mt-6"
            >
              {loading ? (
                <span className="flex items-center justify-center gap-2">
                  <svg className="animate-spin h-5 w-5" viewBox="0 0 24 24">
                    <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" fill="none"/>
                    <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"/>
                  </svg>
                  Creating account...
                </span>
              ) : (
                "Create Account"
              )}
            </button>
          </form>

          {/* Login Link */}
          <div className="mt-6 text-center">
            <p className="text-sm text-gray-600">
              Already have an account?{" "}
              <button
                onClick={handleLoginClick}
                className="text-indigo-600 font-semibold hover:text-indigo-700 hover:underline"
              >
                Sign in instead
              </button>
            </p>
          </div>

          {/* Back to Home Link */}
          <div className="mt-4 pt-4 border-t border-gray-100 text-center">
            <button
              onClick={handleBackClick}
              className="text-sm text-gray-500 hover:text-gray-700 transition-colors inline-flex items-center gap-1"
            >
              <span>←</span>
              <span>Back to Home</span>
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

export default Register;
