import { useState, useEffect } from "react";
import { motion } from "framer-motion";
import type { Variants } from "framer-motion";
import {
  UploadCloud, Search, File, Share2, Folder, Sparkles, Filter, LayoutGrid,
  List, ArrowUpDown, Shield, X
} from "lucide-react";
import { useAuthStore } from "../hooks/use-auth";
import { axiosInstance } from "../services/axios";
import {
  getAssets,
  getOrganizations,
  deleteAsset,
  requestDownload,
  approveDownloadRequest,
  rejectDownloadRequest,
  downloadAssetFile,
  getAssetGroups,
  getTaxonomyMeta,
} from "../services/assets-api";
import type { AssetGroup } from "../services/assets-api";
import { useToast } from "../hooks/use-toast";

// Subcomponents
import { AssetCard } from "../features/assets/components/AssetCard";
import { UploadAssetModal } from "../features/assets/components/UploadAssetModal";
import { EditAssetModal } from "../features/assets/components/EditAssetModal";
import { ShareAssetModal } from "../features/assets/components/ShareAssetModal";
import { AssetDetailsModal } from "../features/assets/components/AssetDetailsModal";
import { AssetViewerModal } from "../features/assets/components/AssetViewerModal";
import { DownloadRequestsModal } from "../features/assets/components/DownloadRequestsModal";
import { ManageGroupsModal } from "../features/assets/components/ManageGroupsModal";
import { FilterDrawer } from "../features/assets/components/FilterDrawer";
import { AssetTableView } from "../features/assets/components/AssetTableView";
import { AssetAdminManagerModal } from "../features/assets/components/AssetAdminManagerModal";

import { PageHeader } from "../components/ui/PageHeader";
import Button from "../components/ui/Button";
import { PageLayout } from "../components/layout/PageLayout";
import Modal from "../components/ui/Modal";

// Type Definitions
import type { Asset, Organization, TaxonomyMeta, AssetQueryFilters } from "../types/assets";

const containerVariants: Variants = {
  hidden: { opacity: 0 },
  show: { opacity: 1, transition: { staggerChildren: 0.04 } },
};

const itemVariants: Variants = {
  hidden: { opacity: 0, y: 12, scale: 0.98 },
  show: {
    opacity: 1,
    y: 0,
    scale: 1,
    transition: { type: "spring", stiffness: 350, damping: 25 },
  },
};

