// File: src/pages/Sites/AddSite.jsx

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

/**
 * AddSite - Page for connecting a new WordPress site to MaplePress
 */
function AddSite() {
  const navigate = useNavigate();
  const { authManager } = useAuth();
  const [user, setUser] = useState(null);
  const [isLoading, setIsLoading] = useState(true);
  const [formData, setFormData] = useState({
    site_url: "",
  });
  const [errors, setErrors] = useState({});
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [generalError, setGeneralError] = useState("");

  useEffect(() => {
    // Wait for AuthManager to initialize before checking authentication
    const checkAuth = () => {
      const isInitialized = authManager.getIsInitialized();

      if (!isInitialized) {
        setTimeout(checkAuth, 50);
        return;
      }

      const isAuth = authManager.isAuthenticated();
      if (!isAuth) {
        navigate("/login");
        return;
      }

      const userData = authManager.getUser();
      setUser(userData);
      setIsLoading(false);
    };

    checkAuth();
  }, [authManager, navigate]);

  // Background token refresh - check every 30 seconds
  useEffect(() => {
    const refreshInterval = setInterval(async () => {
      if (!authManager.getIsInitialized()) {
        return;
      }

      try {
        // This will refresh the token if it's expiring soon (within 1 minute)
        await authManager.ensureValidToken();
      } catch (error) {
        console.error("[AddSite] Background token refresh failed:", error);
        // Token refresh failed, redirect to login
        navigate("/login");
      }
    }, 30000); // Check every 30 seconds

    return () => clearInterval(refreshInterval);
  }, [authManager, navigate]);

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

    // Clear error for this field when user starts typing
    if (errors[name]) {
      setErrors((prev) => ({ ...prev, [name]: null }));
    }
    if (generalError) {
      setGeneralError("");
    }
  };

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

    console.log("[AddSite] Form submitted:", { site_url: formData.site_url });

    try {
      // Call SiteService to create site
      // Backend will extract domain from siteUrl
      const response = await SiteService.createSite({
        siteUrl: formData.site_url,
      });

      console.log("[AddSite] Site created successfully:", response);

      // Navigate to success page with site data
      navigate("/sites/add-success", {
        state: {
          siteData: {
            id: response.id,
            domain: response.domain,
            site_url: response.siteUrl,
            api_key: response.apiKey,
            verification_token: response.verificationToken,
            verification_instructions: response.verificationInstructions,
            status: response.status,
            search_index_name: response.searchIndexName,
          }
        }
      });
    } catch (error) {
      console.error("[AddSite] Site creation failed:", error);
      setIsSubmitting(false);

      // Parse RFC 9457 validation errors
      const { fieldErrors, generalError: parsedGeneralError } = parseBackendError(error);

      if (Object.keys(fieldErrors).length > 0) {
        setErrors(fieldErrors);
      }

      setGeneralError(parsedGeneralError || "Failed to create site. Please try again.");
    }
  };

  /**
   * Format field names for display
   */
  const formatFieldName = (fieldName) => {
    const fieldLabels = {
      site_url: "Site URL",
    };
    return fieldLabels[fieldName] || fieldName;
  };

  /**
   * Parse backend RFC 9457 error format
   */
  const parseBackendError = (error) => {
    console.log("[AddSite] 🔍 Parsing backend error:", error);
    console.log("[AddSite] 🔍 Error has validationErrors:", !!error.validationErrors);
    console.log("[AddSite] 🔍 validationErrors content:", error.validationErrors);

    const fieldErrors = {};
    let generalError = null;

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

      // Process each field's errors
      Object.entries(error.validationErrors).forEach(([fieldName, errorMessages]) => {
        if (Array.isArray(errorMessages) && errorMessages.length > 0) {
          // Join multiple error messages for the same field with semicolon
          fieldErrors[fieldName] = errorMessages.join('; ');
          console.log(`[AddSite] 📋 Field "${fieldName}": ${fieldErrors[fieldName]}`);
        }
      });

      // Use the detail/message as general error if available
      if (error.message) {
        generalError = error.message;
      }
    } else {
      // Fallback for non-RFC 9457 errors
      console.log("[AddSite] ⚠️ Non-RFC 9457 error, using fallback");
      generalError = error.message || "An error occurred. Please try again.";
    }

    console.log("[AddSite] 📊 Parsed errors:", { fieldErrors, generalError });
    return { fieldErrors, generalError };
  };

  const handleCancel = () => {
    navigate("/dashboard");
  };

  // Show loading state while waiting for authentication check
  if (isLoading) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50 to-indigo-100 flex items-center justify-center">
        <div className="text-center">
          <div className="inline-block animate-spin rounded-full h-12 w-12 border-4 border-indigo-600 border-t-transparent"></div>
          <p className="mt-4 text-gray-600">Loading...</p>
        </div>
      </div>
    );
  }


  // Show form to create site
  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50 to-indigo-100">
      {/* Navigation Bar */}
      <nav className="bg-white border-b border-gray-200 shadow-sm sticky top-0 z-50">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex justify-between items-center h-16">
            {/* Logo */}
            <button
              onClick={() => navigate("/dashboard")}
              className="flex items-center gap-2 hover:opacity-80 transition-opacity"
            >
              <span className="text-2xl">🍁</span>
              <h1 className="text-xl font-bold bg-gradient-to-r from-indigo-600 to-blue-600 bg-clip-text text-transparent">
                MaplePress
              </h1>
            </button>

            {/* User Menu */}
            <div className="flex items-center gap-2 px-4 py-2 bg-gray-50 rounded-lg">
              <div className="w-8 h-8 bg-gradient-to-r from-indigo-600 to-blue-600 rounded-full
                            flex items-center justify-center text-white text-sm font-semibold">
                {user?.email?.[0]?.toUpperCase() || "U"}
              </div>
              <span className="text-sm font-medium text-gray-700">
                {user?.email || "User"}
              </span>
            </div>
          </div>
        </div>
      </nav>

      {/* Main Content */}
      <main className="max-w-3xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
        {/* Header */}
        <div className="mb-8">
          <button
            onClick={handleCancel}
            className="text-indigo-600 hover:text-indigo-700 font-medium mb-4 flex items-center gap-2"
          >
            <span>←</span>
            <span>Back to Dashboard</span>
          </button>
          <h1 className="text-3xl font-bold text-gray-900 mb-2">
            Add WordPress Site
          </h1>
          <p className="text-gray-600">
            Register your WordPress site to generate API credentials
          </p>
        </div>

        {/* Form Card */}
        <div className="bg-white rounded-2xl shadow-lg border border-gray-100 overflow-hidden">
          <div className="p-8">
            {/* 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>
                      )}
                      {/* Merge domain and site_url errors since they're about the same field */}
                      {(() => {
                        const fieldErrors = Object.entries(errors).filter(([_, message]) => message);
                        const mergedErrors = new Map();

                        fieldErrors.forEach(([field, message]) => {
                          const displayName = formatFieldName(field);
                          if (mergedErrors.has(displayName)) {
                            // Combine messages if they're different
                            const existing = mergedErrors.get(displayName);
                            if (existing !== message) {
                              mergedErrors.set(displayName, `${existing}; ${message}`);
                            }
                          } else {
                            mergedErrors.set(displayName, message);
                          }
                        });

                        return Array.from(mergedErrors.entries()).map(([displayName, message]) => (
                          <li key={displayName}>
                            • <span className="font-medium">{displayName}:</span> {message}
                          </li>
                        ));
                      })()}
                    </ul>
                  </div>
                </div>
              </div>
            )}

            <form onSubmit={handleSubmit}>
              {/* WordPress Site URL */}
              <div className="mb-6">
                <label
                  htmlFor="site_url"
                  className="block text-sm font-medium text-gray-700 mb-2"
                >
                  WordPress Site URL
                </label>
                <input
                  type="text"
                  id="site_url"
                  name="site_url"
                  value={formData.site_url}
                  onChange={handleInputChange}
                  className={`w-full px-4 py-3 border rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent
                    ${errors.site_url ? "border-red-500" : "border-gray-300"}`}
                  placeholder="https://example.com"
                  disabled={isSubmitting}
                  autoFocus
                />
                {errors.site_url && (
                  <p className="mt-1 text-sm text-red-600">{errors.site_url}</p>
                )}
                <p className="mt-1 text-sm text-gray-500">
                  Enter the full URL of your WordPress site (e.g., https://example.com or https://www.example.com/blog)
                </p>
              </div>

              {/* Info Box */}
              <div className="mb-6 p-4 bg-indigo-50 border border-indigo-100 rounded-lg">
                <div className="flex items-start gap-3">
                  <span className="text-2xl">💡</span>
                  <div className="flex-1">
                    <h4 className="font-semibold text-gray-900 mb-2">
                      What Happens Next?
                    </h4>
                    <ul className="space-y-1 text-sm text-gray-700">
                      <li>• MaplePress will generate an API key for your site</li>
                      <li>• You'll receive the API key <strong>only once</strong> - save it immediately!</li>
                      <li>• Use the API key in your WordPress plugin settings to connect</li>
                    </ul>
                  </div>
                </div>
              </div>

              {/* Action Buttons */}
              <div className="flex gap-3">
                <button
                  type="submit"
                  disabled={isSubmitting}
                  className="flex-1 px-6 py-3 bg-gradient-to-r from-indigo-600 to-blue-600 text-white
                           rounded-lg hover:from-indigo-700 hover:to-blue-700 transition-all
                           font-medium shadow-lg hover:shadow-xl disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {isSubmitting ? "Creating Site..." : "Create Site"}
                </button>
                <button
                  type="button"
                  onClick={handleCancel}
                  disabled={isSubmitting}
                  className="px-6 py-3 text-gray-700 border border-gray-300 rounded-lg
                           hover:bg-gray-50 transition-all font-medium disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  Cancel
                </button>
              </div>
            </form>
          </div>
        </div>

        {/* Help Section */}
        <div className="mt-8 bg-gradient-to-r from-indigo-50 to-blue-50 rounded-2xl p-6 border border-indigo-100">
          <div className="flex items-start gap-3">
            <span className="text-2xl">📚</span>
            <div className="flex-1">
              <h3 className="font-semibold text-gray-900 mb-2">
                Need the WordPress Plugin?
              </h3>
              <p className="text-sm text-gray-700 mb-3">
                Make sure you have the MaplePress plugin installed on your WordPress site before connecting.
              </p>
              <button className="px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700
                               transition-all font-medium text-sm">
                Download Plugin
              </button>
            </div>
          </div>
        </div>
      </main>
    </div>
  );
}

export default AddSite;
