// File Path: monorepo/native/desktop/maplefile/frontend/src/pages/User/Dashboard/Dashboard.jsx
import { useState, useEffect } from "react";
import { Link } from "react-router-dom";
import Navigation from "../../../components/Navigation";
import Page from "../../../components/Page";
import { GetDashboardData } from "../../../../wailsjs/go/app/Application";
import "./Dashboard.css";

function Dashboard() {
  const [dashboardData, setDashboardData] = useState(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    // Wait for Wails runtime to be ready before loading data
    let attempts = 0;
    const maxAttempts = 50; // 5 seconds max (50 * 100ms)
    let isCancelled = false; // Prevent race conditions

    const checkWailsReady = () => {
      if (isCancelled) return;

      if (window.go && window.go.app && window.go.app.Application) {
        loadDashboardData();
      } else if (attempts < maxAttempts) {
        attempts++;
        setTimeout(checkWailsReady, 100);
      } else {
        // Timeout - show error
        if (!isCancelled) {
          setIsLoading(false);
          setError("Failed to initialize Wails runtime. Please restart the application.");
        }
      }
    };

    checkWailsReady();

    // Cleanup function to prevent race conditions with StrictMode
    return () => {
      isCancelled = true;
    };
  }, []);

  const loadDashboardData = async (retryCount = 0) => {
    const maxRetries = 2;

    try {
      setIsLoading(true);
      setError(null);

      // Check if Wails runtime is available
      if (!window.go || !window.go.app || !window.go.app.Application) {
        throw new Error("Wails runtime not initialized. Please refresh the page.");
      }

      console.log("Fetching dashboard data...", retryCount > 0 ? `(retry ${retryCount})` : "");

      // First check if we're actually logged in
      const { IsLoggedIn } = await import("../../../../wailsjs/go/app/Application");
      const loggedIn = await IsLoggedIn();
      console.log("IsLoggedIn:", loggedIn);

      if (!loggedIn) {
        throw new Error("You are not logged in. Please log in first.");
      }

      const data = await GetDashboardData();
      console.log("Dashboard data received:", data);
      setDashboardData(data);
      setError(null); // Clear any previous errors
    } catch (err) {
      console.error("Failed to load dashboard - Full error:", err);
      console.error("Error name:", err.name);
      console.error("Error message:", err.message);

      // Retry logic for token refresh scenarios
      const isTokenError = err.message && (
        err.message.includes("Invalid or expired token") ||
        err.message.includes("token") ||
        err.message.includes("Unauthorized")
      );

      if (isTokenError && retryCount < maxRetries) {
        console.log(`Token error detected, retrying in 500ms... (attempt ${retryCount + 1}/${maxRetries})`);
        // Wait a bit for token refresh to complete, then retry
        setTimeout(() => loadDashboardData(retryCount + 1), 500);
        return; // Don't set error yet, we're retrying
      }

      // Show more detailed error message
      let errorMsg = err.message || "Failed to load dashboard data";
      if (err.toString) {
        errorMsg = err.toString();
      }
      setError(errorMsg);
      setIsLoading(false);
    } finally {
      // Only set loading to false if we're not retrying
      if (retryCount >= maxRetries || !error) {
        setIsLoading(false);
      }
    }
  };

  const handleRefresh = () => {
    loadDashboardData();
  };

  const getTimeAgo = (dateString) => {
    if (!dateString) return "Recently";
    const now = new Date();
    const date = new Date(dateString);
    const diffInMinutes = Math.floor((now - date) / (1000 * 60));

    if (diffInMinutes < 1) return "Just now";
    if (diffInMinutes < 60) return `${diffInMinutes} min ago`;
    if (diffInMinutes < 1440) {
      const hours = Math.floor(diffInMinutes / 60);
      return `${hours} hour${hours > 1 ? "s" : ""} ago`;
    }
    if (diffInMinutes < 2880) return "Yesterday";
    const days = Math.floor(diffInMinutes / 1440);
    return `${days} day${days > 1 ? "s" : ""} ago`;
  };

  if (isLoading) {
    return (
      <div className="layout">
        <Navigation />
        <div className="main-content">
          <Page title="Dashboard">
            <div style={{ textAlign: "center", padding: "40px" }}>
              <p>Loading dashboard...</p>
            </div>
          </Page>
        </div>
      </div>
    );
  }

  if (error) {
    const isTokenError = error.includes("token") || error.includes("Unauthorized");

    return (
      <div className="layout">
        <Navigation />
        <div className="main-content">
          <Page title="Dashboard">
            <div style={{ padding: "20px", color: "#e74c3c" }}>
              <h3>Error Loading Dashboard</h3>
              <p>{error}</p>
              {isTokenError && (
                <p style={{ marginTop: "10px", fontSize: "14px", color: "#7f8c8d" }}>
                  Your session may have expired. Please try logging out and logging back in.
                </p>
              )}
              <div style={{ marginTop: "20px", display: "flex", gap: "10px" }}>
                <button onClick={handleRefresh} className="nav-button">
                  Try Again
                </button>
                {isTokenError && (
                  <button
                    onClick={async () => {
                      const { Logout } = await import("../../../../wailsjs/go/app/Application");
                      await Logout();
                      window.location.href = "/";
                    }}
                    className="nav-button danger"
                  >
                    Logout
                  </button>
                )}
              </div>
            </div>
          </Page>
        </div>
      </div>
    );
  }

  if (!dashboardData) {
    return (
      <div className="layout">
        <Navigation />
        <div className="main-content">
          <Page title="Dashboard">
            <p>No dashboard data available.</p>
          </Page>
        </div>
      </div>
    );
  }

  const { summary, storage_usage_trend, recent_files } = dashboardData;

  return (
    <div className="layout">
      <Navigation />
      <div className="main-content">
        <Page title="Dashboard">
          {/* Header with refresh button */}
          <div
            style={{
              display: "flex",
              justifyContent: "space-between",
              alignItems: "center",
              marginBottom: "20px",
            }}
          >
            <div>
              <h2 style={{ margin: 0 }}>Welcome Back!</h2>
              <p style={{ color: "#7f8c8d", margin: "5px 0 0 0" }}>
                Here's what's happening with your files today
              </p>
            </div>
            <button onClick={handleRefresh} className="nav-button secondary">
              Refresh
            </button>
          </div>

          {/* Summary Statistics */}
          <div
            style={{
              display: "grid",
              gridTemplateColumns: "repeat(auto-fit, minmax(200px, 1fr))",
              gap: "20px",
              marginBottom: "30px",
            }}
          >
            <div className="stat-card">
              <div className="stat-label">Total Files</div>
              <div className="stat-value">{summary.total_files}</div>
            </div>
            <div className="stat-card">
              <div className="stat-label">Total Folders</div>
              <div className="stat-value">{summary.total_folders}</div>
            </div>
            <div className="stat-card">
              <div className="stat-label">Storage Used</div>
              <div className="stat-value">{summary.storage_used}</div>
            </div>
            <div className="stat-card">
              <div className="stat-label">Storage Limit</div>
              <div className="stat-value">{summary.storage_limit}</div>
            </div>
          </div>

          {/* Storage Usage Percentage */}
          <div
            style={{
              marginBottom: "30px",
              padding: "20px",
              background: "white",
              borderRadius: "8px",
              boxShadow: "0 2px 4px rgba(0,0,0,0.1)",
            }}
          >
            <h3 style={{ marginTop: 0 }}>Storage Usage</h3>
            <div
              style={{
                background: "#ecf0f1",
                borderRadius: "10px",
                height: "30px",
                overflow: "hidden",
                position: "relative",
              }}
            >
              <div
                style={{
                  background:
                    summary.storage_usage_percentage > 80
                      ? "#e74c3c"
                      : summary.storage_usage_percentage > 50
                        ? "#f39c12"
                        : "#27ae60",
                  height: "100%",
                  width: `${Math.min(summary.storage_usage_percentage, 100)}%`,
                  transition: "width 0.3s ease",
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center",
                  color: "white",
                  fontWeight: "bold",
                }}
              >
                {summary.storage_usage_percentage}%
              </div>
            </div>
            <div
              style={{
                display: "flex",
                justifyContent: "space-between",
                marginTop: "10px",
                fontSize: "14px",
                color: "#7f8c8d",
              }}
            >
              <span>{summary.storage_used} used</span>
              <span>{summary.storage_limit} total</span>
            </div>
          </div>

          {/* Storage Usage Trend */}
          {storage_usage_trend &&
            storage_usage_trend.data_points &&
            storage_usage_trend.data_points.length > 0 && (
              <div
                style={{
                  marginBottom: "30px",
                  padding: "20px",
                  background: "white",
                  borderRadius: "8px",
                  boxShadow: "0 2px 4px rgba(0,0,0,0.1)",
                }}
              >
                <h3 style={{ marginTop: 0 }}>
                  Storage Trend ({storage_usage_trend.period})
                </h3>
                <div
                  style={{
                    display: "grid",
                    gridTemplateColumns: `repeat(${storage_usage_trend.data_points.length}, 1fr)`,
                    gap: "10px",
                    marginTop: "20px",
                  }}
                >
                  {storage_usage_trend.data_points.map((point, index) => (
                    <div
                      key={index}
                      style={{ textAlign: "center", fontSize: "12px" }}
                    >
                      <div
                        style={{
                          color: "#7f8c8d",
                          marginBottom: "5px",
                          fontWeight: "500",
                        }}
                      >
                        {point.usage}
                      </div>
                      <div style={{ color: "#95a5a6" }}>
                        {new Date(point.date).toLocaleDateString("en-US", {
                          month: "short",
                          day: "numeric",
                        })}
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            )}

          {/* Recent Files */}
          <div
            style={{
              marginBottom: "30px",
              padding: "20px",
              background: "white",
              borderRadius: "8px",
              boxShadow: "0 2px 4px rgba(0,0,0,0.1)",
            }}
          >
            <div
              style={{
                display: "flex",
                justifyContent: "space-between",
                alignItems: "center",
                marginBottom: "15px",
              }}
            >
              <h3 style={{ margin: 0 }}>Recent Files</h3>
              <Link to="/file-manager" style={{ fontSize: "14px" }}>
                View All →
              </Link>
            </div>

            {recent_files && recent_files.length > 0 ? (
              <div style={{ display: "flex", flexDirection: "column", gap: "10px" }}>
                {recent_files.slice(0, 5).map((file) => {
                  // Determine sync status badge
                  const getSyncStatusBadge = (syncStatus) => {
                    switch (syncStatus) {
                      case "synced":
                        return { label: "Synced", color: "#27ae60", bgColor: "#d4edda" };
                      case "local_only":
                        return { label: "Local", color: "#3498db", bgColor: "#d1ecf1" };
                      case "cloud_only":
                        return { label: "Cloud", color: "#9b59b6", bgColor: "#e2d9f3" };
                      case "modified_locally":
                        return { label: "Modified", color: "#f39c12", bgColor: "#fff3cd" };
                      default:
                        return { label: "Unknown", color: "#7f8c8d", bgColor: "#e9ecef" };
                    }
                  };

                  const syncBadge = getSyncStatusBadge(file.sync_status);

                  return (
                    <div
                      key={file.id}
                      style={{
                        display: "flex",
                        justifyContent: "space-between",
                        alignItems: "center",
                        padding: "12px",
                        background: "#f8f9fa",
                        borderRadius: "6px",
                        border: "1px solid #e9ecef",
                      }}
                    >
                      <div style={{ flex: 1 }}>
                        <div
                          style={{
                            display: "flex",
                            alignItems: "center",
                            gap: "8px",
                            marginBottom: "4px",
                          }}
                        >
                          <span
                            style={{
                              fontWeight: "500",
                              color: file.is_decrypted ? "#2c3e50" : "#95a5a6",
                            }}
                          >
                            {file.is_decrypted ? file.name : "🔒 " + file.name}
                          </span>
                          <span
                            style={{
                              fontSize: "10px",
                              padding: "2px 6px",
                              borderRadius: "4px",
                              backgroundColor: syncBadge.bgColor,
                              color: syncBadge.color,
                              fontWeight: "600",
                            }}
                          >
                            {syncBadge.label}
                          </span>
                        </div>
                        <div
                          style={{ fontSize: "12px", color: "#7f8c8d" }}
                        >
                          {file.size} • {getTimeAgo(file.created_at)}
                        </div>
                      </div>
                      <Link
                        to={`/file-manager/files/${file.id}`}
                        className="nav-button secondary"
                        style={{
                          padding: "6px 12px",
                          fontSize: "12px",
                          textDecoration: "none",
                        }}
                      >
                        View
                      </Link>
                    </div>
                  );
                })}
              </div>
            ) : (
              <div style={{ textAlign: "center", padding: "20px", color: "#7f8c8d" }}>
                <p>No recent files found</p>
              </div>
            )}
          </div>

          {/* Quick Actions */}
          <h3>Quick Actions</h3>
          <div className="nav-buttons">
            <Link to="/file-manager" className="nav-button">
              Manage Files
            </Link>
            <Link to="/file-manager/upload" className="nav-button success">
              Upload File
            </Link>
            <Link
              to="/file-manager/collections/create"
              className="nav-button success"
            >
              Create Collection
            </Link>
            <Link to="/me" className="nav-button secondary">
              View Profile
            </Link>
          </div>
        </Page>
      </div>
    </div>
  );
}

export default Dashboard;
