// File: src/pages/User/FileManager/Trash/TrashView.jsx
// UIX version - Theme-aware Trash View with Layout
import React, { useState, useEffect, useCallback, useRef, useMemo, memo } from "react";
import { useNavigate } from "react-router";
import { useFiles, useAuth } from "../../../../services/Services";
import withPasswordProtection from "../../../../hocs/withPasswordProtection";
import Layout from "../../../../components/Layout/Layout";
import {
  Button,
  Input,
  Alert,
  Modal,
  useUIXTheme,
  Breadcrumb,
  Card,
  EmptyState,
  InfoNotice,
  Table,
  Checkbox
} from "../../../../components/UIX";
import {
  TrashIcon,
  ArrowPathIcon,
  DocumentIcon,
  FolderIcon,
  PhotoIcon,
  ExclamationTriangleIcon,
  MagnifyingGlassIcon,
  HomeIcon,
  ClockIcon,
} from "@heroicons/react/24/outline";

const TrashView = () => {
  const navigate = useNavigate();
  const { getThemeClasses } = useUIXTheme();
  const isMountedRef = useRef(true);

  const { listFileManager, deleteFileManager, listCollectionManager, deleteCollectionManager } =
    useFiles();
  const { authManager } = useAuth();

  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState("");
  const [success, setSuccess] = useState("");
  const [deletedFiles, setDeletedFiles] = useState([]);
  const [deletedCollections, setDeletedCollections] = useState([]);
  const [searchQuery, setSearchQuery] = useState("");
  const [selectedItems, setSelectedItems] = useState(new Set());
  const [showEmptyConfirm, setShowEmptyConfirm] = useState(false);
  const [showRestoreConfirm, setShowRestoreConfirm] = useState(false);
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  const [isRestoring, setIsRestoring] = useState(false);
  const [isDeleting, setIsDeleting] = useState(false);

  // Security: Rate limiting refs
  const lastRefreshTime = useRef(0);
  const REFRESH_COOLDOWN_MS = 2000; // 2 seconds between refreshes
  const MAX_SEARCH_LENGTH = 200;

  // OWASP A09:2021 - Security logging for audit trail
  const logSecurityEvent = useCallback((eventType, details) => {
    try {
      // Sanitize details to avoid circular references and keep size manageable
      const sanitizedDetails = {
        totalItems: details.totalItems || 0,
        succeeded: details.succeeded || 0,
        failed: details.failed || 0,
        timestamp: details.timestamp || new Date().toISOString(),
      };

      const auditLog = {
        timestamp: new Date().toISOString(),
        user: authManager?.getCurrentUserEmail?.() || "unknown",
        event: eventType,
        details: sanitizedDetails,
      };

      // In production, this should send to a backend audit logging service
      if (import.meta.env.DEV) {
        console.log("[SECURITY AUDIT]", JSON.stringify(auditLog));
      }

      // Store audit logs locally for compliance (GDPR Article 30)
      try {
        let auditLogs = [];
        const stored = localStorage.getItem("security_audit_logs");
        if (stored) {
          const parsed = JSON.parse(stored);
          // Validate it's an array and each entry has expected structure
          if (Array.isArray(parsed)) {
            // Filter to only valid audit log entries to prevent injection
            auditLogs = parsed.filter(log =>
              log &&
              typeof log === 'object' &&
              typeof log.action === 'string' &&
              typeof log.timestamp === 'string'
            );
          }
          // If structure was invalid, clear corrupted data
          if (!Array.isArray(parsed) || auditLogs.length !== parsed.length) {
            if (import.meta.env.DEV) {
              console.warn("[TrashView] Cleared invalid audit log entries");
            }
          }
        }
        auditLogs.push(auditLog);
        // Keep only last 50 audit logs to prevent storage overflow
        if (auditLogs.length > 50) {
          auditLogs = auditLogs.slice(-50);
        }
        localStorage.setItem("security_audit_logs", JSON.stringify(auditLogs));
      } catch (storageErr) {
        // If storage fails, clear potentially corrupted data and log to console in dev mode
        localStorage.removeItem("security_audit_logs");
        if (import.meta.env.DEV) {
          console.warn("[TrashView] Could not store audit log:", storageErr.message);
        }
      }
    } catch (err) {
      // Catch all to prevent breaking the UI
      if (import.meta.env.DEV) {
        console.error("[TrashView] Audit logging failed:", err);
      }
    }
  }, [authManager]);

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

  // Load deleted items - with rate limiting
  const loadDeletedItems = useCallback(
    async (forceRefresh = false) => {
      if (!listFileManager || !listCollectionManager) return;

      // Security: Rate limiting on forced refreshes
      if (forceRefresh) {
        const now = Date.now();
        const timeSinceLastRefresh = now - lastRefreshTime.current;
        if (timeSinceLastRefresh < REFRESH_COOLDOWN_MS) {
          const waitTime = Math.ceil((REFRESH_COOLDOWN_MS - timeSinceLastRefresh) / 1000);
          setError(`Please wait ${waitTime} second${waitTime !== 1 ? 's' : ''} before refreshing again`);
          return;
        }
        lastRefreshTime.current = now;
      }

      setIsLoading(true);
      setError("");

      try {
        // Load deleted files
        const filesResult = await listFileManager.listFiles({
          states: ["deleted"],
          force_refresh: forceRefresh,
        });

        if (filesResult.files && isMountedRef.current) {
          setDeletedFiles(filesResult.files);
        }

        // Load deleted collections
        const collectionsResult =
          await listCollectionManager.listCollections(forceRefresh);

        if (collectionsResult.collections && isMountedRef.current) {
          const deleted = collectionsResult.collections.filter(
            (c) => c.state === "deleted",
          );
          setDeletedCollections(deleted);
        }
      } catch (err) {
        if (isMountedRef.current) {
          setError("Could not load deleted items");
        }
        if (import.meta.env.DEV) {
          console.error("[TrashView] Failed to load trash items:", err);
        }
      } finally {
        if (isMountedRef.current) {
          setIsLoading(false);
        }
      }
    },
    [listFileManager, listCollectionManager],
  );

  useEffect(() => {
    if (
      listFileManager &&
      listCollectionManager &&
      authManager?.isAuthenticated()
    ) {
      loadDeletedItems();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [listFileManager, listCollectionManager, authManager]);

  // OWASP A04:2021 - Handle restore with proper error reporting and partial success handling
  const handleRestoreConfirmed = useCallback(async () => {
    if ((!deleteFileManager && !deleteCollectionManager) || selectedItems.size === 0 || isRestoring) return;

    setError("");
    setIsRestoring(true);

    try {
      const filePromises = [];
      const collectionPromises = [];
      const itemsToRestore = [];

      // OWASP A01:2021 - Process both files AND collections with IDOR protection
      selectedItems.forEach((itemId) => {
        if (itemId.startsWith("file-")) {
          const fileId = itemId.replace("file-", "");
          // Validate that file exists in deletedFiles
          const file = deletedFiles.find(f => f.id === fileId);
          if (file && deleteFileManager) {
            itemsToRestore.push({ type: 'file', id: fileId, name: file.name || 'Encrypted' });
            filePromises.push(
              deleteFileManager.restoreFile(fileId)
                .then(() => ({ status: 'fulfilled', type: 'file', id: fileId, name: file.name }))
                .catch(err => ({ status: 'rejected', type: 'file', id: fileId, name: file.name, error: err.message }))
            );
          }
        } else if (itemId.startsWith("collection-")) {
          const collectionId = itemId.replace("collection-", "");
          // Validate that collection exists in deletedCollections
          const collection = deletedCollections.find(c => c.id === collectionId);
          if (collection && deleteCollectionManager) {
            itemsToRestore.push({ type: 'collection', id: collectionId, name: collection.name || 'Encrypted' });
            collectionPromises.push(
              deleteCollectionManager.restoreCollection(collectionId)
                .then(() => ({ status: 'fulfilled', type: 'collection', id: collectionId, name: collection.name }))
                .catch(err => ({ status: 'rejected', type: 'collection', id: collectionId, name: collection.name, error: err.message }))
            );
          }
        }
      });

      const allPromises = [...filePromises, ...collectionPromises];

      if (allPromises.length === 0) {
        setError("No valid items to restore");
        setIsRestoring(false);
        setShowRestoreConfirm(false);
        return;
      }

      // OWASP A04:2021 - Use Promise.allSettled to handle partial successes
      const results = await Promise.allSettled(allPromises);

      const succeeded = results.filter(r => r.status === 'fulfilled' && r.value.status === 'fulfilled');
      const failed = results.filter(r => r.status === 'rejected' || (r.status === 'fulfilled' && r.value.status === 'rejected'));

      // OWASP A09:2021 - Audit log for restore operations
      logSecurityEvent('TRASH_RESTORE', {
        totalItems: allPromises.length,
        succeeded: succeeded.length,
        failed: failed.length,
        items: itemsToRestore
      });

      if (isMountedRef.current) {
        setSelectedItems(new Set());
        setShowRestoreConfirm(false);

        // OWASP A04:2021 - Detailed success/failure reporting
        if (succeeded.length > 0 && failed.length === 0) {
          setSuccess(`Successfully restored ${succeeded.length} item${succeeded.length !== 1 ? 's' : ''}`);
        } else if (succeeded.length > 0 && failed.length > 0) {
          setSuccess(`Restored ${succeeded.length} item${succeeded.length !== 1 ? 's' : ''}`);
          setError(`Failed to restore ${failed.length} item${failed.length !== 1 ? 's' : ''}. Please try again.`);
        } else {
          setError(`Failed to restore all items. Please try again.`);
        }
      }
      await loadDeletedItems(true);
    } catch (err) {
      if (isMountedRef.current) {
        setError("Failed to restore items");
      }
      if (import.meta.env.DEV) {
        console.error("[TrashView] Restore error:", err);
      }
    } finally {
      if (isMountedRef.current) {
        setIsRestoring(false);
      }
    }
  }, [deleteFileManager, deleteCollectionManager, selectedItems, loadDeletedItems, deletedFiles, deletedCollections, isRestoring, logSecurityEvent]);

  const handleRestore = useCallback(() => {
    if (selectedItems.size === 0) return;
    setShowRestoreConfirm(true);
  }, [selectedItems]);

  // OWASP A04:2021 & A09:2021 - Handle permanent delete with audit logging and proper error reporting
  const handlePermanentDeleteConfirmed = useCallback(async () => {
    if ((!deleteFileManager && !deleteCollectionManager) || selectedItems.size === 0 || isDeleting) return;

    setError("");
    setIsDeleting(true);

    try {
      const filePromises = [];
      const collectionWarnings = [];
      const itemsToDelete = [];

      // OWASP A01:2021 - Process files with IDOR protection
      selectedItems.forEach((itemId) => {
        if (itemId.startsWith("file-")) {
          const fileId = itemId.replace("file-", "");
          // Validate that file exists in deletedFiles
          const file = deletedFiles.find(f => f.id === fileId);
          if (file && deleteFileManager) {
            itemsToDelete.push({ type: 'file', id: fileId, name: file.name || 'Encrypted', size: file.size });
            filePromises.push(
              deleteFileManager.deleteFile(fileId, true) // true = permanent delete
                .then(() => ({ status: 'fulfilled', type: 'file', id: fileId, name: file.name }))
                .catch(err => ({ status: 'rejected', type: 'file', id: fileId, name: file.name, error: err.message }))
            );
          }
        } else if (itemId.startsWith("collection-")) {
          // OWASP A01:2021 - Collections: permanent delete not supported by API
          // Collections can only be soft deleted, they'll auto-delete after 30 days
          const collectionId = itemId.replace("collection-", "");
          const collection = deletedCollections.find(c => c.id === collectionId);
          if (collection) {
            collectionWarnings.push(collection.name || 'Encrypted folder');
          }
        }
      });

      if (filePromises.length === 0 && collectionWarnings.length === 0) {
        setError("No valid items to delete");
        setIsDeleting(false);
        setShowDeleteConfirm(false);
        return;
      }

      // OWASP A09:2021 - CRITICAL: Audit log BEFORE permanent deletion
      logSecurityEvent('PERMANENT_DELETE_INITIATED', {
        totalItems: itemsToDelete.length,
        collectionWarnings: collectionWarnings.length,
        items: itemsToDelete,
        timestamp: new Date().toISOString()
      });

      // OWASP A04:2021 - Use Promise.allSettled to handle partial successes
      let results = [];
      if (filePromises.length > 0) {
        results = await Promise.allSettled(filePromises);
      }

      const succeeded = results.filter(r => r.status === 'fulfilled' && r.value.status === 'fulfilled');
      const failed = results.filter(r => r.status === 'rejected' || (r.status === 'fulfilled' && r.value.status === 'rejected'));

      // OWASP A09:2021 - CRITICAL: Audit log AFTER permanent deletion
      logSecurityEvent('PERMANENT_DELETE_COMPLETED', {
        totalRequested: filePromises.length,
        succeeded: succeeded.length,
        failed: failed.length,
        items: itemsToDelete.filter((_, idx) => succeeded.some((s, i) => i === idx))
      });

      if (isMountedRef.current) {
        setSelectedItems(new Set());
        setShowDeleteConfirm(false);

        // OWASP A04:2021 - Detailed success/failure reporting
        if (succeeded.length > 0 && failed.length === 0 && collectionWarnings.length === 0) {
          setSuccess(`Successfully deleted ${succeeded.length} file${succeeded.length !== 1 ? 's' : ''} permanently`);
        } else if (succeeded.length > 0 || collectionWarnings.length > 0) {
          let msg = [];
          if (succeeded.length > 0) {
            msg.push(`Deleted ${succeeded.length} file${succeeded.length !== 1 ? 's' : ''}`);
          }
          if (collectionWarnings.length > 0) {
            msg.push(`${collectionWarnings.length} folder${collectionWarnings.length !== 1 ? 's' : ''} will auto-delete after 30 days`);
          }
          setSuccess(msg.join('. '));
          if (failed.length > 0) {
            setError(`Failed to delete ${failed.length} file${failed.length !== 1 ? 's' : ''}. Please try again.`);
          }
        } else {
          setError(`Failed to delete items. Please try again.`);
        }
      }
      await loadDeletedItems(true);
    } catch (err) {
      if (isMountedRef.current) {
        setError("Failed to delete items");
      }
      if (import.meta.env.DEV) {
        console.error("[TrashView] Delete error:", err);
      }

      // OWASP A09:2021 - Log deletion failure
      logSecurityEvent('PERMANENT_DELETE_FAILED', {
        error: err.message,
        selectedCount: selectedItems.size
      });
    } finally {
      if (isMountedRef.current) {
        setIsDeleting(false);
      }
    }
  }, [deleteFileManager, deleteCollectionManager, selectedItems, loadDeletedItems, deletedFiles, deletedCollections, isDeleting, logSecurityEvent]);

  const handlePermanentDelete = useCallback(() => {
    if (selectedItems.size === 0) return;
    setShowDeleteConfirm(true);
  }, [selectedItems]);

  // OWASP A04:2021 & A09:2021 - Handle empty trash with audit logging
  const handleEmptyTrash = useCallback(async () => {
    if (!deleteFileManager) return;

    setError("");

    try {
      const itemsToDelete = deletedFiles.map(file => ({
        type: 'file',
        id: file.id,
        name: file.name || 'Encrypted',
        size: file.size
      }));

      // OWASP A09:2021 - CRITICAL: Audit log BEFORE emptying trash
      logSecurityEvent('EMPTY_TRASH_INITIATED', {
        totalFiles: deletedFiles.length,
        totalCollections: deletedCollections.length,
        files: itemsToDelete,
        timestamp: new Date().toISOString()
      });

      // Delete all files permanently using Promise.allSettled
      const promises = deletedFiles.map((file) =>
        deleteFileManager.deleteFile(file.id, true)
          .then(() => ({ status: 'fulfilled', id: file.id, name: file.name }))
          .catch(err => ({ status: 'rejected', id: file.id, name: file.name, error: err.message }))
      );

      // OWASP A04:2021 - Use Promise.allSettled to handle partial successes
      const results = await Promise.allSettled(promises);

      const succeeded = results.filter(r => r.status === 'fulfilled' && r.value.status === 'fulfilled');
      const failed = results.filter(r => r.status === 'rejected' || (r.status === 'fulfilled' && r.value.status === 'rejected'));

      // OWASP A09:2021 - CRITICAL: Audit log AFTER emptying trash
      logSecurityEvent('EMPTY_TRASH_COMPLETED', {
        totalRequested: promises.length,
        succeeded: succeeded.length,
        failed: failed.length,
        collectionsRemaining: deletedCollections.length
      });

      if (isMountedRef.current) {
        setShowEmptyConfirm(false);

        // OWASP A04:2021 - Detailed success/failure reporting
        if (succeeded.length > 0 && failed.length === 0) {
          let msg = `Successfully deleted ${succeeded.length} file${succeeded.length !== 1 ? 's' : ''} permanently`;
          if (deletedCollections.length > 0) {
            msg += `. ${deletedCollections.length} folder${deletedCollections.length !== 1 ? 's' : ''} will auto-delete after 30 days`;
          }
          setSuccess(msg);
        } else if (succeeded.length > 0) {
          setSuccess(`Deleted ${succeeded.length} of ${promises.length} file${promises.length !== 1 ? 's' : ''}`);
          setError(`Failed to delete ${failed.length} file${failed.length !== 1 ? 's' : ''}. Please try again.`);
        } else {
          setError(`Failed to empty trash. Please try again.`);
        }
      }
      await loadDeletedItems(true);
    } catch (err) {
      if (isMountedRef.current) {
        setError("Failed to empty trash");
      }
      if (import.meta.env.DEV) {
        console.error("[TrashView] Empty trash error:", err);
      }

      // OWASP A09:2021 - Log empty trash failure
      logSecurityEvent('EMPTY_TRASH_FAILED', {
        error: err.message,
        fileCount: deletedFiles.length
      });
    }
  }, [deleteFileManager, deletedFiles, deletedCollections, loadDeletedItems, logSecurityEvent]);

  // Memoize filtered items - CRITICAL for performance
  const filteredFiles = useMemo(() => {
    const lowerQuery = searchQuery.toLowerCase();
    return deletedFiles.filter((file) =>
      (file.name || "").toLowerCase().includes(lowerQuery)
    );
  }, [deletedFiles, searchQuery]);

  const filteredCollections = useMemo(() => {
    const lowerQuery = searchQuery.toLowerCase();
    return deletedCollections.filter((collection) =>
      (collection.name || "").toLowerCase().includes(lowerQuery)
    );
  }, [deletedCollections, searchQuery]);

  const allFilteredItems = useMemo(() => [
    ...filteredFiles.map((f) => ({
      ...f,
      itemType: "file",
      itemId: `file-${f.id}`,
    })),
    ...filteredCollections.map((c) => ({
      ...c,
      itemType: "collection",
      itemId: `collection-${c.id}`,
    })),
  ], [filteredFiles, filteredCollections]);

  // Format date
  const formatDate = useCallback((dateString) => {
    if (!dateString) return "Unknown";
    const date = new Date(dateString);
    const now = new Date();
    const diffInDays = Math.floor((now - date) / (1000 * 60 * 60 * 24));

    if (diffInDays === 0) return "Today";
    if (diffInDays === 1) return "Yesterday";
    if (diffInDays < 7) return `${diffInDays} days ago`;
    return date.toLocaleDateString();
  }, []);

  // Calculate days until permanent deletion (30 days)
  const getDaysUntilDeletion = useCallback((deletedDate) => {
    if (!deletedDate) return 30;
    const deleted = new Date(deletedDate);
    const now = new Date();
    const daysSinceDeletion = Math.floor(
      (now - deleted) / (1000 * 60 * 60 * 24),
    );
    return Math.max(0, 30 - daysSinceDeletion);
  }, []);

  // OWASP A03:2021 - Input sanitization and validation for search
  const handleSearchChange = useCallback((value) => {
    // Validate length
    if (value.length > MAX_SEARCH_LENGTH) {
      setError(`Search query too long (max ${MAX_SEARCH_LENGTH} characters)`);
      return;
    }

    // Unicode normalization to prevent homograph attacks
    // NFC (Canonical Decomposition followed by Canonical Composition)
    const normalized = value.normalize('NFC');

    // Remove control characters and zero-width characters
    const sanitized = normalized.replace(/[\u0000-\u001F\u007F-\u009F\u200B-\u200D\uFEFF]/g, '');

    // Prevent ReDoS by limiting special regex characters (though we use .includes(), not regex)
    // This is a defense-in-depth measure
    const specialCharsCount = (sanitized.match(/[.*+?^${}()|[\]\\]/g) || []).length;
    if (specialCharsCount > 10) {
      setError('Search query contains too many special characters');
      return;
    }

    setSearchQuery(sanitized);
  }, []);

  const toggleSelection = useCallback((itemId) => {
    setSelectedItems(prev => {
      const newSelected = new Set(prev);
      if (newSelected.has(itemId)) {
        newSelected.delete(itemId);
      } else {
        newSelected.add(itemId);
      }
      return newSelected;
    });
  }, []);

  const handleSelectAll = useCallback(() => {
    if (selectedItems.size === allFilteredItems.length) {
      setSelectedItems(new Set());
    } else {
      setSelectedItems(new Set(allFilteredItems.map((item) => item.itemId)));
    }
  }, [selectedItems.size, allFilteredItems]);

  // Memoize breadcrumb items
  const breadcrumbItems = useMemo(() => [
    {
      label: "My Files",
      to: "/file-manager",
      icon: HomeIcon,
    },
    {
      label: "Trash",
      isActive: true,
    },
  ], []);

  // Memoize theme classes for columns - prevents recreation on every render
  const themeClasses = useMemo(() => ({
    bgMuted: getThemeClasses("bg-muted"),
    textAccent: getThemeClasses("text-accent"),
    textSecondary: getThemeClasses("text-secondary"),
    textPrimary: getThemeClasses("text-primary"),
    bgErrorLight: getThemeClasses("bg-error-light"),
    textError: getThemeClasses("text-error"),
    bgWarningLight: getThemeClasses("bg-warning-light"),
    textWarning: getThemeClasses("text-warning"),
    bgSuccessLight: getThemeClasses("bg-success-light"),
    textSuccess: getThemeClasses("text-success"),
  }), [getThemeClasses]);

  // Memoize table columns
  const columns = useMemo(() => [
    {
      key: 'checkbox',
      header: (
        <Checkbox
          checked={
            selectedItems.size === allFilteredItems.length &&
            allFilteredItems.length > 0
          }
          onChange={handleSelectAll}
        />
      ),
      render: (value, item) => (
        <Checkbox
          checked={selectedItems.has(item.itemId)}
          onChange={() => toggleSelection(item.itemId)}
        />
      ),
      align: 'left'
    },
    {
      key: 'name',
      header: 'Name',
      render: (value, item) => (
        <div className="flex items-center">
          <div className={`flex items-center justify-center h-10 w-10 rounded-lg ${themeClasses.bgMuted} mr-3`}>
            {item.itemType === "collection" ? (
              <FolderIcon className={`h-6 w-6 ${themeClasses.textAccent}`} />
            ) : item.mime_type?.startsWith("image/") ? (
              <PhotoIcon className={`h-6 w-6 ${themeClasses.textAccent}`} />
            ) : (
              <DocumentIcon className={`h-6 w-6 ${themeClasses.textSecondary}`} />
            )}
          </div>
          <span className={`text-sm font-medium ${themeClasses.textPrimary}`}>
            {item.name || "Encrypted"}
          </span>
        </div>
      ),
      align: 'left'
    },
    {
      key: 'type',
      header: 'Type',
      render: (value, item) => (
        <span className={`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${themeClasses.bgMuted} ${themeClasses.textPrimary}`}>
          {item.itemType === "collection" ? "Folder" : "File"}
        </span>
      ),
      align: 'left'
    },
    {
      key: 'deleted',
      header: 'Deleted',
      render: (value, item) => (
        <span className={`text-sm ${themeClasses.textSecondary}`}>
          {formatDate(item.modified_at)}
        </span>
      ),
      align: 'left'
    },
    {
      key: 'daysLeft',
      header: 'Days Left',
      render: (value, item) => {
        const daysLeft = getDaysUntilDeletion(item.modified_at);
        return (
          <span
            className={`inline-flex items-center px-2.5 py-1 rounded-full text-xs font-semibold ${
              daysLeft <= 7
                ? `${themeClasses.bgErrorLight} ${themeClasses.textError}`
                : daysLeft <= 14
                  ? `${themeClasses.bgWarningLight} ${themeClasses.textWarning}`
                  : `${themeClasses.bgSuccessLight} ${themeClasses.textSuccess}`
            }`}
          >
            <ClockIcon className="h-3 w-3 mr-1" />
            {daysLeft} days
          </span>
        );
      },
      align: 'left'
    }
  ], [selectedItems, allFilteredItems, handleSelectAll, toggleSelection, themeClasses, formatDate, getDaysUntilDeletion]);

  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 justify-between">
              <div className="flex items-center">
                <div className={`h-12 w-12 ${getThemeClasses("bg-gradient-secondary")} rounded-xl flex items-center justify-center mr-4`}>
                  <TrashIcon className="h-6 w-6 text-white" />
                </div>
                <div>
                  <h1 className={`text-2xl font-bold ${getThemeClasses("text-primary")}`}>
                    Trash
                  </h1>
                  <p className={`${getThemeClasses("text-secondary")} mt-1`}>
                    Items in trash will be permanently deleted after 30 days
                  </p>
                </div>
              </div>

              <div className="flex items-center space-x-3">
                <Button
                  onClick={() => loadDeletedItems(true)}
                  disabled={isLoading}
                  variant="secondary"
                  size="md"
                >
                  <ArrowPathIcon
                    className={`h-4 w-4 mr-2 ${isLoading ? "animate-spin" : ""}`}
                  />
                  Refresh
                </Button>

                {allFilteredItems.length > 0 && (
                  <Button
                    onClick={() => setShowEmptyConfirm(true)}
                    variant="danger"
                    size="md"
                  >
                    <TrashIcon className="h-4 w-4 mr-2" />
                    Empty Trash
                  </Button>
                )}
              </div>
            </div>
          </div>

          {/* Content */}
          <div className="px-6 pt-6 pb-6">
            {/* Messages */}
            {error && (
              <Alert type="error" className="mb-6">
                {error}
              </Alert>
            )}

            {success && (
              <Alert type="success" className="mb-6">
                {success}
              </Alert>
            )}

            {/* Info Notice */}
            <InfoNotice
              variant="info"
              icon={ClockIcon}
              compact
              className="mb-6"
            >
              Deleted items are kept for 30 days before being permanently removed. You can restore them anytime during this period.
            </InfoNotice>

            {/* Search */}
            <div className="mb-6">
              <Input
                type="text"
                value={searchQuery}
                onChange={handleSearchChange}
                placeholder="Search in trash..."
                icon={MagnifyingGlassIcon}
                size="md"
              />
            </div>

            {/* Loading State */}
            {isLoading ? (
              <div className="flex items-center justify-center py-12">
                <div className="text-center">
                  <div className={`animate-spin rounded-full h-8 w-8 border-b-2 mx-auto mb-4 ${getThemeClasses("border-accent")}`}></div>
                  <p className={getThemeClasses("text-secondary")}>Loading deleted items...</p>
                </div>
              </div>
            ) : allFilteredItems.length === 0 ? (
              <EmptyState
                icon={TrashIcon}
                title={searchQuery ? "No items found" : "Trash is empty"}
                message={searchQuery
                  ? "Try adjusting your search to find deleted items."
                  : "Deleted files and folders will appear here. They'll be kept for 30 days before permanent deletion."}
              />
            ) : (
              <>
                {/* Items List - Using UIX Table Component */}
                <div className={`${getThemeClasses("bg-card")} rounded-lg border ${getThemeClasses("border-secondary")} overflow-hidden`}>
                  <Table
                    columns={columns}
                    data={allFilteredItems}
                  />
                </div>

                {/* Action Bar */}
                {selectedItems.size > 0 && (
                  <div className={`mt-6 p-4 ${getThemeClasses("bg-accent-light")} border ${getThemeClasses("border-accent")} rounded-lg flex items-center justify-between`}>
                    <div className="flex items-center space-x-4">
                      <span className={`text-sm font-semibold ${getThemeClasses("text-accent")}`}>
                        {selectedItems.size} item{selectedItems.size !== 1 ? 's' : ''} selected
                      </span>
                    </div>
                    <div className="flex items-center space-x-3">
                      <Button
                        onClick={handleRestore}
                        variant="success"
                        size="sm"
                      >
                        <ArrowPathIcon className="h-4 w-4 mr-1" />
                        Restore
                      </Button>
                      <Button
                        onClick={handlePermanentDelete}
                        variant="danger"
                        size="sm"
                      >
                        <TrashIcon className="h-4 w-4 mr-1" />
                        Delete Forever
                      </Button>
                    </div>
                  </div>
                )}
              </>
            )}
          </div>
        </Card>
      </div>

      {/* Restore Confirmation Modal */}
      <Modal
        isOpen={showRestoreConfirm}
        onClose={() => !isRestoring && setShowRestoreConfirm(false)}
        title="Restore Items"
        footer={
          <div className="flex justify-end space-x-3">
            <Button
              onClick={() => setShowRestoreConfirm(false)}
              variant="secondary"
              disabled={isRestoring}
            >
              Cancel
            </Button>
            <Button
              onClick={handleRestoreConfirmed}
              variant="success"
              disabled={isRestoring}
            >
              {isRestoring ? (
                <>
                  <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-current mr-2"></div>
                  Restoring...
                </>
              ) : (
                <>
                  <ArrowPathIcon className="h-4 w-4 mr-2" />
                  Restore Items
                </>
              )}
            </Button>
          </div>
        }
      >
        <div className="py-4">
          <div className="flex items-start space-x-3">
            <ArrowPathIcon className={`h-6 w-6 ${getThemeClasses("text-success")} flex-shrink-0 mt-0.5`} />
            <div>
              <p className={`text-base ${getThemeClasses("text-primary")} font-medium mb-2`}>
                Restore {selectedItems.size} item{selectedItems.size !== 1 ? 's' : ''}?
              </p>
              <p className={`text-sm ${getThemeClasses("text-secondary")}`}>
                The selected items will be restored to their original location in your file manager.
              </p>
            </div>
          </div>
        </div>
      </Modal>

      {/* Permanent Delete Confirmation Modal */}
      <Modal
        isOpen={showDeleteConfirm}
        onClose={() => !isDeleting && setShowDeleteConfirm(false)}
        title="Permanently Delete Items"
        footer={
          <div className="flex justify-end space-x-3">
            <Button
              onClick={() => setShowDeleteConfirm(false)}
              variant="secondary"
              disabled={isDeleting}
            >
              Cancel
            </Button>
            <Button
              onClick={handlePermanentDeleteConfirmed}
              variant="danger"
              disabled={isDeleting}
            >
              {isDeleting ? (
                <>
                  <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-current mr-2"></div>
                  Deleting...
                </>
              ) : (
                <>
                  <TrashIcon className="h-4 w-4 mr-2" />
                  Delete Forever
                </>
              )}
            </Button>
          </div>
        }
      >
        <div className="py-4">
          <div className="flex items-start space-x-3 mb-4">
            <ExclamationTriangleIcon className={`h-6 w-6 ${getThemeClasses("text-error")} flex-shrink-0 mt-0.5`} />
            <div>
              <p className={`text-base ${getThemeClasses("text-primary")} font-medium mb-2`}>
                Are you sure you want to permanently delete {selectedItems.size} item{selectedItems.size !== 1 ? 's' : ''}?
              </p>
              <p className={`text-sm ${getThemeClasses("text-secondary")} mb-3`}>
                This will permanently remove the selected items from your trash.
              </p>
              <div className={`p-3 ${getThemeClasses("bg-error-light")} border ${getThemeClasses("border-error")} rounded-lg`}>
                <p className={`text-sm font-semibold ${getThemeClasses("text-error")} flex items-center`}>
                  <ExclamationTriangleIcon className="h-4 w-4 mr-2" />
                  This action cannot be undone
                </p>
                <p className={`text-xs ${getThemeClasses("text-error")} mt-1 ml-6`}>
                  Once deleted, these items cannot be recovered.
                </p>
              </div>
            </div>
          </div>
        </div>
      </Modal>

      {/* Empty Trash Confirmation */}
      <Modal
        isOpen={showEmptyConfirm}
        onClose={() => setShowEmptyConfirm(false)}
        title="Empty Trash"
        footer={
          <div className="flex justify-end space-x-3">
            <Button
              onClick={() => setShowEmptyConfirm(false)}
              variant="secondary"
              disabled={isLoading}
            >
              Cancel
            </Button>
            <Button
              onClick={handleEmptyTrash}
              variant="danger"
              disabled={isLoading}
            >
              {isLoading ? (
                <>
                  <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-current mr-2"></div>
                  Emptying...
                </>
              ) : (
                <>
                  <TrashIcon className="h-4 w-4 mr-2" />
                  Empty Trash
                </>
              )}
            </Button>
          </div>
        }
      >
        <div className="py-4">
          <div className="flex items-start space-x-3 mb-4">
            <ExclamationTriangleIcon className={`h-6 w-6 ${getThemeClasses("text-error")} flex-shrink-0 mt-0.5`} />
            <div>
              <p className={`text-base ${getThemeClasses("text-primary")} font-medium mb-2`}>
                Are you sure you want to permanently delete all items in trash?
              </p>
              <p className={`text-sm ${getThemeClasses("text-secondary")} mb-3`}>
                This will permanently delete <strong>{allFilteredItems.length} item{allFilteredItems.length !== 1 ? 's' : ''}</strong> from your trash.
              </p>
              <div className={`p-3 ${getThemeClasses("bg-error-light")} border ${getThemeClasses("border-error")} rounded-lg`}>
                <p className={`text-sm font-semibold ${getThemeClasses("text-error")} flex items-center`}>
                  <ExclamationTriangleIcon className="h-4 w-4 mr-2" />
                  This action cannot be undone
                </p>
                <p className={`text-xs ${getThemeClasses("text-error")} mt-1 ml-6`}>
                  All files and folders will be permanently removed and cannot be recovered.
                </p>
              </div>
            </div>
          </div>
        </div>
      </Modal>
    </Layout>
  );
};

export default withPasswordProtection(TrashView);
