// File Path: monorepo/native/desktop/maplefile/frontend/src/pages/User/FileManager/Collections/CollectionEdit.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 IconPicker from "../../../../components/IconPicker";
import {
  GetCollection,
  UpdateCollection,
  DeleteCollection,
} from "../../../../../wailsjs/go/app/Application";
import "../../Dashboard/Dashboard.css";

function CollectionEdit() {
  const navigate = useNavigate();
  const { collectionId } = useParams();

  const [isLoading, setIsLoading] = useState(true);
  const [isSaving, setIsSaving] = useState(false);
  const [isDeleting, setIsDeleting] = useState(false);
  const [error, setError] = useState("");
  const [success, setSuccess] = useState("");
  const [collection, setCollection] = useState(null);
  const [name, setName] = useState("");
  const [customIcon, setCustomIcon] = useState("");
  const [collectionType, setCollectionType] = useState("folder");
  const [isIconPickerOpen, setIsIconPickerOpen] = useState(false);
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);

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

    try {
      console.log("Loading collection details...", collectionId);
      const collectionData = await GetCollection(collectionId);
      console.log("Collection loaded:", collectionData);
      setCollection(collectionData);
      setName(collectionData.name || "");
      setCustomIcon(collectionData.custom_icon || "");
      setCollectionType(collectionData.collection_type || "folder");
    } catch (err) {
      console.error("Failed to load collection:", err);
      setError(err.message || "Failed to load collection");
    } finally {
      setIsLoading(false);
    }
  }, [collectionId]);

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

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

  // Handle save
  const handleSave = async (e) => {
    e.preventDefault();

    if (!name.trim()) {
      setError("Collection name is required");
      return;
    }

    setIsSaving(true);
    setError("");
    setSuccess("");

    try {
      console.log("Updating collection...", collectionId, name, customIcon, collectionType);
      await UpdateCollection(collectionId, {
        name: name.trim(),
        custom_icon: customIcon,
        collection_type: collectionType,
      });
      setSuccess("Collection updated successfully!");

      // Navigate back to collection details after a short delay
      setTimeout(() => {
        navigate(`/file-manager/collections/${collectionId}`, {
          state: { refresh: true }
        });
      }, 1000);
    } catch (err) {
      console.error("Failed to update collection:", err);
      setError(err.message || "Failed to update collection");
    } finally {
      setIsSaving(false);
    }
  };

  // Handle delete
  const handleDelete = async () => {
    setIsDeleting(true);
    setError("");

    try {
      console.log("Deleting collection...", collectionId);
      await DeleteCollection(collectionId);

      // Navigate to file manager after deletion
      navigate("/file-manager", {
        state: { refresh: true }
      });
    } catch (err) {
      console.error("Failed to delete collection:", err);
      setError(err.message || "Failed to delete collection");
      setIsDeleting(false);
      setShowDeleteConfirm(false);
    }
  };

  // Handle cancel
  const handleCancel = () => {
    navigate(`/file-manager/collections/${collectionId}`);
  };

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

  return (
    <div className="layout">
      <Navigation />
      <div className="main-content">
        <Page title={`Edit Collection`}>
          {/* Back Button */}
          <button
            onClick={handleCancel}
            className="nav-button secondary"
            style={{ marginBottom: "20px" }}
          >
            &larr; 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>
          )}

          {/* Success Display */}
          {success && (
            <div
              style={{
                padding: "15px",
                background: "#e8f5e9",
                color: "#2e7d32",
                borderRadius: "4px",
                marginBottom: "20px",
                border: "1px solid #4caf50",
              }}
            >
              {success}
            </div>
          )}

          {/* Edit Form */}
          <div
            style={{
              background: "white",
              padding: "30px",
              borderRadius: "8px",
              border: "1px solid #ddd",
              marginBottom: "30px",
            }}
          >
            <form onSubmit={handleSave}>
              <div style={{ marginBottom: "20px" }}>
                <label
                  htmlFor="name"
                  style={{
                    display: "block",
                    marginBottom: "8px",
                    fontWeight: "bold",
                  }}
                >
                  Collection Name
                </label>
                <input
                  type="text"
                  id="name"
                  value={name}
                  onChange={(e) => setName(e.target.value)}
                  placeholder="Enter collection name"
                  style={{
                    width: "100%",
                    padding: "12px",
                    border: "1px solid #ddd",
                    borderRadius: "4px",
                    fontSize: "16px",
                  }}
                  disabled={isSaving}
                />
              </div>

              {/* Custom Icon */}
              <div style={{ marginBottom: "20px" }}>
                <label
                  style={{
                    display: "block",
                    marginBottom: "8px",
                    fontWeight: "bold",
                  }}
                >
                  Icon{" "}
                  <span style={{ fontSize: "12px", color: "#666", fontWeight: "normal" }}>
                    (optional)
                  </span>
                </label>
                <button
                  type="button"
                  onClick={() => setIsIconPickerOpen(true)}
                  disabled={isSaving}
                  style={{
                    display: "flex",
                    alignItems: "center",
                    gap: "10px",
                    padding: "10px 14px",
                    border: "1px solid #ddd",
                    borderRadius: "4px",
                    background: "white",
                    cursor: "pointer",
                    fontSize: "14px",
                    color: "#333",
                    transition: "all 0.15s ease",
                  }}
                  onMouseOver={(e) => {
                    e.currentTarget.style.borderColor = "#999";
                    e.currentTarget.style.background = "#f9f9f9";
                  }}
                  onMouseOut={(e) => {
                    e.currentTarget.style.borderColor = "#ddd";
                    e.currentTarget.style.background = "white";
                  }}
                >
                  <span style={{ fontSize: "24px" }}>
                    {customIcon || "📁"}
                  </span>
                  <span>{customIcon ? "Change Icon" : "Choose Icon"}</span>
                </button>
                <p style={{ fontSize: "12px", color: "#666", marginTop: "5px" }}>
                  Select an emoji to customize your collection
                </p>
              </div>

              {/* Collection Type */}
              <div style={{ marginBottom: "20px" }}>
                <label
                  style={{
                    display: "block",
                    marginBottom: "8px",
                    fontWeight: "bold",
                  }}
                >
                  Type
                </label>
                <div style={{ display: "flex", gap: "10px" }}>
                  <button
                    type="button"
                    onClick={() => setCollectionType("folder")}
                    disabled={isSaving}
                    style={{
                      flex: 1,
                      display: "flex",
                      alignItems: "center",
                      justifyContent: "center",
                      gap: "8px",
                      padding: "12px",
                      border: collectionType === "folder" ? "2px solid #991b1b" : "1px solid #ddd",
                      borderRadius: "4px",
                      background: collectionType === "folder" ? "#fef2f2" : "white",
                      cursor: "pointer",
                      fontSize: "14px",
                      color: "#333",
                      transition: "all 0.15s ease",
                    }}
                  >
                    <span style={{ fontSize: "20px" }}>📁</span>
                    <span>Folder</span>
                  </button>
                  <button
                    type="button"
                    onClick={() => setCollectionType("album")}
                    disabled={isSaving}
                    style={{
                      flex: 1,
                      display: "flex",
                      alignItems: "center",
                      justifyContent: "center",
                      gap: "8px",
                      padding: "12px",
                      border: collectionType === "album" ? "2px solid #991b1b" : "1px solid #ddd",
                      borderRadius: "4px",
                      background: collectionType === "album" ? "#fef2f2" : "white",
                      cursor: "pointer",
                      fontSize: "14px",
                      color: "#333",
                      transition: "all 0.15s ease",
                    }}
                  >
                    <span style={{ fontSize: "20px" }}>🖼️</span>
                    <span>Album</span>
                  </button>
                </div>
                <p style={{ fontSize: "12px", color: "#666", marginTop: "5px" }}>
                  Folders are for general files, albums are optimized for photos and media
                </p>
              </div>

              {collection && (
                <div
                  style={{
                    marginBottom: "20px",
                    padding: "15px",
                    background: "#f5f5f5",
                    borderRadius: "4px",
                  }}
                >
                  <div style={{ fontSize: "14px", color: "#666" }}>
                    <div><strong>Collection ID:</strong> {collection.id}</div>
                    <div><strong>Files:</strong> {collection.file_count || 0}</div>
                    {collection.parent_id && (
                      <div><strong>Parent Collection:</strong> {collection.parent_id}</div>
                    )}
                  </div>
                </div>
              )}

              <div className="nav-buttons">
                <button
                  type="submit"
                  className="nav-button success"
                  disabled={isSaving || !name.trim()}
                >
                  {isSaving ? "Saving..." : "Save Changes"}
                </button>
                <button
                  type="button"
                  onClick={handleCancel}
                  className="nav-button secondary"
                  disabled={isSaving}
                >
                  Cancel
                </button>
              </div>
            </form>
          </div>

          {/* Danger Zone */}
          <div
            style={{
              background: "#fff5f5",
              padding: "20px",
              borderRadius: "8px",
              border: "1px solid #f44336",
            }}
          >
            <h3 style={{ color: "#c62828", marginBottom: "15px" }}>
              Danger Zone
            </h3>
            <p style={{ marginBottom: "15px", color: "#666" }}>
              Deleting a collection will move it to trash. This action can be
              reversed from the trash within 30 days.
            </p>

            {!showDeleteConfirm ? (
              <button
                onClick={() => setShowDeleteConfirm(true)}
                className="nav-button danger"
                disabled={isDeleting}
              >
                Delete Collection
              </button>
            ) : (
              <div
                style={{
                  background: "#ffebee",
                  padding: "15px",
                  borderRadius: "4px",
                }}
              >
                <p style={{ marginBottom: "15px", fontWeight: "bold" }}>
                  Are you sure you want to delete "{collection?.name}"?
                </p>
                <div className="nav-buttons">
                  <button
                    onClick={handleDelete}
                    className="nav-button danger"
                    disabled={isDeleting}
                  >
                    {isDeleting ? "Deleting..." : "Yes, Delete"}
                  </button>
                  <button
                    onClick={() => setShowDeleteConfirm(false)}
                    className="nav-button secondary"
                    disabled={isDeleting}
                  >
                    Cancel
                  </button>
                </div>
              </div>
            )}
          </div>
        </Page>
      </div>

      {/* Icon Picker Modal */}
      <IconPicker
        value={customIcon}
        onChange={setCustomIcon}
        onClose={() => setIsIconPickerOpen(false)}
        isOpen={isIconPickerOpen}
      />
    </div>
  );
}

export default CollectionEdit;
