// File Path: monorepo/native/desktop/maplefile/frontend/src/pages/User/FileManager/Collections/CollectionCreate.jsx
import { useState, useEffect } from "react";
import { useNavigate, useLocation } from "react-router-dom";
import Navigation from "../../../../components/Navigation";
import Page from "../../../../components/Page";
import IconPicker from "../../../../components/IconPicker";
import { CreateCollection, ListTags } from "../../../../../wailsjs/go/app/Application";
import "../../Dashboard/Dashboard.css";

function CollectionCreate() {
  const navigate = useNavigate();
  const location = useLocation();

  // Get parent collection info from navigation state
  const parentCollectionId = location.state?.parentCollectionId;
  const parentCollectionName = location.state?.parentCollectionName;

  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState("");
  const [collectionName, setCollectionName] = useState("");
  const [description, setDescription] = useState("");
  const [customIcon, setCustomIcon] = useState("");
  const [collectionType, setCollectionType] = useState("folder");
  const [isIconPickerOpen, setIsIconPickerOpen] = useState(false);
  const [availableTags, setAvailableTags] = useState([]);
  const [selectedTagIds, setSelectedTagIds] = useState([]);
  const [isLoadingTags, setIsLoadingTags] = useState(false);

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

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError("");

    // Client-side validation
    if (!collectionName || !collectionName.trim()) {
      setError("Collection name is required");
      return;
    }

    if (collectionName.trim().length < 2) {
      setError("Collection name must be at least 2 characters");
      return;
    }

    if (collectionName.trim().length > 100) {
      setError("Collection name must be less than 100 characters");
      return;
    }

    setIsLoading(true);

    try {
      const input = {
        name: collectionName.trim(),
        description: description.trim(),
        parent_id: parentCollectionId || "",
        custom_icon: customIcon,
        collection_type: collectionType,
        tag_ids: selectedTagIds.length > 0 ? selectedTagIds : undefined,
      };

      const result = await CreateCollection(input);

      if (result.success) {
        // Navigate back to file manager or parent collection
        if (parentCollectionId) {
          navigate(`/file-manager/collections/${parentCollectionId}`, {
            state: { refresh: true },
          });
        } else {
          navigate("/file-manager", {
            state: { refresh: true },
          });
        }
      }
    } catch (err) {
      console.error("Failed to create collection:", err);
      setError(err.message || "Failed to create collection. Please try again.");
    } finally {
      setIsLoading(false);
    }
  };

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

  const getBackText = () => {
    if (parentCollectionName) {
      return `Back to ${parentCollectionName}`;
    }
    return "Back to File Manager";
  };

  return (
    <div className="layout">
      <Navigation />
      <div className="main-content">
        <Page title="Create New Collection">
          <button
            onClick={() => navigate(getBackUrl())}
            className="nav-button secondary"
            style={{ marginBottom: "20px" }}
          >
            ← {getBackText()}
          </button>

          {parentCollectionName && (
            <p style={{ marginBottom: "20px", color: "#666" }}>
              Creating collection inside: <strong>{parentCollectionName}</strong>
            </p>
          )}

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

          <form
            onSubmit={handleSubmit}
            style={{
              maxWidth: "600px",
              background: "white",
              padding: "30px",
              borderRadius: "8px",
              border: "1px solid #ddd",
            }}
          >
            {/* Collection Name */}
            <div style={{ marginBottom: "20px" }}>
              <label
                htmlFor="name"
                style={{
                  display: "block",
                  marginBottom: "8px",
                  fontWeight: "bold",
                  color: "#333",
                }}
              >
                Collection Name <span style={{ color: "#f44336" }}>*</span>
              </label>
              <input
                type="text"
                id="name"
                value={collectionName}
                onChange={(e) => {
                  setCollectionName(e.target.value);
                  if (error) setError("");
                }}
                placeholder="Enter collection name"
                disabled={isLoading}
                style={{
                  width: "100%",
                  padding: "10px 12px",
                  border: "1px solid #ddd",
                  borderRadius: "4px",
                  fontSize: "14px",
                }}
                autoFocus
                required
              />
              <p style={{ fontSize: "12px", color: "#666", marginTop: "5px" }}>
                A descriptive name for your collection
              </p>
            </div>

            {/* Custom Icon */}
            <div style={{ marginBottom: "20px" }}>
              <label
                style={{
                  display: "block",
                  marginBottom: "8px",
                  fontWeight: "bold",
                  color: "#333",
                }}
              >
                Icon{" "}
                <span style={{ fontSize: "12px", color: "#666", fontWeight: "normal" }}>
                  (optional)
                </span>
              </label>
              <button
                type="button"
                onClick={() => setIsIconPickerOpen(true)}
                disabled={isLoading}
                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",
                  color: "#333",
                }}
              >
                Type
              </label>
              <div style={{ display: "flex", gap: "10px" }}>
                <button
                  type="button"
                  onClick={() => setCollectionType("folder")}
                  disabled={isLoading}
                  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={isLoading}
                  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>

            {/* Tag Selection */}
            <div style={{ marginBottom: "20px" }}>
              <label
                style={{
                  display: "block",
                  marginBottom: "8px",
                  fontWeight: "bold",
                  color: "#333",
                }}
              >
                Tags{" "}
                <span style={{ fontSize: "12px", color: "#666", fontWeight: "normal" }}>
                  (optional)
                </span>
              </label>
              {isLoadingTags ? (
                <div style={{ padding: "10px", color: "#666", fontSize: "14px" }}>
                  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={isLoading}
                        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. Create tags first to organize your collections.
                </div>
              )}
              <p style={{ fontSize: "12px", color: "#666", marginTop: "5px" }}>
                Select tags to organize this collection
              </p>
            </div>

            {/* Description (Optional) */}
            <div style={{ marginBottom: "30px" }}>
              <label
                htmlFor="description"
                style={{
                  display: "block",
                  marginBottom: "8px",
                  fontWeight: "bold",
                  color: "#333",
                }}
              >
                Description{" "}
                <span style={{ fontSize: "12px", color: "#666", fontWeight: "normal" }}>
                  (optional)
                </span>
              </label>
              <textarea
                id="description"
                value={description}
                onChange={(e) => setDescription(e.target.value)}
                placeholder="Enter a description (optional)"
                disabled={isLoading}
                rows="4"
                style={{
                  width: "100%",
                  padding: "10px 12px",
                  border: "1px solid #ddd",
                  borderRadius: "4px",
                  fontSize: "14px",
                  fontFamily: "inherit",
                  resize: "vertical",
                }}
              />
              <p style={{ fontSize: "12px", color: "#666", marginTop: "5px" }}>
                Additional details about this collection
              </p>
            </div>

            {/* Submit Buttons */}
            <div className="nav-buttons" style={{ marginTop: "30px" }}>
              <button
                type="submit"
                disabled={isLoading || !collectionName.trim()}
                className="nav-button success"
              >
                {isLoading ? "Creating..." : "Create Collection"}
              </button>
              <button
                type="button"
                onClick={() => navigate(getBackUrl())}
                disabled={isLoading}
                className="nav-button secondary"
              >
                Cancel
              </button>
            </div>
          </form>
        </Page>
      </div>

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

export default CollectionCreate;
