// File: src/pages/User/FileManager/Collections/CollectionCreate.jsx
// UIX version - Full UIX component integration with infinite loop prevention
//
// ⚠️ IMPORTANT - INFINITE LOOP PREVENTION:
// - useUIXTheme's getThemeClasses is memoized and stable
// - All event handlers use useCallback
// - All derived values use useMemo
// - Radio group options are memoized to prevent recreation
//
// 📋 GDPR COMPLIANCE NOTES:
// - Data minimization: Only collects folder name and type
// - Audit logging: Backend handles GDPR accountability via collection creation logs
// - User control: User initiates and controls all data creation
// - Data retention: Managed by backend policy
//
// 🔒 SECURITY NOTES:
// - Input sanitization: Removes < > and javascript: protocol (defense-in-depth)
// - Protected route: withPasswordProtection HOC enforces authentication
// - XSS prevention: React auto-escapes + explicit sanitization
// - CSRF: Handled by backend token validation
// - Validation: Client-side validation (UX) + backend validation (security)

import React, { useState, useMemo, useCallback } from "react";
import { useNavigate, useLocation } from "react-router";
import { useCollections } from "../../../../services/Services";
import withPasswordProtection from "../../../../hocs/withPasswordProtection";
import Layout from "../../../../components/Layout/Layout";
import {
  Breadcrumb,
  Input,
  Button,
  Alert,
  Card,
  useUIXTheme,
  IconPicker,
  CollectionIconPreview,
} from "../../../../components/UIX";
import {
  FolderIcon,
  HomeIcon,
  PlusIcon,
  SparklesIcon,
} from "@heroicons/react/24/outline";
import TagSelector from "../../../../components/UIX/TagSelector/TagSelector";

