// File Path: monorepo/native/desktop/maplefile/frontend/src/pages/User/FileManager/Files/FileDetails.jsx
import { useState, useEffect, useCallback } from "react";
import { useNavigate, useParams } from "react-router-dom";
import Navigation from "../../../../components/Navigation";
import Page from "../../../../components/Page";
import {
  GetFile,
  DeleteFile,
  DownloadFile,
  OnloadFile,
  OpenFile,
  OffloadFile,
  ListTags,
  AssignTagToFile,
  UnassignTagFromFile,
} from "../../../../../wailsjs/go/app/Application";
import "../../Dashboard/Dashboard.css";

function FileDetails() {
  const navigate = useNavigate();
  const { fileId } = useParams();

  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState("");
  const [file, setFile] = useState(null);
  const [isDeleting, setIsDeleting] = useState(false);
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  const [isDownloading, setIsDownloading] = useState(false);
  const [isOnloading, setIsOnloading] = useState(false);
  const [isOpening, setIsOpening] = useState(false);
  const [isOffloading, setIsOffloading] = useState(false);
  const [showTagEditor, setShowTagEditor] = useState(false);
  const [allTags, setAllTags] = useState([]);
  const [isLoadingTags, setIsLoadingTags] = useState(false);
  const [isUpdatingTags, setIsUpdatingTags] = useState(false);

  // Load file details
  const loadFile = useCallback(async () => {
    setIsLoading(true);
    setError("");

    try {
      console.log("Loading file details...", fileId);
      const fileData = await GetFile(fileId);
      console.log("File loaded:", fileData);
      setFile(fileData);
    } catch (err) {
      console.error("Failed to load file:", err);
      setError(err.message || "Failed to load file");
    } finally {
      setIsLoading(false);
    }
  }, [fileId]);

  // Initial load - wait for Wails to be ready
  useEffect(() => {
    if (typeof window !== 'undefined' && window.go && window.go.app && window.go.app.Application) {
      loadFile();
    } else {
      const checkWails = setInterval(() => {
        if (window.go && window.go.app && window.go.app.Application) {
          clearInterval(checkWails);
          loadFile();
        }
      }, 100);

      setTimeout(() => clearInterval(checkWails), 10000);
      return () => clearInterval(checkWails);
    }
  }, [loadFile]);

  // Helper functions
  const formatFileSize = (bytes) => {
    if (!bytes) return "0 B";
    const sizes = ["B", "KB", "MB", "GB", "TB"];
    const i = Math.floor(Math.log(bytes) / Math.log(1024));
    return `${(bytes / Math.pow(1024, i)).toFixed(i > 0 ? 2 : 0)} ${sizes[i]}`;
  };

  const formatDate = (dateString) => {
    if (!dateString) return "Unknown";
    const date = new Date(dateString);
    return date.toLocaleString();
  };

  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 < 60) return "Just now";
    if (diffInMinutes < 1440) return "Today";
    if (diffInMinutes < 2880) return "Yesterday";
    const diffInDays = Math.floor(diffInMinutes / 1440);
    if (diffInDays < 7) return `${diffInDays} days ago`;
    if (diffInDays < 30) return `${Math.floor(diffInDays / 7)} weeks ago`;
    return `${Math.floor(diffInDays / 30)} months ago`;
  };

  const getStateIcon = (state) => {
    switch (state) {
      case "active":
        return "[A]";
      case "archived":
        return "[R]";
      case "deleted":
        return "[D]";
      default:
        return "[?]";
    }
  };

  const getStateLabel = (state) => {
    switch (state) {
      case "active":
        return "Active";
      case "archived":
        return "Archived";
      case "deleted":
        return "Deleted";
      default:
        return "Unknown";
    }
  };

  // Get sync status icon and color
  const getSyncStatusInfo = (syncStatus) => {
    switch (syncStatus) {
      case "cloud_only":
        return { icon: "☁️", color: "#2196f3", label: "Cloud Only", tooltip: "File is in the cloud, not downloaded locally" };
      case "local_only":
        return { icon: "💻", color: "#9c27b0", label: "Local Only", tooltip: "File exists only locally, not uploaded to cloud" };
      case "synced":
        return { icon: "✓", color: "#4caf50", label: "Synced", tooltip: "File is synchronized between local and cloud" };
      case "modified_locally":
        return { icon: "⬆️", color: "#ff9800", label: "Modified", tooltip: "Local changes pending upload to cloud" };
      default:
        return { icon: "☁️", color: "#2196f3", label: "Cloud Only", tooltip: "File is in the cloud" };
    }
  };

  // Handle onload file (download for offline access)
  const handleOnload = async () => {
    setIsOnloading(true);
    setError("");
    try {
      console.log("Onloading file for offline access:", fileId);
      const result = await OnloadFile(fileId);
      console.log("File onloaded:", result);
      // Refresh file details to update sync status
      await loadFile();
    } catch (err) {
      console.error("Failed to onload file:", err);
      setError(err.message || "Failed to download file for offline access");
    } finally {
      setIsOnloading(false);
    }
  };

  // Handle open file
  const handleOpen = async () => {
    setIsOpening(true);
    setError("");
    try {
      console.log("Opening file:", fileId);
      await OpenFile(fileId);
      console.log("File opened");
    } catch (err) {
      console.error("Failed to open file:", err);
      setError(err.message || "Failed to open file");
    } finally {
      setIsOpening(false);
    }
  };

  // Handle offload file (remove local copy, keep in cloud)
  const handleOffload = async () => {
    setIsOffloading(true);
    setError("");
    try {
      console.log("Offloading file to cloud-only:", fileId);
      await OffloadFile(fileId);
      console.log("File offloaded");
      // Refresh file details to update sync status
      await loadFile();
    } catch (err) {
      console.error("Failed to offload file:", err);
      setError(err.message || "Failed to offload file");
    } finally {
      setIsOffloading(false);
    }
  };

  const handleDownload = async () => {
    setIsDownloading(true);
    setError("");
    try {
      console.log("Starting file download and decryption for:", fileId);
      const savePath = await DownloadFile(fileId);
      console.log("File downloaded and decrypted to:", savePath);

      // Show success message if user selected a location (didn't cancel)
      if (savePath) {
        // Could add a success toast/notification here
        console.log("File saved successfully to:", savePath);
      }
    } catch (err) {
      console.error("Failed to download file:", err);
      setError(err.message || "Failed to download file");
    } finally {
      setIsDownloading(false);
    }
  };

  const handleDelete = async () => {
    setIsDeleting(true);
    try {
      console.log("Deleting file:", fileId);
      await DeleteFile(fileId);
      console.log("File deleted successfully");

      // Navigate back to the collection
      if (file?.collection_id) {
        navigate(`/file-manager/collections/${file.collection_id}`, { state: { refresh: true } });
      } else {
        navigate("/file-manager", { state: { refresh: true } });
      }
    } catch (err) {
      console.error("Failed to delete file:", err);
      setError(err.message || "Failed to delete file");
      setIsDeleting(false);
      setShowDeleteConfirm(false);
    }
  };

  // Load all available tags for the tag editor
  const loadAllTags = async () => {
    setIsLoadingTags(true);
    try {
      console.log("Loading all tags...");
      const tags = await ListTags();
      console.log("All tags loaded:", tags);
      setAllTags(tags || []);
    } catch (err) {
      console.error("Failed to load tags:", err);
      setAllTags([]);
    } finally {
      setIsLoadingTags(false);
    }
  };

  // Open tag editor modal
  const handleOpenTagEditor = async () => {
    await loadAllTags();
    setShowTagEditor(true);
  };

  // Check if a tag is assigned to the current file
  const isTagAssigned = (tagId) => {
    return file?.tags?.some((t) => t.id === tagId) || false;
  };

  // Handle tag toggle (assign or unassign)
  const handleTagToggle = async (tagId) => {
    setIsUpdatingTags(true);
    try {
      if (isTagAssigned(tagId)) {
        console.log("Unassigning tag from file:", tagId, fileId);
        await UnassignTagFromFile(tagId, fileId);
      } else {
        console.log("Assigning tag to file:", tagId, fileId);
        await AssignTagToFile(tagId, fileId);
      }
      // Refresh file to update tags
      await loadFile();
    } catch (err) {
      console.error("Failed to update tag:", err);
      setError(err.message || "Failed to update tag");
    } finally {
      setIsUpdatingTags(false);
    }
  };

  const getBackUrl = () => {
    if (file?.collection_id) {
      return `/file-manager/collections/${file.collection_id}`;
    }
    return "/file-manager";
  };

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

  return (
    <div className="layout">
      <Navigation />
      <div className="main-content">
        <Page title={file?.filename || "File Details"}>
          {/* Back Button */}
          <button
            onClick={() => navigate(getBackUrl())}
            className="nav-button secondary"
            style={{ marginBottom: "20px" }}
          >
            Back to Collection
          </button>

          {/* Error Display */}
          {error && (
            <div
              style={{
                padding: "15px",
                background: "#ffebee",
                color: "#c62828",
                borderRadius: "4px",
                marginBottom: "20px",
                border: "1px solid #f44336",
              }}
            >
              {error}
            </div>
          )}

          {/* File Info Card */}
          {file && (
            <div
              style={{
                background: "white",
                padding: "20px",
                borderRadius: "8px",
                border: "1px solid #ddd",
                marginBottom: "30px",
              }}
            >
              <div style={{ display: "flex", alignItems: "flex-start", gap: "20px" }}>
                <div style={{
                  width: "80px",
                  height: "80px",
                  background: "#f5f5f5",
                  borderRadius: "8px",
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center",
                  fontSize: "14px",
                  fontWeight: "bold",
                  color: "#666",
                  textTransform: "uppercase",
                  flexShrink: 0
                }}>
                  {file.mime_type?.split("/")[1]?.substring(0, 4) || "FILE"}
                </div>
                <div style={{ flex: 1 }}>
                  <h2 style={{ margin: 0, marginBottom: "10px", wordBreak: "break-word", color: "#333" }}>
                    {file.filename}
                  </h2>

                  {/* File Details Grid */}
                  <div style={{
                    display: "grid",
                    gridTemplateColumns: "repeat(auto-fit, minmax(200px, 1fr))",
                    gap: "15px",
                    marginTop: "15px"
                  }}>
                    <div>
                      <div style={{ color: "#666", fontSize: "12px", marginBottom: "4px" }}>SIZE</div>
                      <div style={{ fontWeight: "500", color: "#333" }}>{formatFileSize(file.size)}</div>
                      <div style={{ fontSize: "12px", color: "#888" }}>({file.size?.toLocaleString()} bytes)</div>
                    </div>

                    <div>
                      <div style={{ color: "#666", fontSize: "12px", marginBottom: "4px" }}>ENCRYPTED SIZE</div>
                      <div style={{ fontWeight: "500", color: "#333" }}>{formatFileSize(file.encrypted_file_size_in_bytes)}</div>
                    </div>

                    <div>
                      <div style={{ color: "#666", fontSize: "12px", marginBottom: "4px" }}>TYPE</div>
                      <div style={{ fontWeight: "500", color: "#333" }}>{file.mime_type || "Unknown"}</div>
                    </div>

                    <div>
                      <div style={{ color: "#666", fontSize: "12px", marginBottom: "4px" }}>STATUS</div>
                      <div style={{ fontWeight: "500" }}>
                        <span style={{
                          display: "inline-block",
                          padding: "2px 8px",
                          borderRadius: "4px",
                          fontSize: "12px",
                          background: file.state === "active" ? "#e8f5e9" : file.state === "archived" ? "#fff3e0" : "#ffebee",
                          color: file.state === "active" ? "#2e7d32" : file.state === "archived" ? "#ef6c00" : "#c62828"
                        }}>
                          {getStateIcon(file.state)} {getStateLabel(file.state)}
                        </span>
                      </div>
                    </div>

                    <div>
                      <div style={{ color: "#666", fontSize: "12px", marginBottom: "4px" }}>SYNC STATUS</div>
                      <div style={{ fontWeight: "500" }}>
                        {(() => {
                          const syncInfo = getSyncStatusInfo(file.sync_status);
                          return (
                            <span
                              title={syncInfo.tooltip}
                              style={{
                                display: "inline-flex",
                                alignItems: "center",
                                gap: "6px",
                                padding: "4px 10px",
                                borderRadius: "12px",
                                fontSize: "13px",
                                backgroundColor: `${syncInfo.color}20`,
                                color: syncInfo.color,
                                fontWeight: "500",
                                cursor: "help",
                              }}
                            >
                              {syncInfo.icon} {syncInfo.label}
                            </span>
                          );
                        })()}
                      </div>
                    </div>

                    {file.has_local_content && file.local_file_path && (
                      <div>
                        <div style={{ color: "#666", fontSize: "12px", marginBottom: "4px" }}>LOCAL PATH</div>
                        <div style={{
                          fontWeight: "500",
                          fontSize: "11px",
                          fontFamily: "monospace",
                          wordBreak: "break-all",
                          color: "#4caf50"
                        }}>
                          {file.local_file_path}
                        </div>
                      </div>
                    )}

                    <div>
                      <div style={{ color: "#666", fontSize: "12px", marginBottom: "4px" }}>CREATED</div>
                      <div style={{ fontWeight: "500", color: "#333" }}>{formatDate(file.created_at)}</div>
                      <div style={{ fontSize: "12px", color: "#888" }}>{getTimeAgo(file.created_at)}</div>
                    </div>

                    <div>
                      <div style={{ color: "#666", fontSize: "12px", marginBottom: "4px" }}>MODIFIED</div>
                      <div style={{ fontWeight: "500", color: "#333" }}>{formatDate(file.modified_at)}</div>
                      <div style={{ fontSize: "12px", color: "#888" }}>{getTimeAgo(file.modified_at)}</div>
                    </div>

                    <div>
                      <div style={{ color: "#666", fontSize: "12px", marginBottom: "4px" }}>VERSION</div>
                      <div style={{ fontWeight: "500", color: "#333" }}>{file.version}</div>
                    </div>

                    <div>
                      <div style={{ color: "#666", fontSize: "12px", marginBottom: "4px" }}>FILE ID</div>
                      <div style={{
                        fontWeight: "500",
                        fontSize: "11px",
                        fontFamily: "monospace",
                        wordBreak: "break-all",
                        color: "#333"
                      }}>
                        {file.id}
                      </div>
                    </div>
                  </div>

                  {/* Tags Section */}
                  <div style={{ marginTop: "20px", paddingTop: "15px", borderTop: "1px solid #eee" }}>
                    <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: "10px" }}>
                      <div style={{ color: "#666", fontSize: "12px", fontWeight: "bold" }}>TAGS</div>
                      <button
                        onClick={handleOpenTagEditor}
                        style={{
                          background: "none",
                          border: "1px solid #ddd",
                          borderRadius: "4px",
                          padding: "4px 10px",
                          fontSize: "12px",
                          cursor: "pointer",
                          color: "#666",
                        }}
                      >
                        Edit Tags
                      </button>
                    </div>
                    <div style={{ display: "flex", flexWrap: "wrap", gap: "8px" }}>
                      {file.tags && file.tags.length > 0 ? (
                        file.tags.map((tag) => (
                          <span
                            key={tag.id}
                            style={{
                              display: "inline-flex",
                              alignItems: "center",
                              gap: "6px",
                              padding: "4px 10px",
                              borderRadius: "16px",
                              fontSize: "13px",
                              backgroundColor: tag.color ? `${tag.color}20` : "#e3f2fd",
                              color: tag.color || "#1976d2",
                              fontWeight: "500",
                            }}
                          >
                            {tag.name}
                          </span>
                        ))
                      ) : (
                        <span style={{ color: "#999", fontSize: "13px", fontStyle: "italic" }}>
                          No tags assigned
                        </span>
                      )}
                    </div>
                  </div>
                </div>
              </div>
            </div>
          )}

          {/* Actions */}
          <div style={{ marginBottom: "30px" }}>
            <h3 style={{ color: "#333" }}>Actions</h3>
            <div className="nav-buttons">
              {/* Show Onload button for cloud-only files */}
              {file?.sync_status === "cloud_only" && (
                <button
                  onClick={handleOnload}
                  className="nav-button success"
                  disabled={isOnloading}
                  title="Download file from cloud for offline access"
                >
                  {isOnloading ? "Downloading..." : "☁️⬇️ Onload"}
                </button>
              )}

              {/* Show Open button for files with local content */}
              {(file?.sync_status === "synced" || file?.has_local_content) && (
                <button
                  onClick={handleOpen}
                  className="nav-button"
                  disabled={isOpening}
                  title="Open file with default application"
                >
                  {isOpening ? "Opening..." : "📂 Open"}
                </button>
              )}

              {/* Show Offload button for synced files */}
              {(file?.sync_status === "synced" || file?.has_local_content) && (
                <button
                  onClick={handleOffload}
                  className="nav-button secondary"
                  disabled={isOffloading}
                  title="Remove local copy, keep in cloud only"
                >
                  {isOffloading ? "Offloading..." : "☁️⬆️ Offload"}
                </button>
              )}

              {/* Show Push button for modified files */}
              {file?.sync_status === "modified_locally" && (
                <button
                  onClick={() => {
                    // TODO: Implement push to cloud
                    console.log("Push changes for:", fileId);
                  }}
                  className="nav-button success"
                  title="Push local changes to cloud"
                >
                  ⬆️ Push to Cloud
                </button>
              )}

              {/* Save As button - always available */}
              <button
                onClick={handleDownload}
                className="nav-button secondary"
                disabled={isDownloading}
                title="Save file to a specific location"
              >
                {isDownloading ? "Saving..." : "💾 Save As"}
              </button>

              {/* Delete button */}
              <button
                onClick={() => setShowDeleteConfirm(true)}
                className="nav-button danger"
                disabled={isDeleting}
              >
                🗑️ Delete File
              </button>
            </div>
          </div>

          {/* Delete Confirmation Modal */}
          {showDeleteConfirm && (
            <div
              style={{
                position: "fixed",
                top: 0,
                left: 0,
                right: 0,
                bottom: 0,
                background: "rgba(0, 0, 0, 0.5)",
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
                zIndex: 1000,
              }}
              onClick={() => !isDeleting && setShowDeleteConfirm(false)}
            >
              <div
                style={{
                  background: "white",
                  padding: "30px",
                  borderRadius: "8px",
                  maxWidth: "400px",
                  width: "90%",
                }}
                onClick={(e) => e.stopPropagation()}
              >
                <h3 style={{ margin: "0 0 15px 0", color: "#333" }}>Delete File?</h3>
                <p style={{ color: "#666", marginBottom: "20px" }}>
                  Are you sure you want to delete "{file?.filename}"? This action cannot be undone.
                </p>
                <div style={{ display: "flex", gap: "10px", justifyContent: "flex-end" }}>
                  <button
                    onClick={() => setShowDeleteConfirm(false)}
                    className="nav-button secondary"
                    disabled={isDeleting}
                  >
                    Cancel
                  </button>
                  <button
                    onClick={handleDelete}
                    className="nav-button danger"
                    disabled={isDeleting}
                  >
                    {isDeleting ? "Deleting..." : "Delete"}
                  </button>
                </div>
              </div>
            </div>
          )}

          {/* Tag Editor Modal */}
          {showTagEditor && (
            <div
              style={{
                position: "fixed",
                top: 0,
                left: 0,
                right: 0,
                bottom: 0,
                background: "rgba(0, 0, 0, 0.5)",
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
                zIndex: 1000,
              }}
              onClick={() => !isUpdatingTags && setShowTagEditor(false)}
            >
              <div
                style={{
                  background: "white",
                  padding: "30px",
                  borderRadius: "8px",
                  maxWidth: "450px",
                  width: "90%",
                  maxHeight: "80vh",
                  overflow: "auto",
                }}
                onClick={(e) => e.stopPropagation()}
              >
                <h3 style={{ margin: "0 0 15px 0", color: "#333" }}>Manage Tags</h3>
                <p style={{ color: "#666", marginBottom: "20px", fontSize: "14px" }}>
                  Click on a tag to add or remove it from this file.
                </p>

                {isLoadingTags ? (
                  <div style={{ textAlign: "center", padding: "20px", color: "#666" }}>
                    Loading tags...
                  </div>
                ) : allTags.length === 0 ? (
                  <div style={{ textAlign: "center", padding: "20px" }}>
                    <p style={{ color: "#666", marginBottom: "15px" }}>No tags found.</p>
                    <button
                      onClick={() => {
                        setShowTagEditor(false);
                        navigate("/tags");
                      }}
                      className="nav-button"
                    >
                      Create Tags
                    </button>
                  </div>
                ) : (
                  <div style={{ display: "flex", flexWrap: "wrap", gap: "10px", marginBottom: "20px" }}>
                    {allTags.map((tag) => {
                      const assigned = isTagAssigned(tag.id);
                      return (
                        <button
                          key={tag.id}
                          onClick={() => handleTagToggle(tag.id)}
                          disabled={isUpdatingTags}
                          style={{
                            display: "inline-flex",
                            alignItems: "center",
                            gap: "6px",
                            padding: "8px 14px",
                            borderRadius: "20px",
                            fontSize: "14px",
                            border: assigned ? `2px solid ${tag.color || "#1976d2"}` : "2px solid #ddd",
                            backgroundColor: assigned ? (tag.color ? `${tag.color}20` : "#e3f2fd") : "white",
                            color: tag.color || "#1976d2",
                            fontWeight: "500",
                            cursor: isUpdatingTags ? "not-allowed" : "pointer",
                            opacity: isUpdatingTags ? 0.6 : 1,
                            transition: "all 0.2s ease",
                          }}
                        >
                          {assigned && <span>✓</span>}
                          {tag.name}
                        </button>
                      );
                    })}
                  </div>
                )}

                <div style={{ display: "flex", gap: "10px", justifyContent: "flex-end" }}>
                  <button
                    onClick={() => setShowTagEditor(false)}
                    className="nav-button secondary"
                    disabled={isUpdatingTags}
                  >
                    Done
                  </button>
                </div>
              </div>
            </div>
          )}
        </Page>
      </div>
    </div>
  );
}

export default FileDetails;
