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

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

/**
 * RotateApiKey - Page for rotating a site's API key
 */
function RotateApiKey() {
  const navigate = useNavigate();
  const { id } = useParams();
  const { authManager } = useAuth();
  const [user, setUser] = useState(null);
  const [isLoading, setIsLoading] = useState(true);
  const [site, setSite] = useState(null);
  const [siteLoading, setSiteLoading] = useState(false);
  const [siteError, setSiteError] = useState(null);
  const [isRotating, setIsRotating] = useState(false);
  const [rotateError, setRotateError] = useState(null);
  const [rotationResult, setRotationResult] = useState(null);
  const [confirmationText, setConfirmationText] = useState("");
  const [apiKeyCopied, setApiKeyCopied] = useState(false);

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

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

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

      // Proactively refresh token if needed
      try {
        await authManager.ensureValidToken();
      } catch (error) {
        console.error("[RotateApiKey] Token refresh failed:", error);
        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 {
        await authManager.ensureValidToken();
      } catch (error) {
        console.error("[RotateApiKey] Background token refresh failed:", error);
        navigate("/login");
      }
    }, 30000);

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

  // Load site details
  useEffect(() => {
    if (!user || isLoading || !id) {
      return;
    }

    const loadSite = async () => {
      setSiteLoading(true);
      setSiteError(null);

      console.log("[RotateApiKey] Loading site:", id);

      try {
        const siteData = await SiteService.getSiteById(id);
        console.log("[RotateApiKey] Site loaded:", siteData);
        setSite(siteData);
      } catch (error) {
        console.error("[RotateApiKey] Failed to load site:", error);
        setSiteError(error.message || "Failed to load site details");
      } finally {
        setSiteLoading(false);
      }
    };

    loadSite();
  }, [user, isLoading, id]);

  const handleRotateApiKey = async (e) => {
    e.preventDefault();

    // Validate confirmation text
    if (confirmationText.toLowerCase() !== "rotate") {
      setRotateError('Please type "ROTATE" to confirm');
      return;
    }

    setIsRotating(true);
    setRotateError(null);

    console.log("[RotateApiKey] Rotating API key for site:", id);

    try {
      const result = await SiteService.rotateApiKey(id);
      console.log("[RotateApiKey] API key rotated successfully");
      setRotationResult(result);
    } catch (error) {
      console.error("[RotateApiKey] Failed to rotate API key:", error);
      setRotateError(error.message || "Failed to rotate API key. Please try again.");
      setIsRotating(false);
    }
  };

  const handleCopyApiKey = () => {
    if (rotationResult?.newApiKey) {
      navigator.clipboard.writeText(rotationResult.newApiKey);
      setApiKeyCopied(true);
      setTimeout(() => setApiKeyCopied(false), 3000);
    }
  };

  const handleDone = () => {
    navigate(`/sites/${id}`);
  };

  const handleCancel = () => {
    navigate(`/sites/${id}`);
  };

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

  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">
        {/* Back Button */}
        <button
          onClick={handleCancel}
          className="text-indigo-600 hover:text-indigo-700 font-medium mb-6 flex items-center gap-2"
        >
          <span>←</span>
          <span>Back to Site Details</span>
        </button>

        {/* Loading State */}
        {siteLoading && (
          <div className="bg-white rounded-2xl shadow-lg border border-gray-100 p-12 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 site details...</p>
          </div>
        )}

        {/* Error State */}
        {!siteLoading && siteError && (
          <div className="bg-white rounded-2xl shadow-lg border border-gray-100 p-12 text-center">
            <div className="w-20 h-20 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-6">
              <span className="text-4xl">⚠️</span>
            </div>
            <h2 className="text-2xl font-bold text-gray-900 mb-3">
              Failed to Load Site
            </h2>
            <p className="text-gray-600 mb-6">{siteError}</p>
            <div className="flex gap-3 justify-center">
              <button
                onClick={() => window.location.reload()}
                className="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"
              >
                Retry
              </button>
              <button
                onClick={() => navigate("/dashboard")}
                className="px-6 py-3 text-gray-700 border border-gray-300 rounded-lg
                         hover:bg-gray-50 transition-all font-medium"
              >
                Back to Dashboard
              </button>
            </div>
          </div>
        )}

        {/* Success State - Show New API Key */}
        {!siteLoading && !siteError && site && rotationResult && (
          <div className="bg-white rounded-2xl shadow-lg border border-green-200 overflow-hidden">
            {/* Success Header */}
            <div className="bg-gradient-to-r from-green-600 to-emerald-600 px-6 py-8">
              <div className="flex items-center gap-4">
                <div className="w-16 h-16 bg-white rounded-lg flex items-center justify-center text-4xl">
                  ✅
                </div>
                <div>
                  <h1 className="text-3xl font-bold text-white">
                    API Key Rotated Successfully
                  </h1>
                  <p className="text-green-100 mt-1">
                    Your new API key has been generated
                  </p>
                </div>
              </div>
            </div>

            {/* New API Key Display */}
            <div className="p-8">
              <div className="mb-6 p-6 bg-yellow-50 border-2 border-yellow-400 rounded-lg">
                <div className="flex items-start gap-3 mb-4">
                  <span className="text-3xl">⚠️</span>
                  <div className="flex-1">
                    <h3 className="font-bold text-yellow-900 text-lg mb-2">
                      Save Your New API Key Now!
                    </h3>
                    <p className="text-sm text-yellow-800 mb-2">
                      This is the <strong>only time</strong> you'll be able to see this API key.
                      Copy it now and update your WordPress plugin settings immediately.
                    </p>
                  </div>
                </div>

                {/* API Key Display with Copy Button */}
                <div className="bg-white border border-yellow-300 rounded-lg p-4">
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    New API Key:
                  </label>
                  <div className="flex gap-2">
                    <input
                      type="text"
                      value={rotationResult.newApiKey}
                      readOnly
                      className="flex-1 px-4 py-3 border border-gray-300 rounded-lg bg-gray-50 font-mono text-sm"
                    />
                    <button
                      onClick={handleCopyApiKey}
                      className="px-6 py-3 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700
                               transition-all font-medium whitespace-nowrap"
                    >
                      {apiKeyCopied ? "Copied!" : "Copy"}
                    </button>
                  </div>
                </div>
              </div>

              {/* Immediate Action Required */}
              <div className="mb-6 p-4 bg-red-50 border border-red-200 rounded-lg">
                <div className="flex items-start gap-3">
                  <span className="text-2xl">🚨</span>
                  <div className="flex-1">
                    <h4 className="font-semibold text-red-900 mb-2">
                      Old API Key Immediately Invalidated
                    </h4>
                    <p className="text-sm text-red-800 mb-2">
                      Your old API key (ending in <span className="font-mono font-bold">{rotationResult.oldKeyLastFour}</span>)
                      has been <strong>immediately deactivated</strong> and will no longer work.
                    </p>
                    <p className="text-sm text-red-800 mt-2">
                      You must update your WordPress plugin with the new API key <strong>right now</strong> to restore functionality.
                    </p>
                  </div>
                </div>
              </div>

              {/* Site Information */}
              <div className="mb-6 p-4 bg-gray-50 border border-gray-200 rounded-lg">
                <h4 className="font-semibold text-gray-900 mb-3">Site Details:</h4>
                <div className="space-y-2 text-sm">
                  <div className="flex items-center gap-2">
                    <span className="text-gray-600">Domain:</span>
                    <span className="font-semibold text-gray-900">{site.domain}</span>
                  </div>
                  <div className="flex items-center gap-2">
                    <span className="text-gray-600">Site URL:</span>
                    <span className="font-semibold text-gray-900">{site.siteUrl}</span>
                  </div>
                  <div className="flex items-center gap-2">
                    <span className="text-gray-600">Rotated At:</span>
                    <span className="font-semibold text-gray-900">{rotationResult.rotatedAt.toLocaleString()}</span>
                  </div>
                </div>
              </div>

              {/* Next Steps */}
              <div className="mb-6 p-4 bg-indigo-50 border border-indigo-200 rounded-lg">
                <div className="flex items-start gap-3">
                  <span className="text-2xl">📝</span>
                  <div className="flex-1">
                    <h4 className="font-semibold text-indigo-900 mb-2">
                      Next Steps
                    </h4>
                    <ol className="space-y-2 text-sm text-indigo-800">
                      <li>1. Copy the new API key using the button above</li>
                      <li>2. Log in to your WordPress admin panel</li>
                      <li>3. Go to Settings → MaplePress</li>
                      <li>4. Paste the new API key in the settings</li>
                      <li>5. Save the settings to activate the new key</li>
                    </ol>
                  </div>
                </div>
              </div>

              {/* Done Button */}
              <div className="flex gap-3">
                <button
                  onClick={handleDone}
                  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"
                >
                  Done - Return to Site Details
                </button>
              </div>
            </div>
          </div>
        )}

        {/* Rotation Confirmation Form */}
        {!siteLoading && !siteError && site && !rotationResult && (
          <div className="bg-white rounded-2xl shadow-lg border border-yellow-200 overflow-hidden">
            {/* Warning Header */}
            <div className="bg-gradient-to-r from-yellow-600 to-amber-600 px-6 py-8">
              <div className="flex items-center gap-4">
                <div className="w-16 h-16 bg-white rounded-lg flex items-center justify-center text-4xl">
                  🔑
                </div>
                <div>
                  <h1 className="text-3xl font-bold text-white">
                    Rotate API Key
                  </h1>
                  <p className="text-yellow-100 mt-1">
                    Generate a new API key for your site
                  </p>
                </div>
              </div>
            </div>

            {/* Rotation Form */}
            <div className="p-8">
              {/* Site Information */}
              <div className="mb-6 p-6 bg-gray-50 rounded-lg border border-gray-200">
                <h2 className="text-lg font-semibold text-gray-900 mb-4">
                  Site Information:
                </h2>
                <div className="space-y-3">
                  <div className="flex items-center gap-3">
                    <div className="w-12 h-12 bg-gradient-to-br from-indigo-500 to-blue-500 rounded-lg
                                  flex items-center justify-center text-white font-bold text-lg">
                      {site.domain[0]?.toUpperCase() || "W"}
                    </div>
                    <div>
                      <div className="font-semibold text-gray-900 flex items-center gap-2">
                        {site.domain}
                        {site.isVerified && (
                          <span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-green-100 text-green-800">
                            ✓ Verified
                          </span>
                        )}
                      </div>
                      <div className="text-sm text-gray-600">{site.siteUrl}</div>
                    </div>
                  </div>
                  <div className="mt-4 text-sm">
                    <span className="text-gray-600">Current API Key:</span>
                    <span className="ml-2 font-mono font-semibold text-gray-900">
                      {site.apiKeyPrefix}••••{site.apiKeyLastFour}
                    </span>
                  </div>
                </div>
              </div>

              {/* Warning Box */}
              <div className="mb-6 p-4 bg-red-50 border border-red-300 rounded-lg">
                <div className="flex items-start gap-3">
                  <span className="text-2xl">🚨</span>
                  <div className="flex-1">
                    <h3 className="font-semibold text-red-900 mb-2">
                      Critical: What Happens When You Rotate
                    </h3>
                    <ul className="space-y-1 text-sm text-red-800">
                      <li>• A new API key will be generated <strong>immediately</strong></li>
                      <li>• The old API key will be <strong>invalidated instantly</strong> - no grace period!</li>
                      <li>• Your WordPress site functionality will stop working until you update the key</li>
                      <li>• You must update your WordPress plugin settings with the new key right away</li>
                      <li>• The new key will be shown only once - save it immediately!</li>
                    </ul>
                  </div>
                </div>
              </div>

              {/* When to Rotate */}
              <div className="mb-6 p-4 bg-blue-50 border border-blue-200 rounded-lg">
                <div className="flex items-start gap-3">
                  <span className="text-2xl">💡</span>
                  <div className="flex-1">
                    <h4 className="font-semibold text-blue-900 mb-2">
                      When Should You Rotate Your API Key?
                    </h4>
                    <ul className="space-y-1 text-sm text-blue-800">
                      <li>• Your API key has been compromised or exposed</li>
                      <li>• You suspect unauthorized access to your site</li>
                      <li>• As part of regular security maintenance</li>
                      <li>• When removing access for a third party</li>
                    </ul>
                  </div>
                </div>
              </div>

              {/* Rotation Error */}
              {rotateError && (
                <div className="mb-6 p-4 bg-red-50 border border-red-200 rounded-lg">
                  <div className="flex items-start gap-3">
                    <span className="text-xl">❌</span>
                    <div className="flex-1">
                      <p className="text-sm text-red-800">{rotateError}</p>
                    </div>
                  </div>
                </div>
              )}

              {/* Confirmation Form */}
              <form onSubmit={handleRotateApiKey}>
                <div className="mb-6">
                  <label
                    htmlFor="confirmationText"
                    className="block text-sm font-medium text-gray-700 mb-2"
                  >
                    Type <span className="font-mono font-bold text-yellow-600">ROTATE</span> to confirm:
                  </label>
                  <input
                    type="text"
                    id="confirmationText"
                    value={confirmationText}
                    onChange={(e) => {
                      setConfirmationText(e.target.value);
                      setRotateError(null);
                    }}
                    className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-yellow-500 focus:border-transparent"
                    placeholder="ROTATE"
                    disabled={isRotating}
                    autoFocus
                  />
                  <p className="mt-1 text-sm text-gray-500">
                    Type "ROTATE" in capital letters to confirm the rotation
                  </p>
                </div>

                {/* Action Buttons */}
                <div className="flex gap-3">
                  <button
                    type="submit"
                    disabled={isRotating || confirmationText.toLowerCase() !== "rotate"}
                    className="flex-1 px-6 py-3 bg-yellow-600 text-white rounded-lg hover:bg-yellow-700
                             transition-all font-medium shadow-lg hover:shadow-xl
                             disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    {isRotating ? "Rotating API Key..." : "Rotate API Key"}
                  </button>
                  <button
                    type="button"
                    onClick={handleCancel}
                    disabled={isRotating}
                    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>
        )}
      </main>
    </div>
  );
}

export default RotateApiKey;