const CollectionCreate = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const { createCollectionManager } = useCollections();
  const { getThemeClasses } = useUIXTheme();

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

  const [isLoading, setIsLoading] = useState(false);
  const [generalError, setGeneralError] = useState("");
  const [errors, setErrors] = useState({});
  const [collectionName, setCollectionName] = useState("");
  const [customIcon, setCustomIcon] = useState("");
  const [showIconPicker, setShowIconPicker] = useState(false);
  const [selectedTagIds, setSelectedTagIds] = useState([]);

  // Default collection type - always "folder" (Documents)
  const collectionType = "folder";

  // Event handlers with useCallback to prevent recreation
  // NOTE: UIX Input component passes value directly, not event object
  const handleNameChange = useCallback((value) => {
    setCollectionName(value);
    // Clear errors when user starts typing - remove keys instead of setting to ""
    setErrors((prev) => {
      const newErrors = { ...prev };
      delete newErrors.name;
      delete newErrors.Name;
      delete newErrors.collection_name;
      return newErrors;
    });
    setGeneralError("");
  }, []);

  const handleIconChange = useCallback((value) => {
    setCustomIcon(value);
  }, []);

  const handleOpenIconPicker = useCallback(() => {
    setShowIconPicker(true);
  }, []);

  const handleCloseIconPicker = useCallback(() => {
    setShowIconPicker(false);
  }, []);

  const handleTagChange = useCallback((tagIds) => {
    setSelectedTagIds(tagIds);
  }, []);

  const handleCreateCollection = useCallback(
    async (e) => {
      e.preventDefault();

      // Clear previous errors
      setGeneralError("");
      setErrors({});

      // Validate services
      if (!createCollectionManager) {
        setGeneralError("Service not available. Please refresh the page.");
        return;
      }

      // Client-side validation for better UX
      const validationErrors = {};

      if (!collectionName || !collectionName.trim()) {
        validationErrors.name = "Folder name is required";
      } else if (collectionName.trim().length < 2) {
        validationErrors.name = "Folder name must be at least 2 characters";
      } else if (collectionName.trim().length > 100) {
        validationErrors.name = "Folder name must be less than 100 characters";
      }

      // If there are validation errors, show them immediately
      if (Object.keys(validationErrors).length > 0) {
        setErrors(validationErrors);
        return;
      }

      setIsLoading(true);

      try {
        // Sanitize input for defense-in-depth (React auto-escapes, but explicit is better)
        const sanitizedName = collectionName.trim()
          .replace(/[<>]/g, "") // Remove < and > to prevent any HTML injection attempts
          .replace(/javascript:/gi, ""); // Remove javascript: protocol

        // Check if sanitization removed any characters
        if (sanitizedName !== collectionName.trim()) {
          setGeneralError("Folder name contains invalid characters. Special characters like < and > are not allowed.");
          setIsLoading(false);
          return;
        }

        const collectionData = {
          name: sanitizedName,
          collection_type: collectionType,
          custom_icon: customIcon || "", // Empty string means default icon
        };

        // Add parent collection if creating a sub-collection
        if (parentCollectionId) {
          collectionData.parent_id = parentCollectionId;
        }

        // Pass tag IDs to backend - it will look up and embed the full tag data
        if (selectedTagIds.length > 0) {
          collectionData.tag_ids = selectedTagIds;
          if (import.meta.env.DEV) {
            console.log('[CollectionCreate] Sending tag_ids to backend:', selectedTagIds.length);
          }
        }

        const result = await createCollectionManager.createCollection(
          collectionData,
          null,
        );

        if (result.success) {
          if (import.meta.env.DEV) {
            console.log(
              "[CollectionCreate] Collection created successfully with embedded tags:",
              result.collectionId,
            );
          }

          // FIXED: Handle both root and sub-collection cases with proper cache invalidation
          if (parentCollectionId) {
            // Creating a sub-collection - navigate back to parent with refresh state
            if (import.meta.env.DEV) {
              console.log(
                "[CollectionCreate] Navigating to parent collection with refresh",
              );
            }
            navigate(`/file-manager/collections/${parentCollectionId}`, {
              state: { refresh: true, newCollectionCreated: true },
              replace: false,
            });
          } else {
            // Creating a root collection - navigate to file manager index with refresh event
            if (import.meta.env.DEV) {
              console.log(
                "[CollectionCreate] Navigating to file manager with cache invalidation",
              );
            }

            // Dispatch a custom event to notify FileManagerIndex to refresh its cache
            if (typeof window !== "undefined") {
              window.dispatchEvent(
                new CustomEvent("rootCollectionCreated", {
                  detail: {
                    collectionId: result.collectionId,
                    name: collectionData.name,
                    timestamp: Date.now(),
                  },
                }),
              );
            }

            // Navigate to the file manager index (which will refresh due to the event)
            navigate("/file-manager", {
              state: { refresh: true, newRootCollectionCreated: true },
              replace: false,
            });
          }
        }
      } catch (err) {
        if (import.meta.env.DEV) {
          console.error("[CollectionCreate] Collection creation failed:", err);
        }

        // Parse RFC 9457 error response
        if (err.fieldErrors && Object.keys(err.fieldErrors).length > 0) {
          setErrors(err.fieldErrors);
        }

        if (err.message) {
          // Clean up technical error messages for better UX
          let userMessage = err.message;

          // Remove technical prefixes
          userMessage = userMessage.replace(
            /^Failed to create collection:\s*/i,
            "",
          );
          userMessage = userMessage.replace(/^Request failed:\s*/i, "");
          userMessage = userMessage.replace(/^Error:\s*/i, "");

          // Replace generic validation message with friendlier one
          if (userMessage.includes("One or more fields failed validation")) {
            userMessage = "Please check the folder information and try again.";
          }

          setGeneralError(userMessage);
        } else {
          setGeneralError("Could not create folder. Please try again.");
        }
      } finally {
        setIsLoading(false);
      }
    },
    [
      collectionName,
      customIcon,
      parentCollectionId,
      selectedTagIds,
      createCollectionManager,
      navigate,
    ],
  );

  // Breadcrumb items for navigation
  const breadcrumbItems = useMemo(() => {
    const items = [
      {
        label: "Dashboard",
        to: "/dashboard",
        icon: HomeIcon,
      },
      {
        label: "File Manager",
        to: "/file-manager",
        icon: FolderIcon,
      },
    ];

    // If creating inside a parent collection, add it to the breadcrumb
    if (parentCollectionId && parentCollectionName) {
      items.push({
        label: parentCollectionName,
        to: `/file-manager/collections/${parentCollectionId}`,
      });
    }

    // Current page (Create Folder)
    items.push({
      label: "Create Folder",
      isActive: true,
    });

    return items;
  }, [parentCollectionId, parentCollectionName]);

  return (
    <Layout>
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {/* Breadcrumb Navigation */}
        <Breadcrumb items={breadcrumbItems} />

        {/* Form */}
        <Card>
          <div className={`p-6 border-b ${getThemeClasses("border-secondary")}`}>
            {/* Header with icon */}
            <div className="flex items-start">
              {/* Icon */}
              <div className={`p-3 rounded-2xl shadow-lg mr-4 flex-shrink-0 ${getThemeClasses("bg-gradient-secondary")}`}>
                <PlusIcon className="h-8 w-8 sm:h-10 sm:w-10 text-white" />
              </div>
              {/* Title and subtitle */}
              <div>
                <h1 className={`text-2xl sm:text-3xl lg:text-4xl font-bold ${getThemeClasses("text-primary")} leading-tight`}>
                  Create New Folder
                </h1>
                <p className={`mt-2 text-base sm:text-lg lg:text-xl ${getThemeClasses("text-secondary")} font-medium`}>
                  {parentCollectionName
                    ? `Creating folder inside: ${parentCollectionName}`
                    : "Creating a root-level folder"}
                </p>
              </div>
            </div>
          </div>

          <div className="p-6">
            <form onSubmit={handleCreateCollection}>
              {/* Error Alert */}
              {(generalError || Object.keys(errors).length > 0) && (
                <div className="mb-6">
                  <Alert type="error">
                    <div className="space-y-2">
                      <p className="font-semibold">Unable to Create Folder</p>
                      {generalError && <p>{generalError}</p>}
                      {Object.keys(errors).length > 0 && (
                        <div>
                          <p className="font-medium mb-1">
                            Please fix the following errors:
                          </p>
                          <ul className="list-disc list-inside space-y-1 ml-2">
                            {Object.entries(errors).map(([field, message]) => (
                              <li key={field}>
                                <span className="font-medium">
                                  {field
                                    .replace(/_/g, " ")
                                    .replace(/\b\w/g, (l) => l.toUpperCase())}
                                  :
                                </span>{" "}
                                {message}
                              </li>
                            ))}
                          </ul>
                        </div>
                      )}
                    </div>
                  </Alert>
                </div>
              )}

              {/* Name Input */}
              <div className="mb-6">
                <Input
                  label="Folder Name"
                  type="text"
                  value={collectionName}
                  onChange={handleNameChange}
                  placeholder="Enter folder name"
                  disabled={isLoading}
                  error={errors.name || errors.Name || errors.collection_name}
                  required
                  autoFocus
                  maxLength={100}
                />
                {collectionName.trim() && collectionName.trim().length < 2 && (
                  <p className={`mt-1 text-sm ${getThemeClasses("text-warning")}`}>
                    Name should be at least 2 characters
                  </p>
                )}
              </div>

              {/* Custom Icon and Tags - Two Column Layout */}
              <div className="mb-6 grid grid-cols-1 lg:grid-cols-2 gap-6 items-stretch">
                {/* Custom Icon Section */}
                <div className="flex flex-col">
                  <label className={`block text-sm font-medium ${getThemeClasses("text-primary")} mb-3`}>
                    <span className="flex items-center">
                      <SparklesIcon className="h-4 w-4 mr-2" />
                      Customize Icon
                      <span className={`ml-2 text-xs font-normal ${getThemeClasses("text-secondary")}`}>
                        (Optional)
                      </span>
                    </span>
                  </label>
                  <div className={`flex items-center p-4 rounded-lg border ${getThemeClasses("border-secondary")} ${getThemeClasses("bg-muted")} flex-1`}>
                    <CollectionIconPreview
                      customIcon={customIcon}
                      collectionType={collectionType}
                      size="xl"
                      className="mr-4"
                    />
                    <div className="flex-1">
                      <p className={`text-sm ${getThemeClasses("text-primary")} font-medium mb-1`}>
                        {customIcon ? "Custom Icon" : "Default Icon"}
                      </p>
                      <p className={`text-xs ${getThemeClasses("text-secondary")} mb-3`}>
                        {customIcon
                          ? "Click to change or reset to default"
                          : "Add a custom emoji or icon to personalize your folder"}
                      </p>
                      <div className="flex space-x-2">
                        <Button
                          type="button"
                          onClick={handleOpenIconPicker}
                          disabled={isLoading}
                          variant="secondary"
                          size="sm"
                        >
                          {customIcon ? "Change Icon" : "Choose Icon"}
                        </Button>
                        {customIcon && (
                          <Button
                            type="button"
                            onClick={() => setCustomIcon("")}
                            disabled={isLoading}
                            variant="ghost"
                            size="sm"
                          >
                            Reset
                          </Button>
                        )}
                      </div>
                    </div>
                  </div>
                </div>

                {/* Tag Selection */}
                <div className="flex flex-col">
                  <TagSelector
                    value={selectedTagIds}
                    onChange={handleTagChange}
                    disabled={isLoading}
                    label="Tags"
                    placeholder="Search tags..."
                  />
                </div>
              </div>

              {/* Submit Button */}
              <Button
                type="submit"
                variant="primary"
                disabled={
                  isLoading ||
                  !collectionName.trim() ||
                  collectionName.trim().length < 2
                }
                className="w-full"
              >
                {isLoading ? "Creating..." : "Create Folder"}
              </Button>

              {!collectionName.trim() && (
                <p className={`mt-2 text-sm ${getThemeClasses("text-secondary")} text-center`}>
                  Please enter a folder name to continue
                </p>
              )}
            </form>
          </div>
        </Card>
      </div>

      {/* Icon Picker Modal */}
      <IconPicker
        isOpen={showIconPicker}
        value={customIcon}
        onChange={handleIconChange}
        onClose={handleCloseIconPicker}
      />
    </Layout>
  );
};

export default withPasswordProtection(CollectionCreate);
