// File: src/pages/User/FileManager/Collections/CollectionEdit.jsx
// NOTE: This is a mock/placeholder page - the logic is not implemented yet
import React, { useState, useEffect, useRef, useCallback } from "react";
import { useNavigate, useParams } from "react-router";
import withPasswordProtection from "../../../../hocs/withPasswordProtection";
import Layout from "../../../../components/Layout/Layout";
import {
  Button,
  Input,
  Alert,
  Card,
  Breadcrumb,
  Modal,
  Select,
  useUIXTheme,
} from "../../../../components/UIX";
import {
  FolderIcon,
  PhotoIcon,
  ArrowLeftIcon,
  UsersIcon,
  CheckIcon,
  XMarkIcon,
  PlusIcon,
  DocumentDuplicateIcon,
  GlobeAltIcon,
  HomeIcon,
  ExclamationTriangleIcon,
  TrashIcon,
  ArrowPathIcon,
  LockClosedIcon,
  Cog6ToothIcon,
} from "@heroicons/react/24/outline";

const CollectionEdit = () => {
  const navigate = useNavigate();
  const { collectionId } = useParams();
  const { getThemeClasses } = useUIXTheme();
  const isMountedRef = useRef(true);

  // Cleanup on unmount
  useEffect(() => {
    isMountedRef.current = true;
    return () => {
      isMountedRef.current = false;
    };
  }, []);

  // Mock existing collection data
  const [collectionData] = useState({
    id: collectionId || "1",
    name: "Work Documents",
    type: "folder",
    description: "Important work-related documents and presentations",
    parentCollection: null,
    privacyMode: "shared",
    sharedWith: [
      {
        id: 1,
        name: "Alice Johnson",
        email: "alice@example.com",
        avatar: "AJ",
        role: "viewer",
      },
      {
        id: 2,
        name: "Bob Smith",
        email: "bob@example.com",
        avatar: "BS",
        role: "editor",
      },
    ],
    created: "January 15, 2024",
    modified: "2 hours ago",
    itemCount: 24,
    totalSize: "1.2 GB",
  });

  const [formData, setFormData] = useState({
    name: collectionData.name,
    description: collectionData.description,
    parentCollection: collectionData.parentCollection,
    privacyMode: collectionData.privacyMode,
  });

  const [selectedUsers, setSelectedUsers] = useState(collectionData.sharedWith);
  const [showUserSearch, setShowUserSearch] = useState(false);
  const [userSearchQuery, setUserSearchQuery] = useState("");
  const [hasChanges, setHasChanges] = useState(false);
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  const [isLoading, setIsLoading] = useState(false);

  // Mock users for sharing
  const mockUsers = [
    { id: 3, name: "Carol Williams", email: "carol@example.com", avatar: "CW" },
    { id: 4, name: "David Brown", email: "david@example.com", avatar: "DB" },
    { id: 5, name: "Eva Martinez", email: "eva@example.com", avatar: "EM" },
  ];

  useEffect(() => {
    // Check if any changes were made
    const changed =
      formData.name !== collectionData.name ||
      formData.description !== collectionData.description ||
      formData.parentCollection !== collectionData.parentCollection ||
      formData.privacyMode !== collectionData.privacyMode ||
      JSON.stringify(selectedUsers) !==
        JSON.stringify(collectionData.sharedWith);

    setHasChanges(changed);
  }, [formData, selectedUsers, collectionData]);

  const handleAddUser = useCallback((user) => {
    setSelectedUsers((prev) => {
      if (!prev.find((u) => u.id === user.id)) {
        return [...prev, { ...user, role: "viewer" }];
      }
      return prev;
    });
    setShowUserSearch(false);
    setUserSearchQuery("");
  }, []);

  const handleRemoveUser = useCallback((userId) => {
    setSelectedUsers((prev) => prev.filter((u) => u.id !== userId));
  }, []);

  const handleUserRoleChange = useCallback((userId, newRole) => {
    setSelectedUsers((prev) =>
      prev.map((u) => (u.id === userId ? { ...u, role: newRole } : u))
    );
  }, []);

  const handleSave = useCallback(() => {
    if (!isMountedRef.current) return;
    setIsLoading(true);
    // Simulate save
    setTimeout(() => {
      if (isMountedRef.current) {
        navigate(`/file-manager/collections/${collectionId}`);
      }
    }, 1000);
  }, [navigate, collectionId]);

  const handleDelete = useCallback(() => {
    // Simulate delete
    navigate("/file-manager");
  }, [navigate]);

  const handleReset = useCallback(() => {
    setFormData({
      name: collectionData.name,
      description: collectionData.description,
      parentCollection: collectionData.parentCollection,
      privacyMode: collectionData.privacyMode,
    });
    setSelectedUsers(collectionData.sharedWith);
  }, [collectionData]);

  // Breadcrumb items
  const breadcrumbItems = [
    { label: "My Files", to: "/file-manager", icon: HomeIcon },
    { label: collectionData.name, to: `/file-manager/collections/${collectionId}`, icon: FolderIcon },
    { label: "Edit", isActive: true },
  ];

  // Parent collection options
  const parentOptions = [
    { value: "", label: "Root level (no parent)" },
    { value: "2", label: "Personal Files" },
    { value: "3", label: "Archive" },
    { value: "4", label: "Shared Projects" },
  ];

  // Role options
  const roleOptions = [
    { value: "viewer", label: "Can view" },
    { value: "editor", label: "Can edit" },
  ];

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

        {/* Main Card */}
        <Card>
          {/* Header */}
          <div className={`p-6 border-b ${getThemeClasses("border-secondary")}`}>
            <div className="flex flex-col space-y-4 lg:flex-row lg:items-center lg:justify-between lg:space-y-0">
              <div className="flex-1 min-w-0">
                <div className="flex items-start">
                  <div className={`p-3 rounded-2xl shadow-lg mr-4 flex-shrink-0 ${getThemeClasses("bg-gradient-secondary")}`}>
                    <Cog6ToothIcon className="h-8 w-8 sm:h-10 sm:w-10 text-white" />
                  </div>
                  <div>
                    <h1 className={`text-2xl sm:text-3xl lg:text-4xl font-bold ${getThemeClasses("text-primary")} leading-tight`}>
                      Edit Collection
                    </h1>
                    <p className={`mt-2 text-base sm:text-lg ${getThemeClasses("text-secondary")}`}>
                      Update collection settings and permissions
                    </p>
                  </div>
                </div>
              </div>
              <div className="flex items-center gap-3">
                {hasChanges && (
                  <div className={`flex items-center ${getThemeClasses("bg-warning-light")} ${getThemeClasses("text-warning")} px-4 py-2 rounded-lg`}>
                    <ExclamationTriangleIcon className="h-5 w-5 mr-2" />
                    <span className="text-sm font-medium">Unsaved changes</span>
                  </div>
                )}
                <Button
                  onClick={() => navigate(`/file-manager/collections/${collectionId}`)}
                  variant="secondary"
                  size="sm"
                >
                  <span className="inline-flex items-center gap-2">
                    <ArrowLeftIcon className="h-4 w-4" />
                    <span>Back</span>
                  </span>
                </Button>
              </div>
            </div>
          </div>

          {/* Content */}
          <div className="p-6 space-y-6">
            {/* Collection Info Summary */}
            <Card className={`border ${getThemeClasses("border-muted")} p-6`}>
              <div className="flex items-center justify-between flex-wrap gap-4">
                <div className="flex items-center space-x-4">
                  <div className={`flex items-center justify-center h-12 w-12 rounded-lg ${
                    collectionData.type === "album"
                      ? getThemeClasses("bg-accent-light")
                      : getThemeClasses("bg-info-light")
                  }`}>
                    {collectionData.type === "album" ? (
                      <PhotoIcon className={`h-6 w-6 ${getThemeClasses("text-accent")}`} />
                    ) : (
                      <FolderIcon className={`h-6 w-6 ${getThemeClasses("text-info")}`} />
                    )}
                  </div>
                  <div>
                    <p className={`text-sm ${getThemeClasses("text-secondary")}`}>Collection Type</p>
                    <p className={`font-semibold ${getThemeClasses("text-primary")} capitalize`}>
                      {collectionData.type}
                    </p>
                  </div>
                </div>

                <div className="flex gap-8">
                  <div className="text-center">
                    <p className={`text-2xl font-bold ${getThemeClasses("text-primary")}`}>
                      {collectionData.itemCount}
                    </p>
                    <p className={`text-sm ${getThemeClasses("text-secondary")}`}>Items</p>
                  </div>
                  <div className="text-center">
                    <p className={`text-2xl font-bold ${getThemeClasses("text-primary")}`}>
                      {collectionData.totalSize}
                    </p>
                    <p className={`text-sm ${getThemeClasses("text-secondary")}`}>Total Size</p>
                  </div>
                  <div className="text-center">
                    <p className={`text-2xl font-bold ${getThemeClasses("text-primary")}`}>
                      {selectedUsers.length}
                    </p>
                    <p className={`text-sm ${getThemeClasses("text-secondary")}`}>Shared</p>
                  </div>
                </div>
              </div>
            </Card>

            {/* Basic Information */}
            <Card className={`border ${getThemeClasses("border-muted")} p-6`}>
              <h2 className={`text-lg font-semibold ${getThemeClasses("text-primary")} mb-4 flex items-center`}>
                <DocumentDuplicateIcon className={`h-5 w-5 mr-2 ${getThemeClasses("text-secondary")}`} />
                Basic Information
              </h2>

              <div className="space-y-4">
                <Input
                  label="Collection Name"
                  type="text"
                  name="collection_name"
                  value={formData.name}
                  onChange={(value) => setFormData((prev) => ({ ...prev, name: value }))}
                  placeholder="Enter collection name"
                  required
                  disabled={isLoading}
                  icon={FolderIcon}
                />

                <div>
                  <label className={`block text-sm font-medium ${getThemeClasses("text-primary")} mb-2`}>
                    Description
                  </label>
                  <textarea
                    name="description"
                    value={formData.description}
                    onChange={(e) => setFormData((prev) => ({ ...prev, description: e.target.value }))}
                    rows={3}
                    disabled={isLoading}
                    className={`w-full px-4 py-3 border rounded-xl ${getThemeClasses("bg-input")} ${getThemeClasses("border-input")} ${getThemeClasses("text-primary")} ${getThemeClasses("placeholder-muted")} focus:ring-2 focus:ring-red-500 focus:border-red-500 transition-all duration-200 disabled:opacity-50`}
                    placeholder="Optional description for this collection"
                  />
                </div>

                <Select
                  label="Parent Collection"
                  name="parent_collection"
                  value={formData.parentCollection || ""}
                  onChange={(value) => setFormData((prev) => ({ ...prev, parentCollection: value || null }))}
                  options={parentOptions}
                  disabled={isLoading}
                />
              </div>
            </Card>

            {/* Privacy & Sharing */}
            <Card className={`border ${getThemeClasses("border-muted")} p-6`}>
              <h2 className={`text-lg font-semibold ${getThemeClasses("text-primary")} mb-4 flex items-center`}>
                <UsersIcon className={`h-5 w-5 mr-2 ${getThemeClasses("text-secondary")}`} />
                Privacy & Sharing
              </h2>

              {/* Privacy Mode */}
              <div className="mb-6">
                <label className={`block text-sm font-medium ${getThemeClasses("text-primary")} mb-3`}>
                  Privacy Mode
                </label>
                <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
                  {[
                    { value: "private", icon: LockClosedIcon, label: "Private", desc: "Only you" },
                    { value: "shared", icon: UsersIcon, label: "Shared", desc: "Specific users" },
                    { value: "public", icon: GlobeAltIcon, label: "Public", desc: "Anyone with link" },
                  ].map((option) => (
                    <label
                      key={option.value}
                      className={`relative flex cursor-pointer rounded-lg border p-4 transition-all duration-200 ${
                        formData.privacyMode === option.value
                          ? `${getThemeClasses("border-accent")} ${getThemeClasses("bg-accent-light")}`
                          : `${getThemeClasses("border-secondary")} ${getThemeClasses("hover:bg-muted")}`
                      }`}
                    >
                      <input
                        type="radio"
                        name="privacyMode"
                        value={option.value}
                        checked={formData.privacyMode === option.value}
                        onChange={(e) => setFormData((prev) => ({ ...prev, privacyMode: e.target.value }))}
                        className="sr-only"
                        disabled={isLoading}
                      />
                      <div className="flex items-center">
                        <option.icon
                          className={`h-5 w-5 mr-2 ${
                            formData.privacyMode === option.value
                              ? getThemeClasses("text-accent")
                              : getThemeClasses("text-secondary")
                          }`}
                        />
                        <div>
                          <p className={`font-medium ${getThemeClasses("text-primary")}`}>{option.label}</p>
                          <p className={`text-xs ${getThemeClasses("text-secondary")}`}>{option.desc}</p>
                        </div>
                      </div>
                      {formData.privacyMode === option.value && (
                        <CheckIcon className={`absolute top-3 right-3 h-4 w-4 ${getThemeClasses("text-accent")}`} />
                      )}
                    </label>
                  ))}
                </div>
              </div>

              {/* Share with Users */}
              {formData.privacyMode === "shared" && (
                <div>
                  <label className={`block text-sm font-medium ${getThemeClasses("text-primary")} mb-3`}>
                    Shared with
                  </label>

                  {/* Current Shared Users */}
                  {selectedUsers.length > 0 && (
                    <div className="mb-3 space-y-2">
                      {selectedUsers.map((user) => (
                        <div
                          key={user.id}
                          className={`flex items-center justify-between p-3 ${getThemeClasses("bg-muted")} rounded-lg`}
                        >
                          <div className="flex items-center">
                            <div className={`flex items-center justify-center h-8 w-8 ${getThemeClasses("bg-accent-light")} ${getThemeClasses("text-accent")} text-sm font-medium rounded-full mr-3`}>
                              {user.avatar}
                            </div>
                            <div>
                              <p className={`text-sm font-medium ${getThemeClasses("text-primary")}`}>
                                {user.name}
                              </p>
                              <p className={`text-xs ${getThemeClasses("text-secondary")}`}>
                                {user.email}
                              </p>
                            </div>
                          </div>
                          <div className="flex items-center space-x-2">
                            <Select
                              name={`role_${user.id}`}
                              value={user.role}
                              onChange={(value) => handleUserRoleChange(user.id, value)}
                              options={roleOptions}
                              size="sm"
                              disabled={isLoading}
                            />
                            <button
                              onClick={() => handleRemoveUser(user.id)}
                              className={`${getThemeClasses("text-secondary")} ${getThemeClasses("hover:text-error")} transition-colors duration-200`}
                              disabled={isLoading}
                            >
                              <XMarkIcon className="h-4 w-4" />
                            </button>
                          </div>
                        </div>
                      ))}
                    </div>
                  )}

                  {/* Add User Button */}
                  <Button
                    onClick={() => setShowUserSearch(!showUserSearch)}
                    variant="secondary"
                    size="sm"
                    disabled={isLoading}
                  >
                    <span className="inline-flex items-center gap-2">
                      <PlusIcon className="h-4 w-4" />
                      <span>Add Users</span>
                    </span>
                  </Button>

                  {/* User Search Dropdown */}
                  {showUserSearch && (
                    <div className={`mt-3 p-4 ${getThemeClasses("bg-muted")} rounded-lg border ${getThemeClasses("border-muted")}`}>
                      <Input
                        type="text"
                        name="user_search"
                        value={userSearchQuery}
                        onChange={(value) => setUserSearchQuery(value)}
                        placeholder="Search by name or email..."
                        size="sm"
                      />
                      <div className="mt-3 space-y-2 max-h-48 overflow-y-auto">
                        {mockUsers
                          .filter((u) => !selectedUsers.find((su) => su.id === u.id))
                          .map((user) => (
                            <button
                              key={user.id}
                              onClick={() => handleAddUser(user)}
                              className={`w-full flex items-center p-2 ${getThemeClasses("hover:bg-card")} rounded-lg transition-colors duration-200`}
                            >
                              <div className={`flex items-center justify-center h-8 w-8 ${getThemeClasses("bg-accent-light")} ${getThemeClasses("text-accent")} text-sm font-medium rounded-full mr-3`}>
                                {user.avatar}
                              </div>
                              <div className="text-left">
                                <p className={`text-sm font-medium ${getThemeClasses("text-primary")}`}>
                                  {user.name}
                                </p>
                                <p className={`text-xs ${getThemeClasses("text-secondary")}`}>
                                  {user.email}
                                </p>
                              </div>
                            </button>
                          ))}
                      </div>
                    </div>
                  )}
                </div>
              )}
            </Card>

            {/* Danger Zone */}
            <Card className={`border ${getThemeClasses("border-error")} ${getThemeClasses("bg-error-light")} p-6`}>
              <h2 className={`text-lg font-semibold ${getThemeClasses("text-error")} mb-4 flex items-center`}>
                <ExclamationTriangleIcon className="h-5 w-5 mr-2" />
                Danger Zone
              </h2>

              <div className="flex items-center justify-between flex-wrap gap-4">
                <div>
                  <h3 className={`font-medium ${getThemeClasses("text-primary")}`}>
                    Delete this collection
                  </h3>
                  <p className={`text-sm ${getThemeClasses("text-secondary")} mt-1`}>
                    Once deleted, this collection and all its contents cannot be recovered.
                  </p>
                </div>
                <Button
                  onClick={() => setShowDeleteConfirm(true)}
                  variant="danger"
                  size="sm"
                  disabled={isLoading}
                >
                  Delete Collection
                </Button>
              </div>
            </Card>

            {/* Action Buttons */}
            <div className={`flex items-center justify-between pt-6 border-t ${getThemeClasses("border-muted")}`}>
              <Button
                onClick={() => navigate(`/file-manager/collections/${collectionId}`)}
                variant="secondary"
                disabled={isLoading}
              >
                Cancel
              </Button>

              <div className="flex items-center gap-3">
                {hasChanges && (
                  <Button
                    onClick={handleReset}
                    variant="ghost"
                    size="sm"
                    disabled={isLoading}
                  >
                    <span className="inline-flex items-center gap-1">
                      <ArrowPathIcon className="h-4 w-4" />
                      <span>Reset</span>
                    </span>
                  </Button>
                )}
                <Button
                  onClick={handleSave}
                  variant="primary"
                  disabled={!hasChanges || !formData.name.trim() || isLoading}
                  loading={isLoading}
                >
                  {!isLoading && (
                    <span className="inline-flex items-center gap-2">
                      <CheckIcon className="h-4 w-4" />
                      <span>Save Changes</span>
                    </span>
                  )}
                  {isLoading && "Saving..."}
                </Button>
              </div>
            </div>
          </div>
        </Card>
      </div>

      {/* Delete Confirmation Modal */}
      <Modal
        isOpen={showDeleteConfirm}
        onClose={() => setShowDeleteConfirm(false)}
        title="Delete Collection"
        size="md"
      >
        <div className="mb-6">
          <div className={`flex items-center justify-center h-12 w-12 ${getThemeClasses("bg-error-light")} rounded-lg mb-4`}>
            <TrashIcon className={`h-6 w-6 ${getThemeClasses("text-error")}`} />
          </div>
          <p className={`${getThemeClasses("text-primary")} mb-2`}>
            Are you sure you want to delete{" "}
            <strong>{collectionData.name}</strong>?
          </p>
          <p className={`text-sm ${getThemeClasses("text-secondary")}`}>
            This will permanently delete the collection and all{" "}
            {collectionData.itemCount} items inside it. This action cannot
            be undone.
          </p>
        </div>

        <div className="flex justify-end space-x-3">
          <Button
            onClick={() => setShowDeleteConfirm(false)}
            variant="secondary"
          >
            Cancel
          </Button>
          <Button
            onClick={handleDelete}
            variant="danger"
          >
            Delete Collection
          </Button>
        </div>
      </Modal>
    </Layout>
  );
};

export default withPasswordProtection(CollectionEdit);
