// File: src/pages/User/FileManager/Files/FileDetails.jsx
import React, { useState, useEffect, useCallback } from "react";
import { useNavigate, useParams } from "react-router";
import { useFiles, useAuth, useTags } from "../../../../services/Services";
import withPasswordProtection from "../../../../hocs/withPasswordProtection";
import Layout from "../../../../components/Layout/Layout";
import { Button, Alert, useUIXTheme, Breadcrumb, Card } from "../../../../components/UIX";
import {
  DocumentIcon,
  ArrowLeftIcon,
  ArrowDownTrayIcon,
  ShareIcon,
  TrashIcon,
  CheckIcon,
  PhotoIcon,
  PlayIcon,
  SpeakerWaveIcon,
  ExclamationTriangleIcon,
  LockClosedIcon,
  ServerIcon,
  ChevronDownIcon,
  ChevronUpIcon,
  HomeIcon,
  FolderIcon,
  TagIcon,
  PencilIcon,
  XMarkIcon,
  PlusIcon,
} from "@heroicons/react/24/outline";

const FileDetails = () => {
  const navigate = useNavigate();
  const { fileId } = useParams();

  const { getFileManager, downloadFileManager, deleteFileManager } = useFiles();
  const { authManager } = useAuth();
  const { tagManager, fileTagManager } = useTags();
  const { getThemeClasses } = useUIXTheme();

  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState("");
  const [fieldErrors, setFieldErrors] = useState({});
  const [fileDetails, setFileDetails] = useState(null);
  const [isDownloading, setIsDownloading] = useState(false);
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  const [showTechnicalDetails, setShowTechnicalDetails] = useState(false);

  // Tag management state
  const [showTagEditor, setShowTagEditor] = useState(false);
  const [availableTags, setAvailableTags] = useState([]);
  const [selectedTagIds, setSelectedTagIds] = useState([]);
  const [isLoadingTags, setIsLoadingTags] = useState(false);
  const [isSavingTags, setIsSavingTags] = useState(false);
  const [tagError, setTagError] = useState("");

  const loadFileDetails = useCallback(
    async (forceRefresh = false) => {
      if (!getFileManager || !fileId) return;

      setIsLoading(true);
      setError("");

      try {
        const file = await getFileManager.getFileById(fileId, forceRefresh);
        setFileDetails(file);
      } catch (err) {
        console.error("[FileDetails] Failed to load file details:", err);

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

        if (err.message) {
          let userMessage = err.message;
          userMessage = userMessage.replace(/^Failed to load file:\s*/i, '');
          userMessage = userMessage.replace(/^Failed to get file:\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 = 'Could not load file details. Please try again.';
          }

          setError(userMessage);
        } else {
          setError("Could not load file details. Please try again.");
        }
      } finally {
        setIsLoading(false);
      }
    },
    [getFileManager, fileId],
  );

  useEffect(() => {
    if (getFileManager && fileId && authManager?.isAuthenticated()) {
      loadFileDetails();
    }
  }, [getFileManager, fileId, authManager, loadFileDetails]);

  const handleDownloadFile = async () => {
    if (!downloadFileManager || !fileDetails) return;

    setIsDownloading(true);
    setError("");

    try {
      await downloadFileManager.downloadFile(fileId, {
        saveToDisk: true,
      });
    } catch (err) {
      console.error("[FileDetails] Failed to download file:", err);

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

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

  const handleDeleteFile = async () => {
    if (!deleteFileManager || !fileId) return;

    try {
      await deleteFileManager.deleteFile(fileId, null); // Move to trash
      // Navigate with state to force refresh
      navigate(`/file-manager/collections/${fileDetails?.collection_id}`, {
        state: { refresh: true, deletedFileId: fileId }
      });
    } catch (err) {
      console.error("[FileDetails] Failed to delete file:", err);

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

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

  // Tag management functions
  const loadAvailableTags = useCallback(async () => {
    if (!tagManager) return;

    setIsLoadingTags(true);
    setTagError("");

    try {
      const tags = await tagManager.listTags();
      setAvailableTags(tags || []);
    } catch (err) {
      console.error("[FileDetails] Failed to load available tags:", err);
      setTagError("Failed to load tags. Please try again.");
    } finally {
      setIsLoadingTags(false);
    }
  }, [tagManager]);

  const handleOpenTagEditor = async () => {
    setShowTagEditor(true);
    // Set initially selected tags from file's current tags
    const currentTagIds = (fileDetails?.tags || []).map(tag => tag.id);
    setSelectedTagIds(currentTagIds);
    // Load available tags
    await loadAvailableTags();
  };

  const handleCloseTagEditor = () => {
    setShowTagEditor(false);
    setTagError("");
  };

  const handleToggleTag = (tagId) => {
    setSelectedTagIds(prev =>
      prev.includes(tagId)
        ? prev.filter(id => id !== tagId)
        : [...prev, tagId]
    );
  };

  const handleSaveTags = async () => {
    if (!fileTagManager || !fileId) return;

    setIsSavingTags(true);
    setTagError("");

    try {
      const currentTagIds = (fileDetails?.tags || []).map(tag => tag.id);
      await fileTagManager.updateFileTags(fileId, currentTagIds, selectedTagIds);

      // Reload file details to get updated tags
      await loadFileDetails(true);

      setShowTagEditor(false);
    } catch (err) {
      console.error("[FileDetails] Failed to save tags:", err);
      setTagError("Failed to save tags. Please try again.");
    } finally {
      setIsSavingTags(false);
    }
  };

  const handleRemoveTag = async (tagId) => {
    if (!fileTagManager || !fileId) return;

    try {
      await fileTagManager.unassignTagsFromFile(fileId, [tagId]);
      // Reload file details to get updated tags
      await loadFileDetails(true);
    } catch (err) {
      console.error("[FileDetails] Failed to remove tag:", err);
      setError("Failed to remove tag. Please try again.");
    }
  };

  const getFileIcon = () => {
    const iconClass = "h-8 w-8 text-white";
    if (!fileDetails) return <DocumentIcon className={iconClass} />;

    const mimeType = fileDetails.mime_type || "";
    if (mimeType.startsWith("image/"))
      return <PhotoIcon className={iconClass} />;
    if (mimeType.startsWith("video/"))
      return <PlayIcon className={iconClass} />;
    if (mimeType.startsWith("audio/"))
      return <SpeakerWaveIcon className={iconClass} />;
    if (mimeType.includes("pdf"))
      return <DocumentIcon className={iconClass} />;
    return <DocumentIcon className={iconClass} />;
  };

  const formatFileSize = (bytes) => {
    if (!bytes) return "0 B";
    const sizes = ["B", "KB", "MB", "GB"];
    const i = Math.floor(Math.log(bytes) / Math.log(1024));
    return `${Math.round(bytes / Math.pow(1024, i))} ${sizes[i]}`;
  };

  const formatDate = (dateString) => {
    if (!dateString || dateString === "0001-01-01T00:00:00Z") return "Unknown";
    const date = new Date(dateString);
    return date.toLocaleDateString("en-US", {
      year: "numeric",
      month: "long",
      day: "numeric",
      hour: "2-digit",
      minute: "2-digit",
    });
  };

  const formatTimeAgo = (dateString) => {
    if (!dateString || dateString === "0001-01-01T00:00:00Z")
      return "a while ago";
    const date = new Date(dateString);
    const now = new Date();
    const diffInMinutes = Math.floor((now - date) / (1000 * 60));

    if (diffInMinutes < 1) return "just now";
    if (diffInMinutes < 60) return `${diffInMinutes} minutes ago`;
    if (diffInMinutes < 1440)
      return `${Math.floor(diffInMinutes / 60)} hours ago`;
    if (diffInMinutes < 2880) return "Yesterday";
    return `${Math.floor(diffInMinutes / 1440)} days ago`;
  };

  const getStateLabel = (state) => {
    return state ? state.charAt(0).toUpperCase() + state.slice(1) : "Unknown";
  };

  if (isLoading) {
    return (
      <Layout>
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
          <div className="flex items-center justify-center py-12">
            <div className="text-center">
              <div className={`h-8 w-8 spinner mx-auto mb-4 ${getThemeClasses("border-primary")}`}></div>
              <p className={getThemeClasses("text-secondary")}>Loading file details...</p>
            </div>
          </div>
        </div>
      </Layout>
    );
  }

  if (error && !fileDetails) {
    return (
      <Layout>
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
          <div className="text-center py-12">
            <ExclamationTriangleIcon className={`h-12 w-12 mx-auto mb-4 ${getThemeClasses("text-error")}`} />
            <h3 className={`text-lg font-medium mb-2 ${getThemeClasses("text-primary")}`}>
              File not found or could not be loaded
            </h3>
            <p className={`text-sm mb-4 ${getThemeClasses("text-secondary")}`}>{error}</p>
            <Button
              onClick={() => navigate("/file-manager")}
              variant="secondary"
            >
              <span className="inline-flex items-center gap-2">
                <ArrowLeftIcon className="h-4 w-4" />
                <span>Back to Files</span>
              </span>
            </Button>
          </div>
        </div>
      </Layout>
    );
  }

  if (!fileDetails) return null; // Should be covered by error state, but for safety

  // Build breadcrumb
  const breadcrumbItems = [
    {
      label: "My Files",
      to: "/file-manager",
      icon: HomeIcon,
    },
    {
      label: "Collection",
      to: `/file-manager/collections/${fileDetails.collection_id}`,
      icon: FolderIcon,
    },
    {
      label: fileDetails.name || "File Details",
      isActive: true,
    },
  ];

  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 with icon, title, and action buttons */}
          <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">
                  {/* Icon */}
                  <div className={`p-3 rounded-2xl shadow-lg mr-4 flex-shrink-0 ${getThemeClasses("bg-gradient-secondary")}`}>
                    {getFileIcon()}
                  </div>
                  {/* Title and metadata */}
                  <div>
                    <h1 className={`text-2xl sm:text-3xl lg:text-4xl font-bold ${getThemeClasses("text-primary")} leading-tight flex items-center`}>
                      {fileDetails.name || "Encrypted File"}
                      {fileDetails._isDecrypted && (
                        <CheckIcon className={`h-5 w-5 ml-2 ${getThemeClasses("text-success")}`} />
                      )}
                    </h1>
                    <div className="flex items-center space-x-3 mt-2">
                      <span className={`text-sm ${getThemeClasses("text-secondary")}`}>
                        {formatFileSize(
                          fileDetails.size ||
                            fileDetails.encrypted_file_size_in_bytes,
                        )}
                      </span>
                      <span className={`text-sm ${getThemeClasses("text-muted")}`}>•</span>
                      <span className={`text-sm ${getThemeClasses("text-secondary")}`}>
                        Modified {formatTimeAgo(fileDetails.modified_at)}
                      </span>
                      <span className={`text-sm ${getThemeClasses("text-muted")}`}>•</span>
                      <span className={`text-sm ${getThemeClasses("text-secondary")}`}>
                        v{fileDetails.version || 1}
                      </span>
                    </div>
                  </div>
                </div>
              </div>
              {/* Action buttons */}
              <div className="flex-shrink-0 flex items-center gap-3">
                <Button
                  onClick={() => navigate(`/file-manager/collections/${fileDetails.collection_id}`)}
                  variant="secondary"
                  size="sm"
                >
                  <span className="inline-flex items-center gap-2">
                    <ArrowLeftIcon className="h-4 w-4" />
                    <span>Back</span>
                  </span>
                </Button>
                <span className={`text-xl ${getThemeClasses("text-muted")}`}>|</span>
                <Button
                  onClick={() => navigate(`/file-manager/collections/${fileDetails.collection_id}/share`)}
                  variant="secondary"
                  size="sm"
                >
                  <span className="inline-flex items-center gap-2">
                    <ShareIcon className="h-4 w-4" />
                    <span>Share</span>
                  </span>
                </Button>
                <Button
                  onClick={() => setShowDeleteConfirm(true)}
                  variant="danger"
                  size="sm"
                >
                  <span className="inline-flex items-center gap-2">
                    <TrashIcon className="h-4 w-4" />
                    <span>Delete</span>
                  </span>
                </Button>
              </div>
            </div>
          </div>

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

          {/* Content */}
          <div className="px-6 pb-6 pt-5">
            <div className="space-y-6 max-w-4xl mx-auto">
              {/* File Information */}
              <div className={`${getThemeClasses("bg-card")} rounded-lg border ${getThemeClasses("border-secondary")} shadow-sm p-6`}>
                  <h3 className={`text-sm font-semibold mb-4 flex items-center ${getThemeClasses("text-primary")}`}>
                    <DocumentIcon className={`h-5 w-5 mr-2 ${getThemeClasses("text-secondary")}`} />
                    File Information
                  </h3>
                <dl className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  <div className={`p-3 ${getThemeClasses("bg-muted")} rounded-lg`}>
                    <dt className={`text-sm font-medium ${getThemeClasses("text-secondary")}`}>
                      Type
                    </dt>
                    <dd className={`text-sm ${getThemeClasses("text-primary")} mt-1`}>
                      {fileDetails.mime_type || "Unknown"}
                    </dd>
                  </div>
                  <div className={`p-3 ${getThemeClasses("bg-muted")} rounded-lg`}>
                    <dt className={`text-sm font-medium ${getThemeClasses("text-secondary")}`}>
                      Size
                    </dt>
                    <dd className={`text-sm ${getThemeClasses("text-primary")} mt-1`}>
                      {formatFileSize(fileDetails.size)}
                    </dd>
                  </div>
                  <div className={`p-3 ${getThemeClasses("bg-muted")} rounded-lg`}>
                    <dt className={`text-sm font-medium ${getThemeClasses("text-secondary")}`}>
                      Created
                    </dt>
                    <dd className={`text-sm ${getThemeClasses("text-primary")} mt-1`}>
                      {formatDate(fileDetails.created_at)}
                    </dd>
                  </div>
                  <div className={`p-3 ${getThemeClasses("bg-muted")} rounded-lg`}>
                    <dt className={`text-sm font-medium ${getThemeClasses("text-secondary")}`}>
                      Modified
                    </dt>
                    <dd className={`text-sm ${getThemeClasses("text-primary")} mt-1`}>
                      {formatDate(fileDetails.modified_at)}
                    </dd>
                  </div>
                </dl>

                {/* Tags Section */}
                <div className={`border-t ${getThemeClasses("border-secondary")} pt-4 mt-4`}>
                  <div className="flex items-center justify-between mb-3">
                    <h4 className={`text-sm font-semibold flex items-center ${getThemeClasses("text-primary")}`}>
                      <TagIcon className={`h-5 w-5 mr-2 ${getThemeClasses("text-secondary")}`} />
                      Tags
                    </h4>
                    <button
                      onClick={handleOpenTagEditor}
                      className={`inline-flex items-center px-2 py-1 text-xs font-medium rounded ${getThemeClasses("bg-muted")} ${getThemeClasses("text-secondary")} ${getThemeClasses("hover:bg-accent")} ${getThemeClasses("hover:text-white")} transition-colors`}
                    >
                      <PencilIcon className="h-3 w-3 mr-1" />
                      Edit Tags
                    </button>
                  </div>
                  {fileDetails.tags && fileDetails.tags.length > 0 ? (
                    <div className="flex flex-wrap gap-2">
                      {fileDetails.tags.map((tag) => (
                        <span
                          key={tag.id}
                          className={`inline-flex items-center px-3 py-1 rounded-full text-sm font-medium ${getThemeClasses("bg-accent-light")} ${getThemeClasses("text-accent")} group`}
                          style={tag.color ? { backgroundColor: `${tag.color}20`, color: tag.color } : {}}
                        >
                          <TagIcon className="h-4 w-4 mr-1.5" />
                          {tag.name || tag.encrypted_name || "Unnamed Tag"}
                          <button
                            onClick={() => handleRemoveTag(tag.id)}
                            className="ml-1.5 opacity-60 hover:opacity-100 transition-opacity"
                            title="Remove tag"
                          >
                            <XMarkIcon className="h-3.5 w-3.5" />
                          </button>
                        </span>
                      ))}
                    </div>
                  ) : (
                    <p className={`text-sm ${getThemeClasses("text-muted")} italic`}>
                      No tags assigned. Click "Edit Tags" to add tags.
                    </p>
                  )}
                </div>

                {/* Encryption Status */}
                <div className={`border-t ${getThemeClasses("border-secondary")} pt-4 mt-4`}>
                  <h4 className={`text-sm font-semibold mb-3 flex items-center ${getThemeClasses("text-primary")}`}>
                    <LockClosedIcon className={`h-5 w-5 mr-2 ${getThemeClasses("text-secondary")}`} />
                    Encryption Status
                  </h4>
                  {fileDetails._isDecrypted ? (
                    <div className={`p-4 ${getThemeClasses("alert-success-bg")} border ${getThemeClasses("alert-success-border")} rounded-lg`}>
                      <div className="flex items-start">
                        <CheckIcon className={`h-5 w-5 ${getThemeClasses("text-success")} mr-3 flex-shrink-0 mt-0.5`} />
                        <div className="flex-1">
                          <h5 className={`text-sm font-medium ${getThemeClasses("text-success")}`}>
                            File is Encrypted and Decrypted
                          </h5>
                          <p className={`text-sm ${getThemeClasses("text-success")} mt-1`}>
                            This file is protected with end-to-end encryption
                            and has been successfully decrypted for viewing.
                          </p>
                        </div>
                      </div>
                    </div>
                  ) : (
                    <div className={`p-4 ${getThemeClasses("alert-warning-bg")} border ${getThemeClasses("alert-warning-border")} rounded-lg`}>
                      <div className="flex items-start">
                        <ExclamationTriangleIcon className={`h-5 w-5 ${getThemeClasses("text-warning")} mr-3 flex-shrink-0 mt-0.5`} />
                        <div className="flex-1">
                          <h5 className={`text-sm font-medium ${getThemeClasses("text-warning")}`}>
                            File Not Decrypted
                          </h5>
                          <p className={`text-sm ${getThemeClasses("text-warning")} mt-1`}>
                            File content is currently encrypted. Decryption is
                            required to download or view.
                          </p>
                          {fileDetails._decryptionError && (
                            <p className={`text-xs ${getThemeClasses("text-error")} mt-2 font-medium`}>
                              <strong>Error:</strong>{" "}
                              {fileDetails._decryptionError}
                            </p>
                          )}
                        </div>
                      </div>
                    </div>
                  )}
                </div>

                {/* Technical Details */}
                <div className={`border-t ${getThemeClasses("border-secondary")} pt-4 mt-4`}>
                  <button
                    onClick={() => setShowTechnicalDetails(!showTechnicalDetails)}
                    className={`w-full flex items-center justify-between text-sm font-semibold ${getThemeClasses("text-primary")} ${getThemeClasses("hover:text-accent")} transition-colors`}
                  >
                    <span className="flex items-center">
                      <ServerIcon className={`h-5 w-5 mr-2 ${getThemeClasses("text-secondary")}`} />
                      Technical Details
                    </span>
                    {showTechnicalDetails ? (
                      <ChevronUpIcon className={`h-5 w-5 ${getThemeClasses("text-muted")}`} />
                    ) : (
                      <ChevronDownIcon className={`h-5 w-5 ${getThemeClasses("text-muted")}`} />
                    )}
                  </button>
                  {showTechnicalDetails && (
                    <dl className="space-y-2 mt-4">
                      <div className={`flex justify-between py-2 border-b ${getThemeClasses("border-secondary")}`}>
                        <dt className={`text-sm font-medium ${getThemeClasses("text-secondary")}`}>
                          File ID
                        </dt>
                        <dd className={`text-sm ${getThemeClasses("text-primary")} font-mono break-all`}>
                          {fileDetails.id}
                        </dd>
                      </div>
                      <div className={`flex justify-between py-2 border-b ${getThemeClasses("border-secondary")}`}>
                        <dt className={`text-sm font-medium ${getThemeClasses("text-secondary")}`}>
                          Collection ID
                        </dt>
                        <dd className={`text-sm ${getThemeClasses("text-primary")} font-mono break-all`}>
                          {fileDetails.collection_id}
                        </dd>
                      </div>
                      <div className="flex justify-between py-2">
                        <dt className={`text-sm font-medium ${getThemeClasses("text-secondary")}`}>
                          State
                        </dt>
                        <dd>
                          <span className={`px-2 py-1 rounded text-xs font-medium ${getThemeClasses("bg-success-light")} ${getThemeClasses("text-success")} capitalize`}>
                            {getStateLabel(fileDetails.state)}
                          </span>
                        </dd>
                      </div>
                    </dl>
                  )}
                </div>
              </div>

              {/* Download Button */}
              <Button
                onClick={handleDownloadFile}
                disabled={isDownloading || !fileDetails._isDecrypted}
                variant="primary"
                className="w-full"
              >
                <span className="inline-flex items-center justify-center gap-2">
                  {isDownloading ? (
                    <>
                      <div className="animate-spin rounded-full h-5 w-5 border-2 border-white border-t-transparent"></div>
                      <span>Downloading...</span>
                    </>
                  ) : (
                    <>
                      <ArrowDownTrayIcon className="h-5 w-5" />
                      <span>Download</span>
                    </>
                  )}
                </span>
              </Button>
              {!fileDetails._isDecrypted && (
                <Alert type="warning" className="mt-3">
                  File must be decrypted before downloading
                </Alert>
              )}
            </div>
          </div>
        </Card>
      </div>

      {showDeleteConfirm && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
          <div className={`${getThemeClasses("bg-card")} rounded-xl shadow-xl max-w-md w-full p-6`}>
            <div className="text-center">
              <div className={`mx-auto flex items-center justify-center h-12 w-12 rounded-full ${getThemeClasses("bg-error-light")} mb-4`}>
                <ExclamationTriangleIcon className={`h-6 w-6 ${getThemeClasses("text-error")}`} />
              </div>
              <h3 className={`text-lg font-semibold ${getThemeClasses("text-primary")} mb-2`}>
                Delete File
              </h3>
              <p className={`text-sm ${getThemeClasses("text-secondary")} mb-6`}>
                Are you sure you want to delete "
                {fileDetails.name || "this file"}"? The file will be moved to
                trash and permanently deleted after 30 days.
              </p>
            </div>
            <div className="flex justify-end space-x-3">
              <Button
                onClick={() => setShowDeleteConfirm(false)}
                variant="secondary"
              >
                Cancel
              </Button>
              <Button onClick={handleDeleteFile} variant="danger">
                Delete File
              </Button>
            </div>
          </div>
        </div>
      )}

      {/* Tag Editor Modal */}
      {showTagEditor && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
          <div className={`${getThemeClasses("bg-card")} rounded-xl shadow-xl max-w-md w-full p-6`}>
            <div className="flex items-center justify-between mb-4">
              <h3 className={`text-lg font-semibold ${getThemeClasses("text-primary")} flex items-center`}>
                <TagIcon className="h-5 w-5 mr-2" />
                Edit Tags
              </h3>
              <button
                onClick={handleCloseTagEditor}
                className={`${getThemeClasses("text-secondary")} ${getThemeClasses("hover:text-primary")} transition-colors`}
              >
                <XMarkIcon className="h-5 w-5" />
              </button>
            </div>

            {tagError && (
              <Alert type="error" className="mb-4">
                {tagError}
              </Alert>
            )}

            <p className={`text-sm ${getThemeClasses("text-secondary")} mb-4`}>
              Select the tags you want to assign to this file:
            </p>

            {isLoadingTags ? (
              <div className="flex items-center justify-center py-8">
                <div className={`h-6 w-6 spinner ${getThemeClasses("border-primary")}`}></div>
                <span className={`ml-2 text-sm ${getThemeClasses("text-secondary")}`}>Loading tags...</span>
              </div>
            ) : availableTags.length === 0 ? (
              <div className={`text-center py-6 ${getThemeClasses("text-muted")}`}>
                <TagIcon className="h-10 w-10 mx-auto mb-2 opacity-50" />
                <p className="text-sm">No tags available.</p>
                <p className="text-xs mt-1">Create tags in the Tags section first.</p>
              </div>
            ) : (
              <div className="max-h-60 overflow-y-auto space-y-2 mb-4">
                {availableTags.map((tag) => (
                  <label
                    key={tag.id}
                    className={`flex items-center p-3 rounded-lg cursor-pointer transition-colors ${
                      selectedTagIds.includes(tag.id)
                        ? getThemeClasses("bg-accent-light")
                        : getThemeClasses("bg-muted")
                    } ${getThemeClasses("hover:bg-accent-light")}`}
                  >
                    <input
                      type="checkbox"
                      checked={selectedTagIds.includes(tag.id)}
                      onChange={() => handleToggleTag(tag.id)}
                      className={`h-4 w-4 rounded ${getThemeClasses("checkbox-focus")}`}
                    />
                    <span
                      className="w-4 h-4 rounded-full ml-3 mr-2 flex-shrink-0"
                      style={{ backgroundColor: tag.color || '#6B7280' }}
                    />
                    <span className={`text-sm ${getThemeClasses("text-primary")} truncate`}>
                      {tag.name || "Unnamed Tag"}
                    </span>
                  </label>
                ))}
              </div>
            )}

            <div className={`flex justify-end space-x-3 mt-4 pt-4 border-t ${getThemeClasses("border-secondary")}`}>
              <Button
                onClick={handleCloseTagEditor}
                variant="secondary"
                disabled={isSavingTags}
              >
                Cancel
              </Button>
              <Button
                onClick={handleSaveTags}
                variant="primary"
                disabled={isSavingTags || isLoadingTags}
              >
                {isSavingTags ? (
                  <span className="inline-flex items-center">
                    <div className="animate-spin rounded-full h-4 w-4 border-2 border-white border-t-transparent mr-2"></div>
                    Saving...
                  </span>
                ) : (
                  <span className="inline-flex items-center">
                    <CheckIcon className="h-4 w-4 mr-1" />
                    Save Tags
                  </span>
                )}
              </Button>
            </div>
          </div>
        </div>
      )}
    </Layout>
  );
};

export default withPasswordProtection(FileDetails);
