// File Path: monorepo/native/desktop/maplefile/frontend/src/pages/User/FileManager/Files/FileUpload.jsx
import { useState, useEffect } from "react";
import { useNavigate, useSearchParams } from "react-router-dom";
import Navigation from "../../../../components/Navigation";
import Page from "../../../../components/Page";
import {
  SelectFile,
  UploadFile,
  ListCollections,
  ListTags,
} from "../../../../../wailsjs/go/app/Application";
import "../../Dashboard/Dashboard.css";

function FileUpload() {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();

  // Get collection ID from URL params if provided
  const preselectedCollectionId = searchParams.get("collection");

  const [selectedFilePath, setSelectedFilePath] = useState("");
  const [selectedCollectionId, setSelectedCollectionId] = useState(preselectedCollectionId || "");
  const [collections, setCollections] = useState([]);
  const [isLoadingCollections, setIsLoadingCollections] = useState(true);
  const [isUploading, setIsUploading] = useState(false);
  const [uploadProgress, setUploadProgress] = useState("");
  const [error, setError] = useState("");
  const [uploadResult, setUploadResult] = useState(null);
  const [availableTags, setAvailableTags] = useState([]);
  const [selectedTagIds, setSelectedTagIds] = useState([]);
  const [isLoadingTags, setIsLoadingTags] = useState(false);

  // Load available collections and tags
  useEffect(() => {
    const loadData = async () => {
      try {
        const collectionsData = await ListCollections();
        setCollections(collectionsData || []);
      } catch (err) {
        console.error("Failed to load collections:", err);
        setError("Failed to load collections");
      } finally {
        setIsLoadingCollections(false);
      }

      // Load tags
      setIsLoadingTags(true);
      try {
        const tags = await ListTags();
        setAvailableTags(tags || []);
      } catch (err) {
        console.error("Failed to load tags:", err);
        setAvailableTags([]);
      } finally {
        setIsLoadingTags(false);
      }
    };

    // Wait for Wails
    if (typeof window !== 'undefined' && window.go && window.go.app && window.go.app.Application) {
      loadData();
    } else {
      const checkWails = setInterval(() => {
        if (window.go && window.go.app && window.go.app.Application) {
          clearInterval(checkWails);
          loadData();
        }
      }, 100);
      setTimeout(() => clearInterval(checkWails), 10000);
      return () => clearInterval(checkWails);
    }
  }, []);

  const handleSelectFile = async () => {
    try {
      setError("");
      const filePath = await SelectFile();
      if (filePath) {
        setSelectedFilePath(filePath);
        console.log("File selected:", filePath);
      }
    } catch (err) {
      console.error("Failed to select file:", err);
      setError(err.message || "Failed to select file");
    }
  };

  const handleUpload = async () => {
    if (!selectedFilePath) {
      setError("Please select a file to upload");
      return;
    }
    if (!selectedCollectionId) {
      setError("Please select a collection");
      return;
    }

    setIsUploading(true);
    setError("");
    setUploadProgress("Preparing upload...");
    setUploadResult(null);

    try {
      console.log("Starting upload:", {
        filePath: selectedFilePath,
        collectionId: selectedCollectionId,
      });

      setUploadProgress("Encrypting and uploading file...");

      const result = await UploadFile({
        file_path: selectedFilePath,
        collection_id: selectedCollectionId,
        tag_ids: selectedTagIds.length > 0 ? selectedTagIds : undefined,
      });

      console.log("Upload result:", result);

      if (result.success) {
        setUploadResult(result);
        setUploadProgress("Upload complete!");
      } else {
        setError(result.message || "Upload failed");
        setUploadProgress("");
      }
    } catch (err) {
      console.error("Upload failed:", err);
      setError(err.message || "Failed to upload file");
      setUploadProgress("");
    } finally {
      setIsUploading(false);
    }
  };

  const handleUploadAnother = () => {
    setSelectedFilePath("");
    setUploadResult(null);
    setUploadProgress("");
    setError("");
  };

  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 getFileName = (filePath) => {
    if (!filePath) return "";
    const parts = filePath.split(/[/\\]/);
    return parts[parts.length - 1];
  };

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

  // Success state
  if (uploadResult) {
    return (
      <div className="layout">
        <Navigation />
        <div className="main-content">
          <Page title="Upload Complete">
            <div
              style={{
                background: "#e8f5e9",
                padding: "30px",
                borderRadius: "8px",
                textAlign: "center",
                marginBottom: "30px",
              }}
            >
              <div style={{ fontSize: "64px", marginBottom: "15px" }}>
                [OK]
              </div>
              <h2 style={{ margin: "0 0 10px 0", color: "#2e7d32" }}>
                File Uploaded Successfully!
              </h2>
              <p style={{ color: "#666", margin: "0" }}>
                Your file has been encrypted and uploaded to the cloud.
              </p>
            </div>

            <div
              style={{
                background: "white",
                padding: "20px",
                borderRadius: "8px",
                border: "1px solid #ddd",
                marginBottom: "30px",
              }}
            >
              <h3 style={{ marginTop: 0 }}>Upload Details</h3>
              <div style={{ display: "grid", gap: "10px" }}>
                <div>
                  <span style={{ color: "#666" }}>Filename: </span>
                  <strong>{uploadResult.filename}</strong>
                </div>
                <div>
                  <span style={{ color: "#666" }}>Size: </span>
                  <strong>{formatFileSize(uploadResult.size)}</strong>
                </div>
                <div>
                  <span style={{ color: "#666" }}>File ID: </span>
                  <code style={{ fontSize: "12px" }}>{uploadResult.file_id}</code>
                </div>
              </div>
            </div>

            <div className="nav-buttons">
              <button
                onClick={() => navigate(`/file-manager/files/${uploadResult.file_id}`)}
                className="nav-button success"
              >
                View File
              </button>
              <button
                onClick={handleUploadAnother}
                className="nav-button"
              >
                Upload Another
              </button>
              <button
                onClick={() => navigate(getBackUrl(), { state: { refresh: true } })}
                className="nav-button secondary"
              >
                Back to Collection
              </button>
            </div>
          </Page>
        </div>
      </div>
    );
  }

  return (
    <div className="layout">
      <Navigation />
      <div className="main-content">
        <Page title="Upload File">
          {/* Back Button */}
          <button
            onClick={() => navigate(getBackUrl())}
            className="nav-button secondary"
            style={{ marginBottom: "20px" }}
          >
            Cancel
          </button>

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

          {/* Upload Form */}
          <div
            style={{
              background: "white",
              padding: "30px",
              borderRadius: "8px",
              border: "1px solid #ddd",
              marginBottom: "30px",
            }}
          >
            {/* Step 1: Select Collection */}
            <div style={{ marginBottom: "25px" }}>
              <label
                style={{
                  display: "block",
                  fontWeight: "bold",
                  marginBottom: "8px",
                }}
              >
                1. Select Collection
              </label>
              {isLoadingCollections ? (
                <div style={{ color: "#666" }}>Loading collections...</div>
              ) : (
                <select
                  value={selectedCollectionId}
                  onChange={(e) => setSelectedCollectionId(e.target.value)}
                  disabled={isUploading}
                  style={{
                    width: "100%",
                    padding: "10px 12px",
                    border: "1px solid #ddd",
                    borderRadius: "4px",
                    fontSize: "14px",
                    backgroundColor: isUploading ? "#f5f5f5" : "white",
                  }}
                >
                  <option value="">-- Select a collection --</option>
                  {collections.map((col) => (
                    <option key={col.id} value={col.id}>
                      {col.name || "Unnamed Collection"}
                    </option>
                  ))}
                </select>
              )}
              {collections.length === 0 && !isLoadingCollections && (
                <p style={{ color: "#666", fontSize: "14px", marginTop: "8px" }}>
                  No collections found.{" "}
                  <button
                    onClick={() => navigate("/file-manager/collections/create")}
                    style={{
                      background: "none",
                      border: "none",
                      color: "#1976d2",
                      cursor: "pointer",
                      textDecoration: "underline",
                      padding: 0,
                    }}
                  >
                    Create one first
                  </button>
                </p>
              )}
            </div>

            {/* Step 2: Select File */}
            <div style={{ marginBottom: "25px" }}>
              <label
                style={{
                  display: "block",
                  fontWeight: "bold",
                  marginBottom: "8px",
                }}
              >
                2. Select File
              </label>
              <div style={{ display: "flex", gap: "10px", alignItems: "center" }}>
                <button
                  onClick={handleSelectFile}
                  disabled={isUploading}
                  className="nav-button"
                  style={{ flexShrink: 0 }}
                >
                  Browse...
                </button>
                <div
                  style={{
                    flex: 1,
                    padding: "10px 12px",
                    border: "1px solid #ddd",
                    borderRadius: "4px",
                    background: "#f9f9f9",
                    color: selectedFilePath ? "#333" : "#999",
                    overflow: "hidden",
                    textOverflow: "ellipsis",
                    whiteSpace: "nowrap",
                  }}
                >
                  {selectedFilePath ? getFileName(selectedFilePath) : "No file selected"}
                </div>
              </div>
              {selectedFilePath && (
                <div style={{ fontSize: "12px", color: "#666", marginTop: "5px" }}>
                  Full path: {selectedFilePath}
                </div>
              )}
            </div>

            {/* Step 3: Select Tags (Optional) */}
            <div style={{ marginBottom: "25px" }}>
              <label
                style={{
                  display: "block",
                  fontWeight: "bold",
                  marginBottom: "8px",
                }}
              >
                3. Tags{" "}
                <span style={{ fontSize: "12px", fontWeight: "normal", color: "#666" }}>
                  (optional)
                </span>
              </label>
              {isLoadingTags ? (
                <div style={{ color: "#666" }}>Loading tags...</div>
              ) : availableTags.length > 0 ? (
                <div
                  style={{
                    border: "1px solid #ddd",
                    borderRadius: "4px",
                    padding: "10px",
                    maxHeight: "150px",
                    overflowY: "auto",
                  }}
                >
                  {availableTags.map((tag) => (
                    <label
                      key={tag.id}
                      style={{
                        display: "flex",
                        alignItems: "center",
                        padding: "6px",
                        cursor: "pointer",
                        borderRadius: "4px",
                        transition: "background-color 0.15s ease",
                      }}
                      onMouseOver={(e) => {
                        e.currentTarget.style.backgroundColor = "#f9f9f9";
                      }}
                      onMouseOut={(e) => {
                        e.currentTarget.style.backgroundColor = "transparent";
                      }}
                    >
                      <input
                        type="checkbox"
                        checked={selectedTagIds.includes(tag.id)}
                        onChange={(e) => {
                          if (e.target.checked) {
                            setSelectedTagIds([...selectedTagIds, tag.id]);
                          } else {
                            setSelectedTagIds(selectedTagIds.filter((id) => id !== tag.id));
                          }
                        }}
                        disabled={isUploading}
                        style={{ marginRight: "8px", cursor: "pointer" }}
                      />
                      <span
                        style={{
                          display: "inline-block",
                          width: "12px",
                          height: "12px",
                          borderRadius: "50%",
                          backgroundColor: tag.color || "#666",
                          marginRight: "8px",
                        }}
                      />
                      <span style={{ fontSize: "14px", color: "#333" }}>{tag.name}</span>
                    </label>
                  ))}
                </div>
              ) : (
                <div
                  style={{
                    padding: "10px",
                    color: "#666",
                    fontSize: "14px",
                    fontStyle: "italic",
                  }}
                >
                  No tags available
                </div>
              )}
            </div>

            {/* Upload Progress */}
            {uploadProgress && (
              <div
                style={{
                  padding: "15px",
                  background: "#e3f2fd",
                  color: "#1565c0",
                  borderRadius: "4px",
                  marginBottom: "20px",
                  display: "flex",
                  alignItems: "center",
                  gap: "10px",
                }}
              >
                <div
                  style={{
                    width: "20px",
                    height: "20px",
                    border: "2px solid #1565c0",
                    borderTopColor: "transparent",
                    borderRadius: "50%",
                    animation: "spin 1s linear infinite",
                  }}
                />
                {uploadProgress}
              </div>
            )}

            {/* Upload Button */}
            <button
              onClick={handleUpload}
              disabled={isUploading || !selectedFilePath || !selectedCollectionId}
              className="nav-button success"
              style={{
                width: "100%",
                padding: "15px",
                fontSize: "16px",
                opacity: (isUploading || !selectedFilePath || !selectedCollectionId) ? 0.6 : 1,
              }}
            >
              {isUploading ? "Uploading..." : "Encrypt & Upload File"}
            </button>
          </div>

          {/* Info Box */}
          <div
            style={{
              background: "#f5f5f5",
              padding: "20px",
              borderRadius: "8px",
              fontSize: "14px",
              color: "#666",
            }}
          >
            <h4 style={{ marginTop: 0, color: "#333" }}>How it works</h4>
            <ul style={{ margin: 0, paddingLeft: "20px" }}>
              <li>Your file is encrypted locally before being uploaded</li>
              <li>Only you and people you share with can decrypt it</li>
              <li>The server never sees your unencrypted data</li>
              <li>Files are stored securely in the cloud</li>
            </ul>
          </div>

          {/* Inline CSS for spinner animation */}
          <style>{`
            @keyframes spin {
              to { transform: rotate(360deg); }
            }
          `}</style>
        </Page>
      </div>
    </div>
  );
}

export default FileUpload;