export const AssetsPage = () => {
  const { success, error } = useToast();
  const user = useAuthStore((state) => state.user);
  const [assets, setAssets] = useState<Asset[]>([]);
  const [organizations, setOrganizations] = useState<Organization[]>([]);
  const [taxonomyMeta, setTaxonomyMeta] = useState<TaxonomyMeta | null>(null);
  const [loading, setLoading] = useState(true);
  const [groups, setGroups] = useState<AssetGroup[]>([]);

  // Layout Density State
  const [viewMode, setViewMode] = useState<'grid' | 'compact' | 'table'>('grid');

  // Search, Sort & Filter State
  const [searchQuery, setSearchQuery] = useState("");
  const [selectedCategory, setSelectedCategory] = useState<string>("ALL");
  const [sortBy, setSortBy] = useState<'newest' | 'oldest' | 'title_asc' | 'title_desc' | 'type'>('newest');
  const [filters, setFilters] = useState<AssetQueryFilters>({});

  // Slide-over Filter Drawer & Admin Manager Controls
  const [isFilterDrawerOpen, setIsFilterDrawerOpen] = useState(false);
  const [isAdminManagerOpen, setIsAdminManagerOpen] = useState(false);

  // Multi-Selection State (Shift+Click Engine)
  const [selectedAssetIds, setSelectedAssetIds] = useState<string[]>([]);
  const [lastSelectedIndex, setLastSelectedIndex] = useState<number | null>(null);

  // Recommended assets logic
  const partnerGroupStrings = user?.partnerGroup && user.role === "PARTNER_USER"
    ? user.partnerGroup.split(',').map(s => s.trim().toLowerCase())
    : [];

  const recommendedAssets = (() => {
    if (partnerGroupStrings.length === 0) return [];
    const activeGroups = groups.filter(g => partnerGroupStrings.includes(g.name.trim().toLowerCase()));
    return activeGroups
      .flatMap(g => g.assets)
      .filter((recAsset, index, self) =>
        self.findIndex(a => a.id === recAsset.id) === index &&
        assets.some(allAsset => allAsset.id === recAsset.id)
      );
  })();

  // Modal Control States
  const [isUploadOpen, setIsUploadOpen] = useState(false);
  const [isEditOpen, setIsEditOpen] = useState(false);
  const [isShareOpen, setIsShareOpen] = useState(false);
  const [isDetailsOpen, setIsDetailsOpen] = useState(false);
  const [isViewerOpen, setIsViewerOpen] = useState(false);
  const [isRequestsOpen, setIsRequestsOpen] = useState(false);
  const [isGroupsOpen, setIsGroupsOpen] = useState(false);

  const [activeAsset, setActiveAsset] = useState<Asset | null>(null);
  const [activeMenuId, setActiveMenuId] = useState<string | null>(null);
  const [expandedAssetId, setExpandedAssetId] = useState<string | null>(null);
  const [assetToDelete, setAssetToDelete] = useState<{ id: string, title: string } | null>(null);

  useEffect(() => {
    fetchData();
  }, []);

  const fetchData = async () => {
    setLoading(true);
    try {
      const [assetsData, metaData, groupsData] = await Promise.all([
        getAssets({ ...filters, search: searchQuery, sortBy }),
        getTaxonomyMeta(),
        getAssetGroups(),
      ]);

      setAssets(assetsData);
      setTaxonomyMeta(metaData);
      setGroups(groupsData);

      if (user?.role === "ADMIN") {
        const orgsData = await getOrganizations();
        setOrganizations(orgsData);
      }
    } catch (err) {
      console.error("Failed to fetch assets data", err);
    } finally {
      setLoading(false);
    }
  };

  // Re-fetch when query or filters change
  useEffect(() => {
    const timer = setTimeout(() => {
      fetchFilteredAssets();
    }, 250);
    return () => clearTimeout(timer);
  }, [searchQuery, sortBy, filters]);

  const fetchFilteredAssets = async () => {
    try {
      const assetsData = await getAssets({
        ...filters,
        search: searchQuery,
        sortBy,
      });
      setAssets(assetsData);
    } catch (err) {
      console.error("Failed to filter assets", err);
    }
  };

  // Shift + Click Range Multi-Selection Handler
  const handleToggleSelectAsset = (assetId: string, event?: React.MouseEvent) => {
    const clickedIndex = filteredAssets.findIndex(a => a.id === assetId);

    if (event?.shiftKey && lastSelectedIndex !== null && clickedIndex !== -1) {
      const start = Math.min(lastSelectedIndex, clickedIndex);
      const end = Math.max(lastSelectedIndex, clickedIndex);
      const rangeIds = filteredAssets.slice(start, end + 1).map(a => a.id);

      setSelectedAssetIds(prev => Array.from(new Set([...prev, ...rangeIds])));
    } else {
      setSelectedAssetIds(prev =>
        prev.includes(assetId) ? prev.filter(id => id !== assetId) : [...prev, assetId]
      );
      setLastSelectedIndex(clickedIndex);
    }
  };

  const handleSelectAll = () => {
    if (selectedAssetIds.length === filteredAssets.length) {
      setSelectedAssetIds([]);
    } else {
      setSelectedAssetIds(filteredAssets.map(a => a.id));
    }
  };

  const openEditModal = (asset: Asset) => {
    setActiveAsset(asset);
    setIsEditOpen(true);
  };

  const openShareModal = (asset: Asset) => {
    setSelectedAssetIds([]);
    setActiveAsset(asset);
    setIsShareOpen(true);
  };

  const openViewerModal = (asset: Asset) => {
    setActiveAsset(asset);
    setIsViewerOpen(true);
  };

  const openDetailsModal = (asset: Asset) => {
    setActiveAsset(asset);
    setIsDetailsOpen(true);
  };

  const handleDeleteAsset = (id: string) => {
    const asset = assets.find(a => a.id === id);
    if (asset) {
      setAssetToDelete({ id: asset.id, title: asset.title });
    }
  };

  const confirmDeleteAsset = async () => {
    if (!assetToDelete) return;
    try {
      await deleteAsset(assetToDelete.id);
      success("Asset deleted successfully", `"${assetToDelete.title}" has been permanently removed.`);
      setAssetToDelete(null);
      await fetchData();
    } catch (err: any) {
      error("Failed to delete asset", err.response?.data?.error || "Something went wrong.");
    }
  };

  const handleRequestDownload = async (asset: Asset) => {
    try {
      await requestDownload(asset.id);
      success("Download request submitted", "An administrator has been notified of your request.");
      await fetchData();
    } catch (err: any) {
      error("Failed to submit request", err.response?.data?.error || "Something went wrong.");
    }
  };

  const handleApproveRequest = async (assetId: string, requestId: string) => {
    try {
      await approveDownloadRequest(assetId, requestId);
      success("Download request approved", "The partner can now download this asset.");
      await fetchData();
    } catch (err: any) {
      error("Failed to approve request", err.response?.data?.error || "Something went wrong.");
    }
  };

  const handleRejectRequest = async (assetId: string, requestId: string) => {
    try {
      await rejectDownloadRequest(assetId, requestId);
      success("Download request rejected", "The access request was denied.");
      await fetchData();
    } catch (err: any) {
      error("Failed to reject request", err.response?.data?.error || "Something went wrong.");
    }
  };

  const handleDownload = async (asset: Asset) => {
    success("Download started", `Downloading "${asset.title}"...`);
    try {
      await downloadAssetFile(asset.id);
      const downloadUrl = asset.url.startsWith("http")
        ? asset.url
        : `${axiosInstance.defaults.baseURL?.replace("/api/v1", "")}${asset.url}`;

      const a = document.createElement("a");
      a.href = downloadUrl;
      a.download = asset.title;
      a.target = "_blank";
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);

      setAssets(prev =>
        prev.map(item => item.id === asset.id ? { ...item, downloadsCount: item.downloadsCount + 1 } : item)
      );
    } catch (err: any) {
      error("Download failed", err.response?.data?.error || "Could not retrieve asset file.");
    }
  };

  // Client-side filtering fallback
  const filteredAssets = assets.filter((asset) => {
    if (selectedCategory === "RECOMMENDED") {
      return recommendedAssets.some((r) => r.id === asset.id);
    }
    return true;
  });

  const activeFilterCount =
    (filters.verticalIds?.length || 0) +
    (filters.contentTypes?.length || 0) +
    (filters.subcategories?.length || 0) +
    (filters.tags?.length || 0);

  const pendingRequestsCount = assets.reduce((acc, asset) => {
    return (
      acc + (asset.downloadRequests?.filter((r) => r.status === "PENDING").length || 0)
    );
  }, 0);

  // Header component
  const headerNode = (
    <PageHeader
      title="Asset Discovery Platform"
      subtitle="Enterprise asset catalog featuring vertical domain search, multi-view density, and partner access controls."
    />
  );

  // Toolbar component
  const toolbarNode = (
    <div className="flex flex-col lg:flex-row gap-3 items-stretch lg:items-center justify-between p-3.5 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-xl shadow-sm">
      <div className="flex flex-wrap items-center gap-3 flex-1 min-w-0">
        
        {/* Search Bar */}
        <div className="relative w-full sm:w-[280px] shrink-0">
          <Search className="w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
          <input
            type="text"
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="w-full bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-lg py-2 pl-9 pr-4 text-xs font-medium text-slate-900 dark:text-slate-100 placeholder-slate-400 outline-none focus:ring-2 ring-slate-400/20 focus:border-slate-500 transition-all"
            placeholder="Search catalog titles, tags..."
          />
        </div>

        {/* Sorting Dropdown */}
        <div className="flex items-center gap-1.5 bg-slate-50 dark:bg-slate-800 px-2.5 py-1.5 rounded-lg border border-slate-200 dark:border-slate-700 shrink-0">
          <ArrowUpDown className="w-3.5 h-3.5 text-slate-400" />
          <select
            value={sortBy}
            onChange={(e) => setSortBy(e.target.value as any)}
            className="bg-transparent text-xs font-semibold text-slate-700 dark:text-slate-300 outline-none cursor-pointer"
          >
            <option value="newest">Newest First</option>
            <option value="oldest">Oldest First</option>
            <option value="title_asc">Title A-Z</option>
            <option value="title_desc">Title Z-A</option>
            <option value="type">Format / Type</option>
          </select>
        </div>

        {/* View Density Switcher */}
        <div className="flex items-center p-0.5 bg-slate-100 dark:bg-slate-800 rounded-lg border border-slate-200 dark:border-slate-700 shrink-0">
          <button
            onClick={() => setViewMode('grid')}
            className={`p-1.5 rounded-md text-xs transition-all ${
              viewMode === 'grid'
                ? 'bg-white dark:bg-slate-900 text-slate-900 dark:text-white shadow-xs font-bold'
                : 'text-slate-500 hover:text-slate-800 dark:hover:text-slate-200'
            }`}
            title="Grid Cards"
          >
            <LayoutGrid className="w-4 h-4" />
          </button>
          <button
            onClick={() => setViewMode('compact')}
            className={`p-1.5 rounded-md text-xs transition-all ${
              viewMode === 'compact'
                ? 'bg-white dark:bg-slate-900 text-slate-900 dark:text-white shadow-xs font-bold'
                : 'text-slate-500 hover:text-slate-800 dark:hover:text-slate-200'
            }`}
            title="Compact Cards"
          >
            <LayoutGrid className="w-3.5 h-3.5 stroke-[2.5]" />
          </button>
          <button
            onClick={() => setViewMode('table')}
            className={`p-1.5 rounded-md text-xs transition-all ${
              viewMode === 'table'
                ? 'bg-white dark:bg-slate-900 text-slate-900 dark:text-white shadow-xs font-bold'
                : 'text-slate-500 hover:text-slate-800 dark:hover:text-slate-200'
            }`}
            title="Tabular List View (Shift+Click)"
          >
            <List className="w-4 h-4" />
          </button>
        </div>

        {/* Partner Recommended Toggle */}
        {user?.role === "PARTNER_USER" && recommendedAssets.length > 0 && (
          <div className="flex items-center gap-1 bg-slate-100 dark:bg-slate-800 p-1 rounded-xl shrink-0">
            <button
              onClick={() => setSelectedCategory("ALL")}
              className={`px-3 py-1 rounded-lg text-xs font-semibold transition-all ${
                selectedCategory === "ALL"
                  ? "bg-slate-900 text-white shadow-xs"
                  : "text-slate-600 dark:text-slate-300 hover:bg-slate-200"
              }`}
            >
              All Assets
            </button>
            <button
              onClick={() => setSelectedCategory("RECOMMENDED")}
              className={`px-3 py-1 rounded-lg text-xs font-semibold flex items-center gap-1.5 transition-all ${
                selectedCategory === "RECOMMENDED"
                  ? "bg-amber-500 text-slate-950 font-bold shadow-xs"
                  : "text-amber-600 dark:text-amber-400 hover:bg-amber-500/10"
              }`}
            >
              <Sparkles className="w-3.5 h-3.5" />
              <span>Recommended ({recommendedAssets.length})</span>
            </button>
          </div>
        )}

      </div>

      {/* Right Action & Filter Drawer Trigger Area */}
      <div className="flex items-center gap-2 shrink-0 justify-end">
        {user?.role === "ADMIN" && (
          <>
            {selectedAssetIds.length > 0 ? (
              <Button
                onClick={() => setSelectedAssetIds([])}
                variant="ghost"
                size="sm"
                className="text-xs font-semibold text-slate-500 hover:text-slate-900 dark:hover:text-slate-100"
              >
                Deselect All
              </Button>
            ) : (
              <Button
                onClick={handleSelectAll}
                variant="ghost"
                size="sm"
                className="text-xs font-semibold text-slate-500 hover:text-slate-900 dark:hover:text-slate-100"
              >
                Select All
              </Button>
            )}

            <Button
              onClick={() => setIsAdminManagerOpen(true)}
              variant="secondary"
              size="sm"
              icon={<Shield className="w-3.5 h-3.5 text-slate-700 dark:text-slate-300" />}
            >
              Taxonomy & Announcements
            </Button>
          </>
        )}

        {user?.role === "ADMIN" && pendingRequestsCount > 0 && (
          <Button
            onClick={() => setIsRequestsOpen(true)}
            variant="secondary"
            size="sm"
            icon={
              <span className="w-4 h-4 rounded-full bg-slate-900 dark:bg-slate-100 text-white dark:text-slate-900 text-[10px] flex items-center justify-center font-bold">
                {pendingRequestsCount}
              </span>
            }
          >
            Requests
          </Button>
        )}

        {user?.role === "ADMIN" && selectedAssetIds.length > 0 && (
          <Button
            onClick={() => {
              setActiveAsset(null);
              setIsShareOpen(true);
            }}
            variant="secondary"
            size="sm"
            icon={<Share2 className="w-3.5 h-3.5" />}
          >
            Share ({selectedAssetIds.length})
          </Button>
        )}

        {user?.role === "ADMIN" && (
          <Button
            onClick={() => setIsGroupsOpen(true)}
            variant="secondary"
            size="sm"
            icon={<Folder className="w-3.5 h-3.5" />}
          >
            Groups
          </Button>
        )}

        {user?.role === "ADMIN" && (
          <Button
            onClick={() => setIsUploadOpen(true)}
            variant="primary"
            size="sm"
            icon={<UploadCloud className="w-3.5 h-3.5" />}
          >
            Create Asset
          </Button>
        )}

        {/* Filter Drawer Trigger Button positioned on the far right end */}
        <button
          onClick={() => setIsFilterDrawerOpen(true)}
          className={`flex items-center gap-2 px-3.5 py-2 rounded-lg text-xs font-bold border transition-all ${
            activeFilterCount > 0
              ? "bg-slate-900 text-white border-slate-900 shadow-sm dark:bg-slate-100 dark:text-slate-900"
              : "bg-slate-50 dark:bg-slate-800 border-slate-200 dark:border-slate-700 text-slate-700 dark:text-slate-200 hover:bg-slate-100 dark:hover:bg-slate-700"
          }`}
        >
          <Filter className="w-4 h-4" />
          <span>Filters</span>
          {activeFilterCount > 0 && (
            <span className="px-1.5 py-0.2 text-[10px] font-extrabold rounded-full bg-amber-500 text-slate-950">
              {activeFilterCount}
            </span>
          )}
        </button>
      </div>
    </div>
  );

  return (
    <PageLayout header={headerNode} toolbar={toolbarNode}>
      <div className="p-5 flex-1 min-h-0 overflow-y-auto custom-scrollbar">

        {/* Result Counter & Active Filter Badges */}
        <div className="mb-4 flex flex-wrap items-center justify-between gap-3 text-xs">
          <div className="text-slate-500 font-medium flex items-center gap-2">
            <span>Showing <strong className="text-slate-900 dark:text-slate-100">{filteredAssets.length}</strong> of {taxonomyMeta?.totalAssets || assets.length} assets</span>
            {selectedAssetIds.length > 0 && (
              <span className="px-2 py-0.5 rounded-md bg-slate-100 dark:bg-slate-800 text-slate-900 dark:text-slate-100 font-bold border border-slate-300 dark:border-slate-700">
                {selectedAssetIds.length} selected (Hold Shift to range-select)
              </span>
            )}
          </div>

          {activeFilterCount > 0 && (
            <button
              onClick={() => setFilters({})}
              className="text-xs text-slate-700 dark:text-slate-300 hover:text-slate-900 dark:hover:text-white font-bold flex items-center gap-1"
            >
              <X className="w-3.5 h-3.5" />
              Reset Filters ({activeFilterCount})
            </button>
          )}
        </div>

        {loading ? (
          <div className="py-20 flex justify-center items-center">
            <div className="w-8 h-8 border-4 border-slate-400/30 border-t-slate-900 dark:border-t-slate-100 rounded-full animate-spin" />
          </div>
        ) : (
          <>
            {filteredAssets.length === 0 ? (
              <div className="py-16 text-center bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl">
                <File className="w-12 h-12 text-slate-300 mx-auto mb-4" />
                <h3 className="text-lg font-bold text-slate-900 dark:text-slate-100">No assets match your query</h3>
                <p className="text-slate-500 text-xs mt-1 max-w-sm mx-auto">
                  Try broadening your search keywords or clearing active domain filters.
                </p>
                <button
                  onClick={() => { setSearchQuery(''); setFilters({}); }}
                  className="mt-4 px-4 py-2 rounded-lg bg-slate-900 dark:bg-slate-100 text-white dark:text-slate-900 text-xs font-bold"
                >
                  Clear All Filters
                </button>
              </div>
            ) : viewMode === 'table' ? (
              /* TABULAR LIST VIEW */
              <AssetTableView
                assets={filteredAssets}
                selectedIds={selectedAssetIds}
                recommendedIds={recommendedAssets.map(r => r.id)}
                onToggleSelect={handleToggleSelectAsset}
                onSelectAll={handleSelectAll}
                onOpenAsset={openViewerModal}
                onRequestDownload={(id) => {
                  const asset = assets.find(a => a.id === id);
                  if (asset) handleRequestDownload(asset);
                }}
                userRole={user?.role}
              />
            ) : (
              /* GRID / COMPACT VIEW */
              <motion.div
                variants={containerVariants}
                initial="hidden"
                animate="show"
                className={`grid grid-cols-1 ${
                  viewMode === 'compact'
                    ? 'md:grid-cols-3 xl:grid-cols-5 gap-3'
                    : 'md:grid-cols-2 xl:grid-cols-4 gap-4'
                } items-start`}
              >
                {filteredAssets.map((asset) => (
                  <motion.div
                    key={asset.id}
                    variants={itemVariants}
                    className={`relative ${viewMode === 'compact' ? 'h-[360px]' : 'h-[410px]'} w-full flex flex-col`}
                  >
                    <AssetCard
                      asset={asset}
                      user={user}
                      activeMenuId={activeMenuId}
                      setActiveMenuId={setActiveMenuId}
                      onViewDetails={openDetailsModal}
                      onEdit={openEditModal}
                      onShare={openShareModal}
                      onDelete={handleDeleteAsset}
                      onOpenViewer={openViewerModal}
                      onDownload={handleDownload}
                      onRequestDownload={handleRequestDownload}
                      isSelected={selectedAssetIds.includes(asset.id)}
                      onToggleSelect={(id, event) => handleToggleSelectAsset(id, event)}
                      isExpanded={expandedAssetId === asset.id}
                      onToggleExpand={() => setExpandedAssetId(expandedAssetId === asset.id ? null : asset.id)}
                      isRecommended={recommendedAssets.some(r => r.id === asset.id)}
                    />
                  </motion.div>
                ))}
              </motion.div>
            )}
          </>
        )}
      </div>

      {/* Slide-over Filter Drawer */}
      <FilterDrawer
        isOpen={isFilterDrawerOpen}
        onClose={() => setIsFilterDrawerOpen(false)}
        meta={taxonomyMeta}
        filters={filters}
        onChangeFilters={setFilters}
        onClearAll={() => setFilters({})}
      />

      {/* Admin Taxonomy & Announcements Control Modal */}
      <AssetAdminManagerModal
        isOpen={isAdminManagerOpen}
        onClose={() => setIsAdminManagerOpen(false)}
        meta={taxonomyMeta}
        organizations={organizations}
        allAssets={assets}
        onRefreshMeta={fetchData}
      />

      {/* Modals Container */}
      <UploadAssetModal
        isOpen={isUploadOpen}
        onClose={() => setIsUploadOpen(false)}
        onSuccess={fetchData}
      />

      <EditAssetModal
        isOpen={isEditOpen}
        onClose={() => {
          setIsEditOpen(false);
          setActiveAsset(null);
        }}
        asset={activeAsset}
        onSuccess={fetchData}
      />

      <ShareAssetModal
        isOpen={isShareOpen}
        onClose={() => {
          setIsShareOpen(false);
          setActiveAsset(null);
          setSelectedAssetIds([]);
        }}
        asset={activeAsset}
        assetIds={selectedAssetIds}
        organizations={organizations}
        onSuccess={fetchData}
      />

      <AssetDetailsModal
        isOpen={isDetailsOpen}
        onClose={() => {
          setIsDetailsOpen(false);
          setActiveAsset(null);
        }}
        asset={activeAsset}
        userRole={user?.role}
      />

      <AssetViewerModal
        isOpen={isViewerOpen}
        onClose={() => {
          setIsViewerOpen(false);
          setActiveAsset(null);
        }}
        asset={activeAsset}
        user={user}
        onDownload={handleDownload}
      />

      <DownloadRequestsModal
        isOpen={isRequestsOpen}
        onClose={() => setIsRequestsOpen(false)}
        assets={assets}
        onApprove={handleApproveRequest}
        onReject={handleRejectRequest}
      />

      <ManageGroupsModal
        isOpen={isGroupsOpen}
        onClose={() => setIsGroupsOpen(false)}
        assets={assets}
        groups={groups}
        onRefresh={fetchData}
      />

      {/* Delete Confirmation Modal */}
      <Modal
        isOpen={assetToDelete !== null}
        onClose={() => setAssetToDelete(null)}
        title="Delete Asset"
        subtitle="Confirm permanent resource deletion."
        size="sm"
      >
        <div className="space-y-4 font-sans">
          <p className="text-xs text-slate-600 dark:text-slate-400 leading-relaxed">
            Are you sure you want to permanently delete <span className="font-bold text-slate-900 dark:text-white">"{assetToDelete?.title}"</span>? This action cannot be undone.
          </p>
          <div className="flex gap-3 justify-end pt-2">
            <Button
              onClick={() => setAssetToDelete(null)}
              variant="secondary"
              size="sm"
            >
              Cancel
            </Button>
            <Button
              onClick={confirmDeleteAsset}
              variant="danger"
              size="sm"
            >
              Delete Permanently
            </Button>
          </div>
        </div>
      </Modal>
    </PageLayout>
  );
};

export default AssetsPage;
