// File: src/pages/User/FileManager/Collections/CollectionShare.jsx
import React, { useState, useEffect, useMemo, useCallback, useRef } from "react";
import { useParams } from "react-router";
import {
  useFiles,
  useAuth,
  useUsers,
  useCollections,
  useDashboard,
} from "../../../../services/Services";
import withPasswordProtection from "../../../../hocs/withPasswordProtection";
import Layout from "../../../../components/Layout/Layout";
import { Button, Alert, useUIXTheme, Breadcrumb, Card, Input, IconDropdown, UserListItem, InfoNotice, Modal, Checkbox } from "../../../../components/UIX";
import {
  ShareIcon,
  UserPlusIcon,
  TrashIcon,
  CheckIcon,
  EnvelopeIcon,
  LockClosedIcon,
  ShieldCheckIcon,
  UserGroupIcon,
  PencilIcon,
  EyeIcon,
  HomeIcon,
  FolderIcon,
  PaperAirplaneIcon,
} from "@heroicons/react/24/outline";
import InviteEmailAPIService from "../../../../services/API/InviteEmail/InviteEmailAPIService";

const CollectionShare = () => {
  const { collectionId } = useParams();
  const { getCollectionManager } = useFiles();
  const { shareCollectionManager } = useCollections();
  const { authManager } = useAuth();
  const { userLookupManager } = useUsers();
  const { dashboardManager } = useDashboard();
  const { getThemeClasses } = useUIXTheme();

  // GDPR-compliant logging - sanitize PII
  // Use console.warn for client errors (4xx), console.error for server errors (5xx)
  const logError = (context, error) => {
    if (import.meta.env.DEV) {
      if (error?.status && error.status >= 400 && error.status < 500) {
        console.warn(`[CollectionShare] ${context} (client error):`, error?.message || 'Unknown error');
      } else {
        console.error(`[CollectionShare] ${context} (server error):`, error?.message || 'Unknown error');
      }
    }
  };

  // Email validation
  const isValidEmail = (email) => {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
  };

  const [isLoading, setIsLoading] = useState(false);
  const [isVerifying, setIsVerifying] = useState(false);
  const [error, setError] = useState("");
  const [success, setSuccess] = useState("");
  const [collection, setCollection] = useState(null);
  const [collectionMembers, setCollectionMembers] = useState([]);
  const [recipientEmail, setRecipientEmail] = useState("");
  const [recipientId, setRecipientId] = useState("");
  const [recipientVerified, setRecipientVerified] = useState(false);
  const [recipientInfo, setRecipientInfo] = useState(null);
  const [permissionLevel, setPermissionLevel] = useState("read_write");
  const [ownerEmail, setOwnerEmail] = useState("");
  const [showRemoveModal, setShowRemoveModal] = useState(false);
  const [memberToRemove, setMemberToRemove] = useState(null);
  const [gdprConsent, setGdprConsent] = useState(false);

  // Invite state
  const [userNotFound, setUserNotFound] = useState(false);
  const [isSendingInvite, setIsSendingInvite] = useState(false);
  const [inviteSuccess, setInviteSuccess] = useState("");
  const [inviteEmailService] = useState(() => new InviteEmailAPIService());

  // Refs for cleanup
  const shareTimeoutRef = useRef(null);
  const removeTimeoutRef = useRef(null);
  const verifyDebounceRef = useRef(null);

  // Memoize permission levels to prevent unnecessary re-renders
  const permissionLevels = useMemo(() => [
    {
      value: "read_only",
      label: "View Only",
      description: "Can view and download files",
      icon: EyeIcon,
      color: "text-blue-600",
    },
    {
      value: "read_write",
      label: "Can Edit",
      description: "Can add, edit, and delete files",
      icon: PencilIcon,
      color: "text-green-600",
    },
    {
      value: "admin",
      label: "Full Access",
      description: "Can manage sharing and permissions",
      icon: ShieldCheckIcon,
      color: "text-purple-600",
    },
  ], []);

  // Sanitize filename to prevent path traversal and special character issues
  const sanitizeFilename = useCallback((filename) => {
    return filename
      .replace(/[^a-z0-9_-]/gi, '_')  // Replace non-alphanumeric with underscore
      .replace(/_+/g, '_')             // Collapse multiple underscores
      .substring(0, 50);               // Limit length
  }, []);

  // Export members list (GDPR Article 20 - Data Portability)
  const handleExportMembers = useCallback(() => {
    const exportData = {
      collection_name: collection?.name,
      exported_at: new Date().toISOString(),
      owner: ownerEmail,
      members: collectionMembers.map(m => ({
        email: m.recipient_email,
        permission: m.permission_level,
        shared_at: m.shared_at
      }))
    };

    const blob = new Blob([JSON.stringify(exportData, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    // Sanitize collection name for safe filename
    const safeName = sanitizeFilename(collection?.name || 'folder');
    a.download = `${safeName}_sharing_${Date.now()}.json`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  }, [collection, ownerEmail, collectionMembers, sanitizeFilename]);

  useEffect(() => {
    if (collectionId && getCollectionManager && shareCollectionManager) {
      loadCollectionData();
      // Force refresh members on initial load to get latest data
      loadCollectionMembers(true);
    }
  }, [collectionId, getCollectionManager, shareCollectionManager, loadCollectionData, loadCollectionMembers]);

  // Clear messages after 5 seconds
  useEffect(() => {
    if (success || error) {
      const timer = setTimeout(() => {
        setError("");
        setSuccess("");
      }, 5000);
      return () => clearTimeout(timer);
    }
  }, [success, error]);

  // Cleanup timeouts on unmount
  useEffect(() => {
    return () => {
      if (shareTimeoutRef.current) clearTimeout(shareTimeoutRef.current);
      if (removeTimeoutRef.current) clearTimeout(removeTimeoutRef.current);
      if (verifyDebounceRef.current) clearTimeout(verifyDebounceRef.current);
    };
  }, []);

  const loadCollectionData = useCallback(async () => {
    try {
      // Force refresh to get latest data including owner_email from backend
      const result = await getCollectionManager.getCollection(collectionId, true);
      if (result.collection) {
        setCollection(result.collection);

        // Use owner_email from backend response
        if (result.collection.owner_email) {
          setOwnerEmail(result.collection.owner_email);
        } else {
          // Fallback: try to determine from current user if they're the owner
          if (result.collection.owner_id && authManager) {
            try {
              const currentUserId = authManager.getCurrentUserId?.() || authManager.userId;
              const currentEmail = authManager.getCurrentUserEmail();
              if (result.collection.owner_id === currentUserId) {
                setOwnerEmail(currentEmail);
              }
            } catch (lookupErr) {
              if (import.meta.env.DEV) {
                console.warn("Could not determine owner email:", lookupErr);
              }
            }
          }
        }
      }
    } catch (err) {
      logError("Failed to load collection", err);

      if (err.message) {
        let userMessage = err.message;
        userMessage = userMessage.replace(/^Failed to load collection:\s*/i, '');
        userMessage = userMessage.replace(/^Request failed:\s*/i, '');
        userMessage = userMessage.replace(/^Error:\s*/i, '');
        setError(userMessage);
      } else {
        setError("Could not load folder details. Please try again.");
      }
    }
  }, [collectionId, getCollectionManager, authManager]);

  const loadCollectionMembers = useCallback(async (forceRefresh = false) => {
    setIsLoading(true);
    try {
      const members = await shareCollectionManager.getCollectionMembers(
        collectionId,
        forceRefresh,
      );
      if (!Array.isArray(members)) {
        logError("Members is not an array", new Error("Invalid data type"));
        setCollectionMembers([]);
        return;
      }
      setCollectionMembers(members);
      if (members.length === 0 && success) {
        setError(
          "Collection shared successfully, but member list may take a moment to update. Try refreshing in a few seconds.",
        );
      }
    } catch (err) {
      logError("Failed to load members", err);

      if (err.message) {
        let userMessage = err.message;
        userMessage = userMessage.replace(/^Failed to load members:\s*/i, '');
        userMessage = userMessage.replace(/^Request failed:\s*/i, '');
        userMessage = userMessage.replace(/^Error:\s*/i, '');
        setError("Could not load folder members: " + userMessage);
      } else {
        setError("Could not load folder members. Please try again.");
      }
      try {
        const localShares =
          shareCollectionManager.getSharedCollectionsByCollectionId(
            collectionId,
          );
        if (localShares && localShares.length > 0) {
          const membersFromLocal = localShares.map((share) => ({
            recipient_id: share.recipient_id,
            recipient_email: share.recipient_email,
            permission_level: share.permission_level,
            shared_at: share.shared_at || share.locally_stored_at,
          }));
          setCollectionMembers(membersFromLocal);
        }
      } catch (localErr) {
        logError("Failed to get local shares", localErr);
      }
    } finally {
      setIsLoading(false);
    }
  }, [collectionId, shareCollectionManager, success]);

  const handleVerifyRecipient = useCallback(async () => {
    // Clear any pending debounce
    if (verifyDebounceRef.current) {
      clearTimeout(verifyDebounceRef.current);
    }

    if (!recipientEmail.trim()) {
      setError("Please enter an email address");
      return;
    }

    // Email format validation
    if (!isValidEmail(recipientEmail.trim())) {
      setError("Please enter a valid email address");
      return;
    }

    const currentUserEmail = authManager.getCurrentUserEmail();
    if (
      recipientEmail.trim().toLowerCase() === currentUserEmail?.toLowerCase()
    ) {
      setError("You cannot share a folder with yourself");
      return;
    }

    setRecipientVerified(false);
    setRecipientId("");
    setRecipientInfo(null);
    setError("");
    setSuccess("");
    setInviteSuccess("");
    setUserNotFound(false);
    setIsVerifying(true);

    // Debounce verification (300ms) to prevent spam
    verifyDebounceRef.current = setTimeout(async () => {
      try {
        const userInfo = await userLookupManager.getUserPublicKey(
          recipientEmail.trim(),
        );
        if (userInfo && userInfo.userId) {
          setRecipientId(userInfo.userId);
          setRecipientInfo(userInfo);
          setRecipientVerified(true);
          setUserNotFound(false);
        } else {
          throw new Error("User information incomplete");
        }
      } catch (err) {
        logError("User verification failed", err);

        let userMessage = err.message || '';
        userMessage = userMessage.replace(/^Failed to lookup user:\s*/i, '');
        userMessage = userMessage.replace(/^User lookup failed:\s*/i, '');
        userMessage = userMessage.replace(/^Request failed:\s*/i, '');
        userMessage = userMessage.replace(/^Error:\s*/i, '');

        // Check if this is a "user not found" error - show invite option
        const isNotFoundError = userMessage.includes('not found') ||
          userMessage.includes('User information incomplete') ||
          userMessage.includes('Unable to complete lookup') ||
          userMessage.includes('lookup failed') ||
          userMessage.includes('does not exist');

        if (isNotFoundError) {
          setUserNotFound(true);
          setError(""); // Don't show error, we'll show invite option instead
        } else {
          setUserNotFound(false);
          setError(userMessage || "Could not verify user. Please try again.");
        }

        setRecipientVerified(false);
        setRecipientId("");
        setRecipientInfo(null);
      } finally {
        setIsVerifying(false);
      }
    }, 300);
  }, [recipientEmail, authManager, userLookupManager]);

  // Handle sending invitation email to non-registered user
  const handleSendInvite = useCallback(async () => {
    if (!recipientEmail.trim()) {
      setError("Please enter an email address");
      return;
    }

    if (!isValidEmail(recipientEmail.trim())) {
      setError("Please enter a valid email address");
      return;
    }

    setIsSendingInvite(true);
    setError("");
    setInviteSuccess("");

    try {
      const result = await inviteEmailService.sendInviteEmail(recipientEmail.trim());

      if (result.success) {
        setInviteSuccess(result.message || `Invitation sent to ${recipientEmail}`);
        setUserNotFound(false);
        setRecipientEmail("");

        // Show remaining invites info if available
        if (result.remaining_invites_today !== undefined) {
          const remainingText = result.remaining_invites_today === 0
            ? "You've reached your daily invite limit."
            : `You can send ${result.remaining_invites_today} more invitation${result.remaining_invites_today === 1 ? '' : 's'} today.`;
          setInviteSuccess(prev => `${prev} ${remainingText}`);
        }
      } else {
        // Handle rate limit or user already exists responses
        setError(result.message || "Could not send invitation. Please try again.");
      }
    } catch (err) {
      logError("Failed to send invite", err);

      let userMessage = err.message || '';
      userMessage = userMessage.replace(/^Failed to send invitation:\s*/i, '');
      userMessage = userMessage.replace(/^Request failed:\s*/i, '');
      userMessage = userMessage.replace(/^Error:\s*/i, '');

      setError(userMessage || "Could not send invitation. Please try again.");
    } finally {
      setIsSendingInvite(false);
    }
  }, [recipientEmail, inviteEmailService]);

  const handleShareCollection = useCallback(async () => {
    if (!recipientVerified || !recipientId || !recipientEmail) {
      setError("Please verify the recipient first");
      return;
    }

    // GDPR consent validation
    if (!gdprConsent) {
      setError("Please consent to data processing before sharing");
      return;
    }

    setIsLoading(true);
    setError("");
    setSuccess("");

    try {
      await shareCollectionManager.shareCollection(
        collectionId,
        {
          recipient_id: recipientId,
          recipient_email: recipientEmail.trim(),
          permission_level: permissionLevel,
          share_with_descendants: true,
        },
        null, // Password will be retrieved automatically from PasswordStorageService
      );

      setSuccess(`Folder shared successfully with ${recipientEmail}!`);

      const newMember = {
        recipient_id: recipientId,
        recipient_email: recipientEmail.trim(),
        permission_level: permissionLevel,
        shared_at: new Date().toISOString(),
        _isLocal: true,
      };

      setCollectionMembers((prevMembers) => {
        const filtered = prevMembers.filter(
          (m) => m.recipient_id !== recipientId,
        );
        return [...filtered, newMember];
      });

      setRecipientEmail("");
      setRecipientId("");
      setRecipientVerified(false);
      setRecipientInfo(null);
      setPermissionLevel("read_write");
      setGdprConsent(false);

      // Clear any existing timeout and set new one with cleanup
      if (shareTimeoutRef.current) clearTimeout(shareTimeoutRef.current);
      shareTimeoutRef.current = setTimeout(() => {
        loadCollectionMembers(true);
      }, 1000);
    } catch (err) {
      logError("Failed to share collection", err);

      if (err.message) {
        let userMessage = err.message;
        userMessage = userMessage.replace(/^Failed to share collection:\s*/i, '');
        userMessage = userMessage.replace(/^Request failed:\s*/i, '');
        userMessage = userMessage.replace(/^Error:\s*/i, '');

        if (userMessage.includes('One or more fields failed validation')) {
          userMessage = 'Please check the sharing information and try again.';
        }

        setError(userMessage);
      } else {
        setError("Could not share folder. Please try again.");
      }
    } finally {
      setIsLoading(false);
    }
  }, [recipientVerified, recipientId, recipientEmail, gdprConsent, permissionLevel, collectionId, shareCollectionManager, loadCollectionMembers]);

  const handleRemoveMember = useCallback((memberId, memberEmail) => {
    setMemberToRemove({ id: memberId, email: memberEmail });
    setShowRemoveModal(true);
  }, []);

  const confirmRemoveMember = useCallback(async () => {
    if (!memberToRemove) return;

    setIsLoading(true);
    setError("");
    setSuccess("");
    setShowRemoveModal(false);

    try {
      setCollectionMembers((prevMembers) =>
        prevMembers.filter((m) => m.recipient_id !== memberToRemove.id),
      );

      await shareCollectionManager.removeMember(collectionId, memberToRemove.id, true);
      setSuccess(`${memberToRemove.email} removed from folder`);

      // Clear the dashboard cache to update stats for all users
      if (dashboardManager && dashboardManager.clearAllCaches) {
        dashboardManager.clearAllCaches();
      }

      // Dispatch event to notify other components (like sidebar)
      window.dispatchEvent(new CustomEvent("dashboardRefresh"));

      // Clear any existing timeout and set new one with cleanup
      if (removeTimeoutRef.current) clearTimeout(removeTimeoutRef.current);
      removeTimeoutRef.current = setTimeout(() => {
        loadCollectionMembers(true);
      }, 1000);
    } catch (err) {
      logError("Failed to remove member", err);

      if (err.message) {
        let userMessage = err.message;
        userMessage = userMessage.replace(/^Failed to remove member:\s*/i, '');
        userMessage = userMessage.replace(/^Request failed:\s*/i, '');
        userMessage = userMessage.replace(/^Error:\s*/i, '');
        setError("Could not remove member: " + userMessage);
      } else {
        setError("Could not remove member. Please try again.");
      }

      loadCollectionMembers(true);
    } finally {
      setIsLoading(false);
      setMemberToRemove(null);
    }
  }, [memberToRemove, collectionId, shareCollectionManager, dashboardManager, loadCollectionMembers]);

  const handleEmailChange = useCallback((newEmail) => {
    // UIX Input onChange receives value directly, not event
    setRecipientEmail(newEmail);

    if (recipientVerified) {
      setRecipientVerified(false);
      setRecipientId("");
      setRecipientInfo(null);
      setSuccess("");
    }
    // Clear invite-related states when email changes
    if (userNotFound) {
      setUserNotFound(false);
    }
    if (inviteSuccess) {
      setInviteSuccess("");
    }
    if (error) {
      setError("");
    }
    const currentUserEmail = authManager.getCurrentUserEmail();
    if (
      newEmail.trim().toLowerCase() === currentUserEmail?.toLowerCase() &&
      newEmail.trim()
    ) {
      setError("You cannot share a folder with yourself");
    }
  }, [recipientVerified, userNotFound, inviteSuccess, error, authManager]);

  const formatTimeAgo = useCallback((dateString) => {
    if (!dateString) return "";
    const date = new Date(dateString);
    const now = new Date();
    const diffInSeconds = Math.floor((now - date) / 1000);

    if (diffInSeconds < 60) return "Just now";
    const diffInMinutes = Math.floor(diffInSeconds / 60);
    if (diffInMinutes < 60) return `${diffInMinutes}m ago`;
    const diffInHours = Math.floor(diffInMinutes / 60);
    if (diffInHours < 24) return `${diffInHours}h ago`;
    const diffInDays = Math.floor(diffInHours / 24);
    if (diffInDays === 1) return "Yesterday";
    if (diffInDays < 7) return `${diffInDays} days ago`;
    return date.toLocaleDateString();
  }, []);

  const currentUserEmail = authManager?.getCurrentUserEmail();

  // Build breadcrumb - memoized to prevent recreation on every render
  const breadcrumbItems = useMemo(() => [
    {
      label: "My Files",
      to: "/file-manager",
      icon: HomeIcon,
    },
    {
      label: collection?.name || "Folder",
      to: `/file-manager/collections/${collectionId}`,
      icon: FolderIcon,
    },
    {
      label: "Share",
      isActive: true,
    },
  ], [collection?.name, collectionId]);

  return (
    <Layout>
      <div className="max-w-7xl 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 items-center">
              <div className={`h-12 w-12 ${getThemeClasses("bg-gradient-secondary")} rounded-xl flex items-center justify-center mr-4`}>
                <ShareIcon className="h-6 w-6 text-white" />
              </div>
              <div>
                <h1 className={`text-2xl font-bold ${getThemeClasses("text-primary")}`}>Share Folder</h1>
                {collection && (
                  <p className={`${getThemeClasses("text-secondary")} mt-1`}>
                    Share "{collection.name}" with end-to-end encryption
                  </p>
                )}
              </div>
            </div>
          </div>

          {/* Messages */}
          <div className="px-6 pt-6">
            {error && (
              <Alert type="error" className="mb-4">
                {error}
              </Alert>
            )}
            {success && (
              <Alert type="success" className="mb-4">
                {success}
              </Alert>
            )}
            {inviteSuccess && !success && (
              <Alert type="success" className="mb-4">
                {inviteSuccess}
              </Alert>
            )}
          </div>

          {/* Content */}
          <div className="px-2 pb-2 pt-2">
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
              {/* Add People Section */}
              <div className={`${getThemeClasses("bg-card")} rounded-lg border ${getThemeClasses("border-secondary")} shadow-sm p-4 flex flex-col`}>
                <div className="flex items-center mb-6">
                  <UserPlusIcon className={`h-6 w-6 ${getThemeClasses("text-primary")} mr-3`} />
                  <h2 className={`text-lg font-semibold ${getThemeClasses("text-primary")}`}>Add People</h2>
                </div>

                <div className="space-y-4">
                  {/* Email Input */}
                  <div>
                    <div className="flex items-end space-x-3">
                      <div className="flex-1">
                        <Input
                          type="email"
                          label="Email Address"
                          value={recipientEmail}
                          onChange={handleEmailChange}
                          placeholder="Enter email address"
                          icon={EnvelopeIcon}
                          disabled={isVerifying || isLoading}
                          size="md"
                        />
                      </div>
                      <div>
                        <Button
                          onClick={handleVerifyRecipient}
                          disabled={
                            isVerifying ||
                            isLoading ||
                            !recipientEmail.trim() ||
                            recipientEmail.trim().toLowerCase() ===
                              currentUserEmail?.toLowerCase()
                          }
                          variant="success"
                          size="md"
                        >
                          {isVerifying ? (
                            <>
                              <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-current mr-2"></div>
                              Verifying...
                            </>
                          ) : (
                            "Verify"
                          )}
                        </Button>
                      </div>
                    </div>
                    {recipientVerified && (
                      <div className={`mt-2 p-3 ${getThemeClasses("bg-success-light")} border ${getThemeClasses("border-success")} rounded-lg`}>
                        <p className={`text-sm ${getThemeClasses("text-success")} flex items-center`}>
                          <CheckIcon className="h-4 w-4 mr-2" />
                          User verified and ready to share
                        </p>
                      </div>
                    )}

                    {/* User Not Found - Invite Option */}
                    {userNotFound && !recipientVerified && (
                      <div className={`mt-2 p-4 ${getThemeClasses("bg-warning-light")} border ${getThemeClasses("border-warning")} rounded-lg`}>
                        <p className={`text-sm font-medium ${getThemeClasses("text-warning")} mb-2`}>
                          User not found
                        </p>
                        <p className={`text-sm ${getThemeClasses("text-secondary")} mb-3`}>
                          This email address is not registered on MapleFile. Would you like to send them an invitation to join?
                        </p>
                        <Button
                          onClick={handleSendInvite}
                          disabled={isSendingInvite}
                          variant="warning"
                          size="sm"
                        >
                          {isSendingInvite ? (
                            <>
                              <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-current mr-2"></div>
                              Sending Invitation...
                            </>
                          ) : (
                            <>
                              <PaperAirplaneIcon className="h-4 w-4 mr-2" />
                              Send Invitation Email
                            </>
                          )}
                        </Button>
                      </div>
                    )}

                    {/* Invite Success Message */}
                    {inviteSuccess && (
                      <div className={`mt-2 p-3 ${getThemeClasses("bg-success-light")} border ${getThemeClasses("border-success")} rounded-lg`}>
                        <p className={`text-sm ${getThemeClasses("text-success")} flex items-center`}>
                          <CheckIcon className="h-4 w-4 mr-2" />
                          {inviteSuccess}
                        </p>
                      </div>
                    )}
                  </div>

                  {/* Permission Level */}
                  <IconDropdown
                    label="Permission Level"
                    options={permissionLevels}
                    value={permissionLevel}
                    onChange={setPermissionLevel}
                    disabled={isLoading}
                  />

                  {/* GDPR Consent Checkbox */}
                  {recipientVerified && (
                    <div className={`p-4 ${getThemeClasses("bg-info-light")} border ${getThemeClasses("border-info")} rounded-lg`}>
                      <div className="flex items-start space-x-3">
                        <Checkbox
                          checked={gdprConsent}
                          onChange={setGdprConsent}
                          className="mt-0.5"
                        />
                        <div className="flex-1">
                          <p className={`text-sm font-medium ${getThemeClasses("text-info")}`}>
                            I consent to data processing for sharing
                          </p>
                          <p className={`text-xs ${getThemeClasses("text-info")} mt-1`}>
                            By checking this box, you consent to processing the recipient's email address and user ID for the purpose of secure folder sharing. This data will be retained for 90 days after access is revoked.
                          </p>
                        </div>
                      </div>
                    </div>
                  )}

                  {/* Share Button */}
                  <Button
                    onClick={handleShareCollection}
                    disabled={
                      isLoading ||
                      isVerifying ||
                      !recipientVerified ||
                      !recipientId ||
                      !recipientEmail.trim()
                    }
                    variant="primary"
                    className="w-full"
                  >
                    {isLoading && !isVerifying ? (
                      <>
                        <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-white mr-2"></div>
                        Sharing Folder...
                      </>
                    ) : (
                      <>
                        <ShareIcon className="h-5 w-5 mr-2" />
                        Share Folder Securely
                      </>
                    )}
                  </Button>
                </div>
              </div>

              {/* Current Members */}
              <div className={`${getThemeClasses("bg-card")} rounded-lg border ${getThemeClasses("border-secondary")} shadow-sm p-4 flex flex-col`}>
                <div className="flex items-center justify-between mb-6">
                  <div className="flex items-center">
                    <UserGroupIcon className={`h-6 w-6 ${getThemeClasses("text-primary")} mr-3`} />
                    <h2 className={`text-lg font-semibold ${getThemeClasses("text-primary")}`}>
                      People with Access ({collectionMembers.length + 1})
                    </h2>
                  </div>
                  {/* +1 for owner */}
                  <div className="flex space-x-2">
                    <Button
                      onClick={handleExportMembers}
                      disabled={collectionMembers.length === 0}
                      variant="secondary"
                      size="sm"
                      title="Export sharing data (GDPR Article 20)"
                    >
                      Export
                    </Button>
                    <Button
                      onClick={() => loadCollectionMembers(true)}
                      disabled={isLoading}
                      variant="secondary"
                      size="sm"
                    >
                      {isLoading ? "Refreshing..." : "Refresh"}
                    </Button>
                  </div>
                </div>

                {isLoading && collectionMembers.length === 0 ? (
                  <div className="text-center py-8">
                    <div className={`animate-spin rounded-full h-8 w-8 border-b-2 ${getThemeClasses("border-accent")} mx-auto`}></div>
                    <p className={`${getThemeClasses("text-secondary")} mt-2`}>Loading members...</p>
                  </div>
                ) : (
                  <div className="space-y-3">
                    {/* Owner */}
                    {collection && (
                      <UserListItem
                        name={ownerEmail || "Owner"}
                        avatarText={ownerEmail ? ownerEmail.charAt(0).toUpperCase() : "O"}
                        badges={[
                          { label: "Owner", variant: "accent" },
                          ...(ownerEmail && ownerEmail === currentUserEmail ? [{ label: "You", variant: "muted" }] : [])
                        ]}
                        rightText="Full control"
                        highlighted={true}
                      />
                    )}

                    {collectionMembers.length > 0
                      ? collectionMembers.map((member) => {
                          const memberPermission =
                            permissionLevels.find(
                              (p) => p.value === member.permission_level,
                            ) || permissionLevels[0];
                          // Check if this member is the owner - owners cannot be removed
                          const isOwner = collection?.owner_id === member.recipient_id;
                          return (
                            <UserListItem
                              key={member.recipient_id}
                              name={member.recipient_email}
                              avatarText={member.recipient_email.charAt(0).toUpperCase()}
                              badges={member._isLocal ? [{ label: "Just added", variant: "success" }] : []}
                              subtitle={`Shared ${formatTimeAgo(member.shared_at)}`}
                              rightText={memberPermission.label}
                              rightIcon={memberPermission.icon}
                              rightIconColor={memberPermission.color}
                              actions={isOwner ? [] : [
                                {
                                  icon: TrashIcon,
                                  label: "Remove access",
                                  onClick: () => handleRemoveMember(member.recipient_id, member.recipient_email),
                                  disabled: isLoading,
                                  variant: "danger"
                                }
                              ]}
                              highlighted={member._isLocal}
                              highlightColor="success"
                            />
                          );
                        })
                      : !isLoading && (
                          <div className={`text-center py-8 border-2 border-dashed ${getThemeClasses("border-secondary")} rounded-lg`}>
                            <UserGroupIcon className={`h-12 w-12 ${getThemeClasses("text-muted")} mx-auto mb-3`} />
                            <p className={`${getThemeClasses("text-secondary")} text-lg font-medium`}>
                              No one else has access yet
                            </p>
                            <p className={`${getThemeClasses("text-muted")} text-sm`}>
                              Share this folder to start collaborating
                            </p>
                          </div>
                        )}
                  </div>
                )}
              </div>

            </div>

            {/* Security Notice - Full width below the grid */}
            <div className="mt-4">
              <InfoNotice
                variant="security"
                title="End-to-End Encryption"
                icon={LockClosedIcon}
              >
                When you share this folder, the encryption key is securely
                shared with the recipient using their public key. Only they can
                decrypt and access the files.
              </InfoNotice>
            </div>
          </div>
        </Card>
      </div>

      {/* Remove Member Confirmation Modal */}
      <Modal
        isOpen={showRemoveModal}
        onClose={() => setShowRemoveModal(false)}
        title="Remove Member Access"
        footer={
          <div className="flex justify-end space-x-3">
            <Button
              onClick={() => setShowRemoveModal(false)}
              variant="secondary"
              disabled={isLoading}
            >
              Cancel
            </Button>
            <Button
              onClick={confirmRemoveMember}
              variant="danger"
              disabled={isLoading}
            >
              {isLoading ? (
                <>
                  <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-current mr-2"></div>
                  Removing...
                </>
              ) : (
                "Remove Access"
              )}
            </Button>
          </div>
        }
      >
        <div className="py-4">
          <p className={`text-base ${getThemeClasses("text-primary")}`}>
            Are you sure you want to remove <strong>{memberToRemove?.email}</strong> from this folder?
          </p>
          <p className={`text-sm ${getThemeClasses("text-secondary")} mt-2`}>
            They will immediately lose access to all files in this folder.
          </p>
        </div>
      </Modal>
    </Layout>
  );
};

export default withPasswordProtection(CollectionShare);
