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

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

/**
 * SiteDetail - Detailed view of a WordPress site with management options
 */
function SiteDetail() {
  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);

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

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

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

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

  const handleNavigateToRotateKey = () => {
    navigate(`/sites/${id}/rotate-key`);
  };

  // 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-5xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
        {/* Back Button */}
        <button
          onClick={() => navigate("/dashboard")}
          className="text-indigo-600 hover:text-indigo-700 font-medium mb-6 flex items-center gap-2"
        >
          <span>←</span>
          <span>Back to Dashboard</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>
        )}

        {/* Site Details */}
        {!siteLoading && !siteError && site && (
          <div className="space-y-6">
            {/* Site Header */}
            <div className="bg-white rounded-2xl shadow-lg border border-gray-100 overflow-hidden">
              <div className="bg-gradient-to-r from-indigo-600 to-blue-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-indigo-600 font-bold text-2xl">
                    {site.domain[0]?.toUpperCase() || "W"}
                  </div>
                  <div>
                    <h1 className="text-3xl font-bold text-white flex items-center gap-3">
                      {site.domain}
                      {site.isVerified && (
                        <span className="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-green-400 text-green-900">
                          ✓ Verified
                        </span>
                      )}
                      {!site.isVerified && (
                        <span className="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-yellow-400 text-yellow-900">
                          Pending Verification
                        </span>
                      )}
                    </h1>
                    <p className="text-indigo-100 mt-1">{site.siteUrl}</p>
                  </div>
                </div>
              </div>
            </div>

            {/* Site Information */}
            <div className="bg-white rounded-2xl shadow-lg border border-gray-100 overflow-hidden">
              <div className="px-6 py-4 border-b border-gray-200">
                <h2 className="text-xl font-bold text-gray-900">Site Information</h2>
              </div>
              <div className="p-6">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <div>
                    <label className="block text-sm font-medium text-gray-500 mb-1">Site ID</label>
                    <p className="text-gray-900 font-mono text-sm">{site.id}</p>
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-500 mb-1">Status</label>
                    <p className="text-gray-900">{site.status}</p>
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-500 mb-1">API Key</label>
                    <p className="text-gray-900 font-mono text-sm">
                      {site.apiKeyPrefix}••••{site.apiKeyLastFour}
                    </p>
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-500 mb-1">Search Index</label>
                    <p className="text-gray-900 font-mono text-sm">{site.searchIndexName}</p>
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-500 mb-1">Created</label>
                    <p className="text-gray-900">{site.createdAt.toLocaleString()}</p>
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-500 mb-1">Last Updated</label>
                    <p className="text-gray-900">{site.updatedAt.toLocaleString()}</p>
                  </div>
                </div>
              </div>
            </div>

            {/* Usage Statistics */}
            <div className="bg-white rounded-2xl shadow-lg border border-gray-100 overflow-hidden">
              <div className="px-6 py-4 border-b border-gray-200">
                <h2 className="text-xl font-bold text-gray-900">Usage Statistics</h2>
              </div>
              <div className="p-6">
                <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                  <div className="text-center p-4 bg-gradient-to-br from-indigo-50 to-blue-50 rounded-lg">
                    <div className="text-3xl font-bold text-indigo-600">{site.totalPagesIndexed}</div>
                    <div className="text-sm text-gray-600 mt-1">Total Pages Indexed</div>
                  </div>
                  <div className="text-center p-4 bg-gradient-to-br from-green-50 to-emerald-50 rounded-lg">
                    <div className="text-3xl font-bold text-green-600">{site.searchRequestsCount}</div>
                    <div className="text-sm text-gray-600 mt-1">Search Requests</div>
                  </div>
                  <div className="text-center p-4 bg-gradient-to-br from-purple-50 to-pink-50 rounded-lg">
                    <div className="text-3xl font-bold text-purple-600">
                      {SiteService.formatStorage(site.storageUsedBytes)}
                    </div>
                    <div className="text-sm text-gray-600 mt-1">Storage Used</div>
                  </div>
                </div>
                {site.lastIndexedAt && (
                  <div className="mt-4 text-center text-sm text-gray-600">
                    Last indexed: {site.lastIndexedAt.toLocaleString()}
                  </div>
                )}
                {site.pluginVersion && (
                  <div className="mt-2 text-center text-sm text-gray-600">
                    Plugin version: {site.pluginVersion}
                  </div>
                )}
              </div>
            </div>

            {/* Actions */}
            <div className="bg-white rounded-2xl shadow-lg border border-gray-100 overflow-hidden">
              <div className="px-6 py-4 border-b border-gray-200">
                <h2 className="text-xl font-bold text-gray-900">Site Management</h2>
              </div>
              <div className="p-6 space-y-4">
                {/* Rotate API Key */}
                <div className="flex items-center justify-between p-4 border border-gray-200 rounded-lg">
                  <div>
                    <h3 className="font-semibold text-gray-900">Rotate API Key</h3>
                    <p className="text-sm text-gray-600">
                      Generate a new API key if the current one is compromised
                    </p>
                  </div>
                  <button
                    onClick={handleNavigateToRotateKey}
                    className="px-4 py-2 bg-yellow-600 text-white rounded-lg hover:bg-yellow-700
                             transition-all font-medium"
                  >
                    Rotate Key
                  </button>
                </div>

                {/* Delete Site */}
                <div className="flex items-center justify-between p-4 border border-red-200 rounded-lg bg-red-50">
                  <div>
                    <h3 className="font-semibold text-gray-900">Delete Site</h3>
                    <p className="text-sm text-gray-600">
                      Permanently delete this site and all associated data
                    </p>
                  </div>
                  <button
                    onClick={handleNavigateToDelete}
                    className="px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700
                             transition-all font-medium"
                  >
                    Delete Site
                  </button>
                </div>
              </div>
            </div>
          </div>
        )}
      </main>
    </div>
  );
}

export default SiteDetail;
