// 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("");
    }
  };

  /**
   * Extract domain from URL
   */
  const extractDomainFromUrl = (url) => {
    try {
      const urlObj = new URL(url);
      return urlObj.hostname;
    } catch (error) {
      // If URL is invalid, return it as-is and let backend validation handle it
      return url;
    }
  };

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

    // Extract domain from the site URL
    const domain = extractDomainFromUrl(formData.site_url);

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

    try {
      // Call SiteService to create site
      // Send data as-is, let backend validate
      const response = await SiteService.createSite({
        domain: domain,
        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,
            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 = {
      domain: "Domain",
      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 success page with API key if site was created
  if (createdSite) {
    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>

        {/* Success Content */}
        <main className="max-w-3xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
          <div className="bg-white rounded-2xl shadow-lg border border-gray-100 overflow-hidden">
            {/* Success Header */}
            <div className="bg-gradient-to-r from-green-600 to-emerald-600 px-8 py-6 text-white">
              <div className="flex items-center gap-3 mb-2">
                <span className="text-3xl">✅</span>
                <h1 className="text-2xl font-bold">Site Created Successfully!</h1>
              </div>
              <p className="text-green-50">
                Your WordPress site has been registered with MaplePress
              </p>
            </div>

            <div className="p-8">
              {/* Site Details */}
              <div className="mb-8">
                <h3 className="text-lg font-semibold text-gray-900 mb-4">Site Details</h3>
                <div className="space-y-3 bg-gray-50 rounded-lg p-4">
                  <div>
                    <span className="text-sm text-gray-600">Domain:</span>
                    <p className="font-medium text-gray-900">{createdSite.domain}</p>
                  </div>
                  <div>
                    <span className="text-sm text-gray-600">Site URL:</span>
                    <p className="font-medium text-gray-900">{createdSite.site_url}</p>
                  </div>
                  <div>
                    <span className="text-sm text-gray-600">Status:</span>
                    <p className="font-medium text-yellow-600 capitalize">{createdSite.status}</p>
                  </div>
                </div>
              </div>

              {/* API Key Section - IMPORTANT */}
              <div className="mb-8 p-6 bg-yellow-50 border-2 border-yellow-200 rounded-lg">
                <div className="flex items-start gap-3 mb-4">
                  <span className="text-2xl">⚠️</span>
                  <div>
                    <h3 className="text-lg font-bold text-gray-900 mb-1">
                      Save Your API Key Now!
                    </h3>
                    <p className="text-sm text-gray-700">
                      This API key will <strong>only be shown once</strong>. Copy it now and add it to your WordPress plugin settings.
                    </p>
                  </div>
                </div>

                <div className="bg-white rounded-lg p-4 border border-yellow-300">
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    API Key
                  </label>
                  <div className="flex gap-2">
                    <input
                      type="text"
                      value={createdSite.api_key}
                      readOnly
                      className="flex-1 px-4 py-2 border border-gray-300 rounded-lg bg-gray-50 font-mono text-sm"
                    />
                    <button
                      onClick={handleCopyApiKey}
                      className="px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700
                               transition-all font-medium"
                    >
                      Copy
                    </button>
                  </div>
                </div>
              </div>

              {/* Next Steps */}
              <div className="mb-8">
                <h3 className="text-lg font-semibold text-gray-900 mb-4">Next Steps</h3>
                <ol className="space-y-3">
                  <li className="flex items-start gap-3">
                    <span className="flex-shrink-0 w-6 h-6 bg-indigo-600 text-white rounded-full
                                   flex items-center justify-center text-sm font-bold">
                      1
                    </span>
                    <div>
                      <p className="font-medium text-gray-900">Install the MaplePress WordPress Plugin</p>
                      <p className="text-sm text-gray-600">Download and activate the plugin on your WordPress site</p>
                    </div>
                  </li>
                  <li className="flex items-start gap-3">
                    <span className="flex-shrink-0 w-6 h-6 bg-indigo-600 text-white rounded-full
                                   flex items-center justify-center text-sm font-bold">
                      2
                    </span>
                    <div>
                      <p className="font-medium text-gray-900">Enter Your API Key</p>
                      <p className="text-sm text-gray-600">
                        Go to Settings → MaplePress and paste your API key (copied above)
                      </p>
                    </div>
                  </li>
                  <li className="flex items-start gap-3">
                    <span className="flex-shrink-0 w-6 h-6 bg-indigo-600 text-white rounded-full
                                   flex items-center justify-center text-sm font-bold">
                      3
                    </span>
                    <div>
                      <p className="font-medium text-gray-900">Verify Your Site</p>
                      <p className="text-sm text-gray-600">
                        The plugin will automatically verify your site and activate cloud services
                      </p>
                    </div>
                  </li>
                </ol>
              </div>

              {/* Action Button */}
              <button
                onClick={handleDone}
                className="w-full 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"
              >
                Go to Dashboard
              </button>
            </div>
          </div>
        </main>
      </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>
                      )}
                      {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>
            )}

            <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>
                )}
                {errors.domain && (
                  <p className="mt-1 text-sm text-red-600">{errors.domain}</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;
