// File: src/pages/Dashboard/Dashboard.jsx

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

/**
 * Dashboard - Launch page for managing WordPress sites
 */
function Dashboard() {
  const navigate = useNavigate();
  const { authManager } = useAuth();
  const [user, setUser] = useState(null);
  const [isLoading, setIsLoading] = useState(true);
  const [sites, setSites] = useState([]);
  const [sitesLoading, setSitesLoading] = useState(false);
  const [sitesError, setSitesError] = useState(null);

  useEffect(() => {
    console.log("[Dashboard] 🔒 Checking authentication...");

    // Wait for AuthManager to initialize before checking authentication
    const checkAuth = async () => {
      const isInitialized = authManager.getIsInitialized();
      console.log("[Dashboard] 🔧 AuthManager initialization status:", {
        isInitialized,
      });

      if (!isInitialized) {
        console.log("[Dashboard] ⏳ Waiting for AuthManager to initialize...");
        // Check again in 50ms
        setTimeout(checkAuth, 50);
        return;
      }

      // Now safe to check authentication
      const isAuth = authManager.isAuthenticated();
      console.log("[Dashboard] 🔍 Authentication check result:", {
        isAuthenticated: isAuth,
        hasAccessToken: !!authManager.getAccessToken(),
        hasUser: !!authManager.getUser(),
      });

      if (!isAuth) {
        console.log("[Dashboard] ⚠️ Not authenticated, redirecting to login");
        setIsLoading(false);
        navigate("/login");
        return;
      }

      // Proactively refresh token if needed BEFORE showing dashboard
      try {
        console.log("[Dashboard] 🔄 Ensuring token is valid...");
        await authManager.ensureValidToken();
        console.log("[Dashboard] ✅ Token is valid and ready");
      } catch (error) {
        console.error("[Dashboard] ❌ Token refresh failed on mount:", error);
        // Token refresh failed, redirect to login
        setIsLoading(false);
        navigate("/login");
        return;
      }

      // Get user data
      const userData = authManager.getUser();
      console.log("[Dashboard] ✅ User authenticated, loading user data:", {
        email: userData?.email,
        role: userData?.role,
      });
      setUser(userData);
      setIsLoading(false);
    };

    // Start the authentication check
    checkAuth();
  }, [authManager, navigate]);

  // Load sites after authentication is complete
  useEffect(() => {
    if (!user || isLoading) {
      return;
    }

    const loadSites = async () => {
      setSitesLoading(true);
      setSitesError(null);

      console.log("[Dashboard] 📋 Loading sites...");

      try {
        const response = await SiteService.listSites({ pageSize: 50 });
        console.log("[Dashboard] ✅ Sites loaded:", response.sites.length);
        setSites(response.sites);
      } catch (error) {
        console.error("[Dashboard] ❌ Failed to load sites:", error);
        setSitesError(error.message || "Failed to load sites");
      } finally {
        setSitesLoading(false);
      }
    };

    loadSites();
  }, [user, isLoading]);

  // Background token refresh - check every 60 seconds
  // The AuthManager will only refresh if token expires within 1 minute
  useEffect(() => {
    console.log("[Dashboard] 🔁 Setting up background token refresh (every 60s)");

    const refreshInterval = setInterval(async () => {
      if (!authManager.getIsInitialized()) {
        return;
      }

      // Check if we're still authenticated (refresh token still valid)
      if (!authManager.isAuthenticated()) {
        console.warn("[Dashboard] ⚠️ Refresh token expired, redirecting to login");
        clearInterval(refreshInterval);
        navigate("/login");
        return;
      }

      try {
        // This will refresh the token if it's expiring soon (within 1 minute)
        await authManager.ensureValidToken();
      } catch (error) {
        console.error("[Dashboard] ❌ Background token refresh failed:", error);
        // Token refresh failed, redirect to login
        clearInterval(refreshInterval);
        navigate("/login");
      }
    }, 60000); // Check every 60 seconds (access token expires in 15 minutes)

    return () => {
      console.log("[Dashboard] 🛑 Cleaning up background token refresh");
      clearInterval(refreshInterval);
    };
  }, [authManager, navigate]);

  const handleLogout = async () => {
    await authManager.logout();
    navigate("/");
  };

  // 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 */}
            <div className="flex items-center gap-2">
              <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>
            </div>

            {/* User Menu */}
            <div className="flex items-center gap-4">
              <div className="hidden sm: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>
              <button
                onClick={handleLogout}
                className="px-4 py-2 text-sm font-medium text-gray-700 hover:text-gray-900
                         border border-gray-300 rounded-lg hover:bg-gray-50 transition-all"
              >
                Sign Out
              </button>
            </div>
          </div>
        </div>
      </nav>

      {/* Main Content */}
      <main className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
        {/* Welcome Section */}
        <div className="text-center mb-12">
          <h1 className="text-4xl font-bold text-gray-900 mb-4">
            Welcome to MaplePress
          </h1>
          <p className="text-xl text-gray-600">
            Cloud services platform for your WordPress sites
          </p>
        </div>

        {/* Sites Section */}
        <div className="bg-white rounded-2xl shadow-lg border border-gray-100 overflow-hidden mb-8">
          {/* Section Header */}
          <div className="bg-gradient-to-r from-indigo-600 to-blue-600 px-6 py-4 flex items-center justify-between">
            <div className="flex items-center gap-3">
              <span className="text-2xl">🌐</span>
              <h2 className="text-xl font-bold text-white">Your WordPress Sites</h2>
            </div>
            <button
              onClick={() => navigate("/sites/add")}
              className="px-4 py-2 bg-white text-indigo-600 rounded-lg hover:bg-indigo-50
                             transition-all font-medium text-sm flex items-center gap-2"
            >
              <span>➕</span>
              <span>Add Site</span>
            </button>
          </div>

          {/* Loading State */}
          {sitesLoading && (
            <div className="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 your sites...</p>
            </div>
          )}

          {/* Error State */}
          {!sitesLoading && sitesError && (
            <div className="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>
              <h3 className="text-xl font-semibold text-gray-900 mb-3">
                Failed to Load Sites
              </h3>
              <p className="text-gray-600 mb-6 max-w-md mx-auto">{sitesError}</p>
              <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 shadow-lg hover:shadow-xl"
              >
                Retry
              </button>
            </div>
          )}

          {/* Empty State */}
          {!sitesLoading && !sitesError && sites.length === 0 && (
            <div className="p-12 text-center">
              <div className="w-20 h-20 bg-gradient-to-br from-indigo-100 to-blue-100 rounded-full
                            flex items-center justify-center mx-auto mb-6">
                <span className="text-4xl">🚀</span>
              </div>
              <h3 className="text-xl font-semibold text-gray-900 mb-3">
                No sites connected yet
              </h3>
              <p className="text-gray-600 mb-6 max-w-md mx-auto">
                Get started by connecting your first WordPress site to unlock cloud-powered search,
                analytics, and more.
              </p>
              <button
                onClick={() => navigate("/sites/add")}
                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 shadow-lg hover:shadow-xl"
              >
                Connect Your First Site
              </button>
            </div>
          )}

          {/* Site List */}
          {!sitesLoading && !sitesError && sites.length > 0 && (
            <div className="divide-y divide-gray-100">
              {sites.map((site) => (
                <div
                  key={site.id}
                  className="p-6 hover:bg-gray-50 transition-all flex items-center justify-between"
                >
                  <div className="flex items-center gap-4">
                    <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>
                      <h3 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>
                        )}
                        {!site.isVerified && (
                          <span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-yellow-100 text-yellow-800">
                            Pending
                          </span>
                        )}
                      </h3>
                      <p className="text-sm text-gray-600">
                        Status: {site.status} • Added {site.createdAt.toLocaleDateString()}
                      </p>
                    </div>
                  </div>
                  <button
                    onClick={() => navigate(`/sites/${site.id}`)}
                    className="px-4 py-2 text-sm font-medium text-indigo-600 hover:text-indigo-700
                             border border-indigo-200 rounded-lg hover:bg-indigo-50 transition-all"
                  >
                    Manage
                  </button>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* Getting Started Guide */}
        <div className="bg-gradient-to-r from-indigo-50 to-blue-50 rounded-2xl p-8
                       border border-indigo-100">
          <div className="flex items-start gap-4">
            <div className="text-4xl">💡</div>
            <div className="flex-1">
              <h3 className="text-xl font-semibold text-gray-900 mb-3">
                Getting Started
              </h3>
              <p className="text-gray-700 mb-4">
                To connect your WordPress site to MaplePress:
              </p>
              <ol className="space-y-2 text-gray-700 mb-6">
                <li className="flex items-start gap-2">
                  <span className="font-semibold text-indigo-600">1.</span>
                  <span>Install the MaplePress plugin on your WordPress site</span>
                </li>
                <li className="flex items-start gap-2">
                  <span className="font-semibold text-indigo-600">2.</span>
                  <span>Enter your API credentials from the plugin settings</span>
                </li>
                <li className="flex items-start gap-2">
                  <span className="font-semibold text-indigo-600">3.</span>
                  <span>Your site will appear here once connected</span>
                </li>
              </ol>
              <div className="flex gap-3">
                <button className="px-4 py-2 bg-indigo-600 text-white rounded-lg
                                 hover:bg-indigo-700 transition-all font-medium">
                  Download Plugin
                </button>
                <button className="px-4 py-2 text-indigo-600 border border-indigo-200 rounded-lg
                                 hover:bg-white transition-all font-medium">
                  View Documentation
                </button>
              </div>
            </div>
          </div>
        </div>
      </main>
    </div>
  );
}

export default Dashboard;
