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

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

/**
 * DeleteSite - Confirmation page for deleting a WordPress site
 */
function DeleteSite() {
  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 [isDeleting, setIsDeleting] = useState(false);
  const [deleteError, setDeleteError] = useState(null);
  const [confirmationText, setConfirmationText] = useState("");

  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("[DeleteSite] 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("[DeleteSite] 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("[DeleteSite] Loading site:", id);

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

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

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

    // Validate confirmation text
    if (confirmationText !== site.domain) {
      setDeleteError(`Please type "${site.domain}" to confirm deletion`);
      return;
    }

    setIsDeleting(true);
    setDeleteError(null);

    console.log("[DeleteSite] Deleting site:", id);

    try {
      await SiteService.deleteSite(id);
      console.log("[DeleteSite] Site deleted successfully");

      // Show success message and redirect to dashboard
      navigate("/dashboard", {
        state: {
          message: `Site "${site.domain}" has been deleted successfully`,
          type: "success"
        }
      });
    } catch (error) {
      console.error("[DeleteSite] Failed to delete site:", error);
      setDeleteError(error.message || "Failed to delete site. Please try again.");
      setIsDeleting(false);
    }
  };

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

        {/* Delete Confirmation Form */}
        {!siteLoading && !siteError && site && (
          <div className="bg-white rounded-2xl shadow-lg border border-red-200 overflow-hidden">
            {/* Warning Header */}
            <div className="bg-gradient-to-r from-red-600 to-red-700 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">
                    Delete Site
                  </h1>
                  <p className="text-red-100 mt-1">
                    This action cannot be undone
                  </p>
                </div>
              </div>
            </div>

            {/* Delete Form */}
            <div className="p-8">
              {/* Site Information */}
              <div className="mb-8 p-6 bg-gray-50 rounded-lg border border-gray-200">
                <h2 className="text-lg font-semibold text-gray-900 mb-4">
                  Site to be deleted:
                </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="grid grid-cols-2 gap-4 mt-4 text-sm">
                    <div>
                      <span className="text-gray-600">Pages Indexed:</span>
                      <span className="ml-2 font-semibold text-gray-900">{site.totalPagesIndexed}</span>
                    </div>
                    <div>
                      <span className="text-gray-600">Search Requests:</span>
                      <span className="ml-2 font-semibold text-gray-900">{site.searchRequestsCount}</span>
                    </div>
                    <div>
                      <span className="text-gray-600">Storage Used:</span>
                      <span className="ml-2 font-semibold text-gray-900">
                        {SiteService.formatStorage(site.storageUsedBytes)}
                      </span>
                    </div>
                    <div>
                      <span className="text-gray-600">Created:</span>
                      <span className="ml-2 font-semibold text-gray-900">
                        {site.createdAt.toLocaleDateString()}
                      </span>
                    </div>
                  </div>
                </div>
              </div>

              {/* Warning Box */}
              <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">
                    <h3 className="font-semibold text-red-900 mb-2">
                      Warning: This action is permanent
                    </h3>
                    <ul className="space-y-1 text-sm text-red-800">
                      <li>• All indexed pages will be permanently deleted</li>
                      <li>• Search index will be destroyed</li>
                      <li>• All usage statistics will be lost</li>
                      <li>• API key will be revoked immediately</li>
                      <li>• This action cannot be undone</li>
                    </ul>
                  </div>
                </div>
              </div>

              {/* Delete Error */}
              {deleteError && (
                <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">{deleteError}</p>
                    </div>
                  </div>
                </div>
              )}

              {/* Confirmation Form */}
              <form onSubmit={handleDeleteSite}>
                <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-red-600">{site.domain}</span> to confirm deletion:
                  </label>
                  <input
                    type="text"
                    id="confirmationText"
                    value={confirmationText}
                    onChange={(e) => {
                      setConfirmationText(e.target.value);
                      setDeleteError(null);
                    }}
                    className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-red-500 focus:border-transparent"
                    placeholder={site.domain}
                    disabled={isDeleting}
                    autoFocus
                  />
                  <p className="mt-1 text-sm text-gray-500">
                    Please type the domain name exactly as shown above to confirm
                  </p>
                </div>

                {/* Action Buttons */}
                <div className="flex gap-3">
                  <button
                    type="submit"
                    disabled={isDeleting || confirmationText !== site.domain}
                    className="flex-1 px-6 py-3 bg-red-600 text-white rounded-lg hover:bg-red-700
                             transition-all font-medium shadow-lg hover:shadow-xl
                             disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    {isDeleting ? "Deleting Site..." : "Delete Site Permanently"}
                  </button>
                  <button
                    type="button"
                    onClick={handleCancel}
                    disabled={isDeleting}
                    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>

              {/* Additional Information */}
              <div className="mt-6 p-4 bg-blue-50 border border-blue-200 rounded-lg">
                <div className="flex items-start gap-3">
                  <span className="text-xl">💡</span>
                  <div className="flex-1">
                    <h4 className="font-semibold text-blue-900 mb-1">
                      Need to reconnect later?
                    </h4>
                    <p className="text-sm text-blue-800">
                      If you delete this site and want to reconnect it later, you'll need to register
                      it again and configure a new API key in your WordPress plugin.
                    </p>
                  </div>
                </div>
              </div>
            </div>
          </div>
        )}
      </main>
    </div>
  );
}

export default DeleteSite;
