import React, { useState, useEffect, useRef, useCallback, useMemo } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { useAssets, useAssetMutations } from '../hooks/useAsset';
import * as XLSX from 'xlsx';
import { FaPlus, FaSearch, FaEdit, FaEye, FaTrash, FaCopy, FaEllipsisV, FaDownload, FaPrint, FaFileExport, FaTimes, FaFilter, FaChevronDown, FaChevronUp, FaSave,
   FaStar, FaLock, FaCheckSquare, FaSquare, FaFileExcel, FaFileCsv, FaWrench, FaClipboardList  } from 'react-icons/fa';
import LinkField from '../components/LinkField';
import { useUserPermissions } from '../hooks/useUserPermissions';
import { ScanQRButton } from '../components/QRScanner';
import ListPagination from '../components/ListPagination';
import ListFilterSortControls from '../components/ListFilterSortControls';
import { useListSortFilters } from '../hooks/useListSortFilters';
import { buildDateRangeFilters } from '../utils/listFilterUtils';
import { buildMobileTeamSiteFilters } from '../utils/hospitalUtils';
import useUserPhccSiteFilter from '../hooks/useUserPhccSiteFilter';
import useUserHospitalFilter from '../hooks/useUserHospitalFilter';

// Export column configuration - will be defined inside component to use translations

type ExportFormat = 'csv' | 'excel';
type ExportScope = 'selected' | 'all_on_page' | 'all_with_filters';

interface ExportModalProps {
  isOpen: boolean;
  onClose: () => void;
  selectedCount: number;
  totalCount: number;
  pageCount: number;
  onExport: (scope: ExportScope, format: ExportFormat, columns: string[]) => void;
  isExporting: boolean;
}

const ExportModal: React.FC<ExportModalProps & { exportColumns: Array<{key: string, label: string, default: boolean}> }> = ({
  isOpen,
  onClose,
  selectedCount,
  totalCount,
  pageCount,
  onExport,
  isExporting,
  exportColumns
}) => {
  const { t } = useTranslation();
  const [scope, setScope] = useState<ExportScope>(selectedCount > 0 ? 'selected' : 'all_with_filters');
  const [format, setFormat] = useState<ExportFormat>('csv');
  const [selectedColumns, setSelectedColumns] = useState<string[]>(
    exportColumns.filter(c => c.default).map(c => c.key)
  );

  useEffect(() => {
    if (selectedCount > 0) {
      setScope('selected');
    } else {
      setScope('all_with_filters');
    }
  }, [selectedCount]);

  const toggleColumn = (key: string) => {
    setSelectedColumns(prev => 
      prev.includes(key) 
        ? prev.filter(k => k !== key)
        : [...prev, key]
    );
  };

  const selectAllColumns = () => {
    setSelectedColumns(exportColumns.map(c => c.key));
  };

  const selectDefaultColumns = () => {
    setSelectedColumns(exportColumns.filter(c => c.default).map(c => c.key));
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-[70] p-4">
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl max-w-2xl w-full max-h-[90vh] overflow-hidden animate-scale-in">
        {/* Header */}
        <div className="bg-gradient-to-r from-green-500 to-green-600 px-6 py-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              <FaFileExport className="text-white text-xl" />
              <h3 className="text-lg font-semibold text-white">{t('listPages.export')} {t('assets.title')}</h3>
            </div>
            <button
              onClick={onClose}
              className="text-white/80 hover:text-white transition-colors"
              disabled={isExporting}
            >
              <FaTimes size={20} />
            </button>
          </div>
        </div>

        <div className="p-6 overflow-y-auto max-h-[calc(90vh-180px)]">
          {/* Export Scope */}
          <div className="mb-6">
            <h4 className="text-sm font-semibold text-gray-700 dark:text-gray-300 mb-3">
              {t('listPages.exportFormat')}
            </h4>
            <div className="space-y-2">
              <label className={`flex items-center gap-3 p-3 rounded-lg border cursor-pointer transition-all ${
                scope === 'selected' 
                  ? 'border-green-500 bg-green-50 dark:bg-green-900/20' 
                  : 'border-gray-200 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-700/50'
              } ${selectedCount === 0 ? 'opacity-50 cursor-not-allowed' : ''}`}>
                <input
                  type="radio"
                  name="scope"
                  value="selected"
                  checked={scope === 'selected'}
                  onChange={() => setScope('selected')}
                  disabled={selectedCount === 0}
                  className="text-green-600 focus:ring-green-500"
                />
                <div className="flex-1">
                  <div className="font-medium text-gray-900 dark:text-white">
                    Selected Rows
                  </div>
                  <div className="text-sm text-gray-500 dark:text-gray-400">
                    Export {selectedCount} selected asset{selectedCount !== 1 ? 's' : ''}
                  </div>
                </div>
                {selectedCount > 0 && (
                  <span className="bg-green-100 dark:bg-green-900/40 text-green-700 dark:text-green-300 px-2 py-1 rounded text-xs font-medium">
                    {selectedCount} selected
                  </span>
                )}
              </label>

              <label className={`flex items-center gap-3 p-3 rounded-lg border cursor-pointer transition-all ${
                scope === 'all_on_page' 
                  ? 'border-green-500 bg-green-50 dark:bg-green-900/20' 
                  : 'border-gray-200 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-700/50'
              }`}>
                <input
                  type="radio"
                  name="scope"
                  value="all_on_page"
                  checked={scope === 'all_on_page'}
                  onChange={() => setScope('all_on_page')}
                  className="text-green-600 focus:ring-green-500"
                />
                <div className="flex-1">
                  <div className="font-medium text-gray-900 dark:text-white">
                    Current Page
                  </div>
                  <div className="text-sm text-gray-500 dark:text-gray-400">
                    Export {pageCount} asset{pageCount !== 1 ? 's' : ''} on current page
                  </div>
                </div>
                <span className="bg-blue-100 dark:bg-blue-900/40 text-blue-700 dark:text-blue-300 px-2 py-1 rounded text-xs font-medium">
                  {pageCount} rows
                </span>
              </label>

              <label className={`flex items-center gap-3 p-3 rounded-lg border cursor-pointer transition-all ${
                scope === 'all_with_filters' 
                  ? 'border-green-500 bg-green-50 dark:bg-green-900/20' 
                  : 'border-gray-200 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-700/50'
              }`}>
                <input
                  type="radio"
                  name="scope"
                  value="all_with_filters"
                  checked={scope === 'all_with_filters'}
                  onChange={() => setScope('all_with_filters')}
                  className="text-green-600 focus:ring-green-500"
                />
                <div className="flex-1">
                  <div className="font-medium text-gray-900 dark:text-white">
                    All Records (with current filters)
                  </div>
                  <div className="text-sm text-gray-500 dark:text-gray-400">
                    Export all {totalCount} asset{totalCount !== 1 ? 's' : ''} matching current filters
                  </div>
                </div>
                <span className="bg-purple-100 dark:bg-purple-900/40 text-purple-700 dark:text-purple-300 px-2 py-1 rounded text-xs font-medium">
                  {totalCount} total
                </span>
              </label>
            </div>
          </div>

          {/* Export Format */}
          <div className="mb-6">
            <h4 className="text-sm font-semibold text-gray-700 dark:text-gray-300 mb-3">
              {t('listPages.exportFormat')}
            </h4>
            <div className="flex gap-3">
              <label className={`flex-1 flex items-center gap-3 p-3 rounded-lg border cursor-pointer transition-all ${
                format === 'csv' 
                  ? 'border-green-500 bg-green-50 dark:bg-green-900/20' 
                  : 'border-gray-200 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-700/50'
              }`}>
                <input
                  type="radio"
                  name="format"
                  value="csv"
                  checked={format === 'csv'}
                  onChange={() => setFormat('csv')}
                  className="text-green-600 focus:ring-green-500"
                />
                <FaFileCsv className="text-green-600 text-xl" />
                <div>
                  <div className="font-medium text-gray-900 dark:text-white">{t('listPages.csv')}</div>
                  <div className="text-xs text-gray-500 dark:text-gray-400">Comma-separated values</div>
                </div>
              </label>

              <label className={`flex-1 flex items-center gap-3 p-3 rounded-lg border cursor-pointer transition-all ${
                format === 'excel' 
                  ? 'border-green-500 bg-green-50 dark:bg-green-900/20' 
                  : 'border-gray-200 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-700/50'
              }`}>
                <input
                  type="radio"
                  name="format"
                  value="excel"
                  checked={format === 'excel'}
                  onChange={() => setFormat('excel')}
                  className="text-green-600 focus:ring-green-500"
                />
                <FaFileExcel className="text-green-700 text-xl" />
                <div>
                  <div className="font-medium text-gray-900 dark:text-white">{t('listPages.excel')}</div>
                  <div className="text-xs text-gray-500 dark:text-gray-400">XLSX spreadsheet</div>
                </div>
              </label>
            </div>
          </div>

          {/* Column Selection */}
          <div>
            <div className="flex items-center justify-between mb-3">
              <h4 className="text-sm font-semibold text-gray-700 dark:text-gray-300">
                Columns to Export
              </h4>
              <div className="flex gap-2">
                <button
                  onClick={selectAllColumns}
                  className="text-xs text-blue-600 dark:text-blue-400 hover:underline"
                >
                  Select All
                </button>
                <span className="text-gray-300 dark:text-gray-600">|</span>
                <button
                  onClick={selectDefaultColumns}
                  className="text-xs text-blue-600 dark:text-blue-400 hover:underline"
                >
                  Reset to Default
                </button>
              </div>
            </div>
            <div className="grid grid-cols-2 md:grid-cols-3 gap-2 max-h-48 overflow-y-auto p-3 bg-gray-50 dark:bg-gray-900/50 rounded-lg">
              {exportColumns.map((col: {key: string, label: string, default: boolean}) => (
                <label
                  key={col.key}
                  className={`flex items-center gap-2 p-2 rounded cursor-pointer transition-all ${
                    selectedColumns.includes(col.key)
                      ? 'bg-green-100 dark:bg-green-900/30 text-green-800 dark:text-green-300'
                      : 'hover:bg-gray-100 dark:hover:bg-gray-800 text-gray-700 dark:text-gray-400'
                  }`}
                >
                  <input
                    type="checkbox"
                    checked={selectedColumns.includes(col.key)}
                    onChange={() => toggleColumn(col.key)}
                    className="rounded text-green-600 focus:ring-green-500"
                  />
                  <span className="text-sm truncate">{col.label}</span>
                </label>
              ))}
            </div>
            <p className="text-xs text-gray-500 dark:text-gray-400 mt-2">
              {selectedColumns.length} column{selectedColumns.length !== 1 ? 's' : ''} selected
            </p>
          </div>
        </div>

        {/* Footer */}
        <div className="px-6 py-4 bg-gray-50 dark:bg-gray-900/50 border-t border-gray-200 dark:border-gray-700 flex justify-between items-center">
          <div className="text-sm text-gray-600 dark:text-gray-400">
            {scope === 'selected' && `Exporting ${selectedCount} selected row${selectedCount !== 1 ? 's' : ''}`}
            {scope === 'all_on_page' && `Exporting ${pageCount} row${pageCount !== 1 ? 's' : ''} from current page`}
            {scope === 'all_with_filters' && `Exporting all ${totalCount} row${totalCount !== 1 ? 's' : ''}`}
          </div>
          <div className="flex gap-3">
            <button
              onClick={onClose}
              className="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
              disabled={isExporting}
            >
              Cancel
            </button>
            <button
              onClick={() => onExport(scope, format, selectedColumns)}
              disabled={selectedColumns.length === 0 || isExporting}
              className="px-4 py-2 text-sm font-medium text-white bg-green-600 hover:bg-green-700 rounded-lg transition-colors flex items-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {isExporting ? (
                <>
                  <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
                  Exporting...
                </>
              ) : (
                <>
                  <FaDownload />
                  Export
                </>
              )}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};


const AssetList: React.FC = () => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const [searchParams, setSearchParams] = useSearchParams();
  const filtersChangedOnce = useRef(false);
  const {
    sortBy,
    dateFilterBy,
    dateStart,
    dateEnd,
    page,
    setSortBy,
    setDateFilterBy,
    setDateStart,
    setDateEnd,
    setPage,
    resetPage,
  } = useListSortFilters('creation desc');
  const [searchTerm, setSearchTerm] = useState('');
  const [deleteConfirmOpen, setDeleteConfirmOpen] = useState<string | null>(null);
  const [actionMenuOpen, setActionMenuOpen] = useState<string | null>(null);
  const dropdownRef = useRef<HTMLDivElement>(null);
  const limit = 20;
  
  // Export column configuration with translations
  const EXPORT_COLUMNS = [
    { key: 'name', label: t('commonFields.assetId'), default: true },
    { key: 'asset_name', label: t('commonFields.assetName'), default: true },
    { key: 'custom_serial_number', label: t('commonFields.serialNumber'), default: true },
    { key: 'company', label: t('commonFields.company'), default: true },
    { key: 'custom_site', label: 'Site Name', default: false },
    { key: 'location', label: t('commonFields.location'), default: true },
    { key: 'department', label: t('commonFields.department'), default: false },
    { key: 'custom_device_status', label: t('commonFields.deviceStatus'), default: true },
    { key: 'custom_modality', label: t('commonFields.modality'), default: false },
    { key: 'custom_manufacturer', label: t('commonFields.manufacturer'), default: false },
    { key: 'supplier', label: t('commonFields.supplier'), default: false },
    { key: 'asset_category', label: t('commonFields.assetCategory'), default: false },
    { key: 'purchase_date', label: t('commonFields.purchaseDate'), default: false },
    { key: 'gross_purchase_amount', label: t('commonFields.purchaseAmount'), default: false },
    { key: 'available_for_use_date', label: t('commonFields.availableForUseDate'), default: false },
    { key: 'creation', label: t('commonFields.createdOn'), default: false },
    { key: 'modified', label: t('commonFields.modifiedOn'), default: true },
    { key: 'owner', label: t('commonFields.createdBy'), default: false },
    { key: 'modified_by', label: t('commonFields.modifiedBy'), default: false },
  ];

  // ✅ Track initial load to prevent full-page refresh on filter changes
  const [initialLoadComplete, setInitialLoadComplete] = useState(false);

  // ✅ Row selection state
  const [selectedRows, setSelectedRows] = useState<Set<string>>(new Set());

  // ✅ Export modal state
  const [showExportModal, setShowExportModal] = useState(false);
  const [isExporting, setIsExporting] = useState(false);

  // ✅ Get user permissions for Asset doctype
  const { 
    // isAdmin, 
    permissionFilters, 
    // restrictions, 
    loading: permissionsLoading, 
    error: permissionsError,
    // hasRestriction,
    // getAllowedValues,
    hasAnyRestrictions
  } = useUserPermissions('Asset');

  // ✅ Role-based access control for Add Asset button
  const [canAddAsset, setCanAddAsset] = useState(false);
  const ALLOWED_ROLES_FOR_ADD = ['Maintenance Manager', 'Maintenance User', 'System Manager'];

  useEffect(() => {
    const checkUserRoles = async () => {
      try {
        console.log('🔍 [Role Check] Starting role check...');
        
        // Use custom whitelisted API
        const response = await fetch('/api/method/asset_lite.api.user_roles.check_has_role', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          credentials: 'include',
          body: JSON.stringify({
            roles: ALLOWED_ROLES_FOR_ADD.join(',')
          })
        });
        
        const data = await response.json();
        console.log('🔍 [Role Check] API Response:', data);
        
        if (data.message) {
          console.log('🔍 [Role Check] User roles:', data.message.user_roles);
          console.log('🔍 [Role Check] Matching roles:', data.message.matching_roles);
          console.log('✅ [Role Check] Has allowed role:', data.message.has_role);
          
          setCanAddAsset(data.message.has_role);
        } else {
          console.error('❌ [Role Check] Invalid response:', data);
          setCanAddAsset(false);
        }
      } catch (error) {
        console.error('❌ [Role Check] Error:', error);
        setCanAddAsset(false);
      }
    };

    checkUserRoles();
  }, []);

  // Filter states
  const { filterHospital, filtersLocked: hospitalLocked, handleHospitalChange, hospitalLinkFilters } = useUserHospitalFilter();
  const { userPhccSiteName, siteLocked } = useUserPhccSiteFilter();
  const [filterAssetId, setFilterAssetId] = useState('');
  const [filterCompany, setFilterCompany] = useState(() => searchParams.get('company') || '');
  const [filterSite, setFilterSite] = useState(() => searchParams.get('site_name') || searchParams.get('custom_site') || '');
  const [filterManufacturer, setFilterManufacturer] = useState('');
  const [filterSupplier, setFilterSupplier] = useState('');
  const [filterLocation, setFilterLocation] = useState('');
  const [filterDepartment, setFilterDepartment] = useState('');
  const [filterModality, setFilterModality] = useState('');
  const [filterDeviceStatus, setFilterDeviceStatus] = useState(() => searchParams.get('device_status') || '');
  const [filterAssetName, setFilterAssetName] = useState('');
  const [filterSerialNumber, setFilterSerialNumber] = useState('');

  // Advanced filter UI states
  const [isFilterExpanded, setIsFilterExpanded] = useState(false);
  const [activeFilterCount, setActiveFilterCount] = useState(0);
  const [savedFilters, setSavedFilters] = useState<any[]>([]);
  const [showSaveFilterModal, setShowSaveFilterModal] = useState(false);
  const [filterPresetName, setFilterPresetName] = useState('');

  // Temporary states for text inputs
  const [tempAssetName, setTempAssetName] = useState('');
  const [tempSerialNumber, setTempSerialNumber] = useState('');

  // Debounce timer refs
  const assetNameDebounceRef = useRef<number | null>(null);
  const serialNumberDebounceRef = useRef<number | null>(null);

  const mobileTeamSiteFilters = useMemo(
    () => buildMobileTeamSiteFilters(filterCompany, userPhccSiteName),
    [filterCompany, userPhccSiteName]
  );

  // Auto-apply user's hospital when set on profile
  useEffect(() => {
    if (hospitalLocked && filterHospital) {
      setFilterCompany(filterHospital);
    }
  }, [hospitalLocked, filterHospital]);

  // Auto-apply user's PHCC site when set on profile
  useEffect(() => {
    if (siteLocked && userPhccSiteName) {
      setFilterSite(userPhccSiteName);
    }
  }, [siteLocked, userPhccSiteName]);

  // Sync filters to URL when user changes a filter (skip first mount)
  useEffect(() => {
    if (!filtersChangedOnce.current) {
      filtersChangedOnce.current = true;
      return;
    }
    setSearchParams((prev) => {
      const next = new URLSearchParams(prev);
      if (filterCompany) next.set('company', filterCompany); else next.delete('company');
      if (filterSite) next.set('site_name', filterSite); else next.delete('site_name');
      next.delete('custom_site');
      if (filterDeviceStatus) next.set('device_status', filterDeviceStatus); else next.delete('device_status');
      next.set('page', '1');
      return next;
    });
  }, [filterCompany, filterSite, filterDeviceStatus, setSearchParams]);

  // Load saved filters from localStorage on mount
  useEffect(() => {
    const saved = localStorage.getItem('assetFilterPresets');
    if (saved) {
      setSavedFilters(JSON.parse(saved));
    }
  }, []);

  // Update active filter count
  useEffect(() => {
    const count = [
      filterAssetId,
      filterCompany,
      filterSite,
      filterLocation,
      filterDepartment,
      filterModality,
      filterManufacturer,
      filterSupplier,
      filterDeviceStatus,
      filterAssetName,
      filterSerialNumber,
      searchTerm
    ].filter(Boolean).length;
    setActiveFilterCount(count);
  }, [
    filterAssetId,
    filterCompany,
    filterSite,
    filterLocation,
    filterDepartment,
    filterModality,
    filterManufacturer,
    filterSupplier,
    filterDeviceStatus,
    filterAssetName,
    filterSerialNumber,
    searchTerm
  ]);

  // Build filters object (match reference: buildDateRangeFilters + Frappe operators)
  const filters: Record<string, any> = {};
  if (filterAssetId) filters.name = filterAssetId;
  if (filterCompany) filters.company = filterCompany;
  if (filterSite) filters.custom_site = filterSite;
  if (filterManufacturer) filters.custom_manufacturer = filterManufacturer;
  if (filterSupplier) filters.supplier = filterSupplier;
  if (filterLocation) filters.location = filterLocation;
  if (filterDepartment) filters.department = filterDepartment;
  if (filterModality) filters.custom_modality = filterModality;
  if (filterDeviceStatus) filters.custom_device_status = filterDeviceStatus;
  if (filterAssetName) filters.asset_name = ['like', `%${filterAssetName}%`];
  if (filterSerialNumber) filters.custom_serial_number = ['like', `%${filterSerialNumber}%`];
  if (searchTerm) filters.asset_name = ['like', `%${searchTerm}%`];
  Object.assign(filters, buildDateRangeFilters(dateFilterBy, dateStart, dateEnd));

  const { assets, totalCount, hasMore, loading, error, refetch } = useAssets(
    filters,
    limit,
    page * limit,
    sortBy,
    permissionFilters
  );

  const { deleteAsset, loading: mutationLoading } = useAssetMutations();

  // ✅ Mark initial load complete
  useEffect(() => {
    if (!loading && !initialLoadComplete && !permissionsLoading) {
      setInitialLoadComplete(true);
    }
  }, [loading, initialLoadComplete, permissionsLoading]);

  // Reset page when filters change (exclude resetPage from deps — it changes on every URL update and breaks pagination)
  useEffect(() => {
    resetPage();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [filterAssetId, filterCompany, filterSite, filterManufacturer, filterSupplier, filterLocation, filterDepartment, filterModality,
     filterDeviceStatus, filterAssetName, filterSerialNumber, searchTerm, sortBy, dateFilterBy, dateStart, dateEnd]);

  // ✅ Clear selection when filters/page change
  useEffect(() => {
    setSelectedRows(new Set());
  }, [filterAssetId, filterCompany, filterSite, filterManufacturer, filterSupplier, filterLocation, filterDepartment, filterModality,
     filterDeviceStatus, filterAssetName, filterSerialNumber, searchTerm, page]);

  // Debounce functions
  const handleAssetNameChange = (value: string) => {
    setTempAssetName(value);
    if (assetNameDebounceRef.current) clearTimeout(assetNameDebounceRef.current);
    assetNameDebounceRef.current = window.setTimeout(() => {
      setFilterAssetName(value);
    }, 800);
  };

  const handleSerialNumberChange = (value: string) => {
    setTempSerialNumber(value);
    if (serialNumberDebounceRef.current) clearTimeout(serialNumberDebounceRef.current);
    serialNumberDebounceRef.current = window.setTimeout(() => {
      setFilterSerialNumber(value);
    }, 800);
  };

  // ✅ Handle Enter key press - with preventDefault to avoid page refresh
  const handleKeyPress = (e: React.KeyboardEvent<HTMLInputElement>, type: 'assetName' | 'serialNumber') => {
    if (e.key === 'Enter') {
      e.preventDefault(); // ← Prevents page refresh
      if (type === 'assetName') {
        if (assetNameDebounceRef.current) clearTimeout(assetNameDebounceRef.current);
        setFilterAssetName(tempAssetName);
      } else if (type === 'serialNumber') {
        if (serialNumberDebounceRef.current) clearTimeout(serialNumberDebounceRef.current);
        setFilterSerialNumber(tempSerialNumber);
      }
    }
  };

  // Save filter preset
  const handleSaveFilterPreset = () => {
    if (!filterPresetName.trim()) {
      alert('Please enter a filter name');
      return;
    }
    
    const preset = {
      id: Date.now(),
      name: filterPresetName,
      filters: {
        filterAssetId,
        filterCompany,
        filterSite,
        filterLocation,
        filterDepartment,
        filterModality,
        filterManufacturer,
        filterSupplier,
        filterDeviceStatus,
        filterAssetName,
        filterSerialNumber,
        searchTerm
      }
    };
    
    const updated = [...savedFilters, preset];
    setSavedFilters(updated);
    setFilterPresetName('');
    setShowSaveFilterModal(false);
    localStorage.setItem('assetFilterPresets', JSON.stringify(updated));
  };

  // Load filter preset
  const handleLoadFilterPreset = (preset: any) => {
    const f = preset.filters;
    setFilterAssetId(f.filterAssetId || '');
    setFilterCompany(f.filterCompany || '');
    setFilterSite(f.filterSite || '');
    setFilterLocation(f.filterLocation || '');
    setFilterDepartment(f.filterDepartment || '');
    setFilterModality(f.filterModality || '');
    setFilterManufacturer(f.filterManufacturer || '');
    setFilterSupplier(f.filterSupplier || '');
    setFilterDeviceStatus(f.filterDeviceStatus || '');
    setFilterAssetName(f.filterAssetName || '');
    setTempAssetName(f.filterAssetName || '');
    setFilterSerialNumber(f.filterSerialNumber || '');
    setTempSerialNumber(f.filterSerialNumber || '');
    setSearchTerm(f.searchTerm || '');
  };

  // Delete filter preset
  const handleDeleteFilterPreset = (id: number) => {
    const updated = savedFilters.filter(f => f.id !== id);
    setSavedFilters(updated);
    localStorage.setItem('assetFilterPresets', JSON.stringify(updated));
  };

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

  const formatDate = (dateString?: string) => {
    if (!dateString) return '-';
    const date = new Date(dateString);
    return date.toLocaleString('en-US', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  // Close dropdown when clicking outside
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setActionMenuOpen(null);
      }
    };

    if (actionMenuOpen) {
      document.addEventListener('mousedown', handleClickOutside);
    }

    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [actionMenuOpen]);

  // ✅ Row selection handlers
  const handleSelectRow = (assetName: string) => {
    setSelectedRows(prev => {
      const newSet = new Set(prev);
      if (newSet.has(assetName)) {
        newSet.delete(assetName);
      } else {
        newSet.add(assetName);
      }
      return newSet;
    });
  };

  const handleSelectAll = () => {
    if (selectedRows.size === assets.length) {
      setSelectedRows(new Set());
    } else {
      setSelectedRows(new Set(assets.map(a => a.name)));
    }
  };

  const isAllSelected = assets.length > 0 && selectedRows.size === assets.length;
  const isSomeSelected = selectedRows.size > 0 && selectedRows.size < assets.length;

  // ✅ Fetch all assets for export (bypassing pagination)
  const fetchAllAssetsForExport = useCallback(async (): Promise<any[]> => {
    // This function should call your API to get ALL assets with current filters
    // You'll need to adjust this based on your actual API implementation
    
    // Option 1: If your useAssets hook or API supports fetching all at once
    // return await fetchAssetsAPI(filters, 0, 0, 'creation desc', permissionFilters); // limit=0 might mean all
    
    // Option 2: Paginate through all results
    const allAssets: any[] = [];
    let currentPage = 0;
    const pageSize = 100; // Fetch in larger batches for efficiency
    let hasMoreData = true;

    while (hasMoreData) {
      try {
        // You'll need to implement this API call based on your backend
        const response = await fetch('/api/method/frappe.client.get_list', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            doctype: 'Asset',
            filters: { ...filters, ...permissionFilters },
            fields: ['*'],
            limit_start: currentPage * pageSize,
            limit_page_length: pageSize,
            order_by: 'creation desc'
          })
        });

        const data = await response.json();
        const results = data.message || [];
        
        allAssets.push(...results);
        
        if (results.length < pageSize) {
          hasMoreData = false;
        } else {
          currentPage++;
        }

        // Safety limit to prevent infinite loops
        if (currentPage > 100) {
          console.warn('Export safety limit reached');
          hasMoreData = false;
        }
      } catch (error) {
        console.error('Error fetching assets for export:', error);
        throw error;
      }
    }

    return allAssets;
  }, [filters, permissionFilters]);

  // ✅ Export handler
  const handleExport = async (scope: ExportScope, format: ExportFormat, columns: string[]) => {
    setIsExporting(true);

    try {
      let dataToExport: any[] = [];

      switch (scope) {
        case 'selected':
          dataToExport = assets.filter(a => selectedRows.has(a.name));
          break;
        case 'all_on_page':
          dataToExport = assets;
          break;
        case 'all_with_filters':
          dataToExport = await fetchAllAssetsForExport();
          break;
      }

      if (dataToExport.length === 0) {
        alert('No data to export');
        return;
      }

      // Get column labels for headers
      const columnLabels = columns.map(key => {
        const col = EXPORT_COLUMNS.find(c => c.key === key);
        return col?.label || key;
      });

      if (format === 'csv') {
        // Generate CSV
        const csvContent = [
          columnLabels.join(','),
          ...dataToExport.map(asset => 
            columns.map(key => {
              let value = asset[key] || '';
              // Escape commas and quotes in CSV
              if (typeof value === 'string' && (value.includes(',') || value.includes('"') || value.includes('\n'))) {
                value = `"${value.replace(/"/g, '""')}"`;
              }
              return value;
            }).join(',')
          )
        ].join('\n');

        const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8;' });
        const url = URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = `assets_export_${new Date().toISOString().split('T')[0]}.csv`;
        link.click();
        URL.revokeObjectURL(url);

      } else if (format === 'excel') {
        // Create a proper Excel workbook using SheetJS
        const worksheetData = [
          columnLabels, // Header row
          ...dataToExport.map(asset =>
            columns.map(key => asset[key] || '')
          )
        ];

        const worksheet = XLSX.utils.aoa_to_sheet(worksheetData);
        const workbook = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(workbook, worksheet, 'Assets');

        // Generate and download the file
        XLSX.writeFile(workbook, `assets_export_${new Date().toISOString().split('T')[0]}.xlsx`);
      }

      setShowExportModal(false);
      setSelectedRows(new Set()); // Clear selection after export
      
    } catch (error) {
      console.error('Export failed:', error);
      alert(`Export failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
    } finally {
      setIsExporting(false);
    }
  };

  const handleCreateNew = () => navigate('/assets/new');
  const handleView = (assetName: string) => navigate(`/assets/${assetName}`);
  const handleEdit = (assetName: string) => navigate(`/assets/${assetName}`);
  const handleDuplicate = (assetName: string) => navigate(`/assets/new?duplicate=${assetName}`);

  // ✅ Create Work Order from Asset - passes asset data as query params
  const handleCreateWorkOrder = (asset: any) => {
    const params = new URLSearchParams();
    
    // Pass asset data to work order form
    if (asset.name) params.append('asset', asset.name);
    if (asset.asset_name) params.append('asset_name', asset.asset_name);
    if (asset.custom_asset_type) params.append('asset_type', asset.custom_asset_type);
    if (asset.custom_manufacturer) params.append('manufacturer', asset.custom_manufacturer);
    if (asset.custom_serial_number) params.append('serial_number', asset.custom_serial_number);
    if (asset.custom_local_id) params.append('local_id', asset.custom_local_id);
    if (asset.custom_moh_id) params.append('moh_id', asset.custom_moh_id);
    if (asset.department) params.append('department', asset.department);
    if (asset.custom_site_contractor) params.append('site_contractor', asset.custom_site_contractor);
    if (asset.custom_subcontractor) params.append('subcontractor', asset.custom_subcontractor);
    if (asset.company) params.append('company', asset.company);
    if (asset.custom_service_agreement) params.append('custom_service_agreement', asset.custom_service_agreement);
    if (asset.custom_service_coverage) params.append('custom_service_coverage', asset.custom_service_coverage);
    if (asset.custom_site) params.append('site_name', asset.custom_site);
    if (asset.custom_smeh_engg) params.append('smeh_engg', asset.custom_smeh_engg);
    
    navigate(`/work-orders/new?${params.toString()}`);
  };

  // ✅ View Linked Work Orders - navigates to WO list with asset filter
  const handleViewLinkedWOs = (assetId: string) => {
    navigate(`/work-orders?asset=${encodeURIComponent(assetId)}`);
  };

  const handleDelete = async (assetName: string) => {
    try {
      await deleteAsset(assetName);
      setDeleteConfirmOpen(null);
      refetch();
      alert('Asset deleted successfully!');
    } catch (err) {
      alert(`Failed to delete asset: ${err instanceof Error ? err.message : 'Unknown error'}`);
    }
  };

  const handleExportSingle = (asset: any) => {
    const dataStr = JSON.stringify(asset, null, 2);
    const dataBlob = new Blob([dataStr], { type: 'application/json' });
    const url = URL.createObjectURL(dataBlob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `asset_${asset.name}.json`;
    link.click();
    URL.revokeObjectURL(url);
  };

  const handlePrint = (assetName: string) => {
    window.open(`/assets/${assetName}?print=true`, '_blank');
  };

  const handleClearFilters = () => {
    setFilterAssetId('');
    if (!hospitalLocked) {
      setFilterCompany('');
    }
    if (!siteLocked) {
      setFilterSite('');
    }
    setFilterManufacturer('');
    setFilterSupplier('');
    setFilterLocation('');
    setFilterDepartment('');
    setFilterModality('');
    setFilterDeviceStatus('');
    setFilterAssetName('');
    setFilterSerialNumber('');
    setTempAssetName('');
    setTempSerialNumber('');
    setSearchTerm('');

    if (assetNameDebounceRef.current) clearTimeout(assetNameDebounceRef.current);
    if (serialNumberDebounceRef.current) clearTimeout(serialNumberDebounceRef.current);
  };

  const hasActiveFilters = filterAssetId || filterCompany || filterSite || filterManufacturer || filterSupplier || 
                          filterLocation || filterDepartment || filterModality || filterDeviceStatus || 
                          filterAssetName || filterSerialNumber || searchTerm;

  // ✅ Loading state for permissions - only on initial load
  if (permissionsLoading && !initialLoadComplete) {
    return (
      <div className="flex items-center justify-center h-screen bg-gray-50 dark:bg-gray-900">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500 mx-auto"></div>
          <p className="mt-4 text-gray-600 dark:text-gray-400">Loading permissions...</p>
        </div>
      </div>
    );
  }

  // ✅ Error state for permissions
  if (permissionsError) {
    return (
      <div className="p-4 sm:p-6 bg-gray-50 dark:bg-gray-900 min-h-screen min-w-0 overflow-x-hidden">
        <div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-6">
          <h2 className="text-xl font-bold text-red-800 dark:text-red-300 mb-4">⚠️ Permission Error</h2>
          <div className="text-red-700 dark:text-red-400 space-y-3">
            <p><strong>Unable to load user permissions.</strong></p>
            <p>{permissionsError}</p>
            <button 
              onClick={() => window.location.reload()}
              className="mt-2 bg-red-600 hover:bg-red-700 text-white px-4 py-2 rounded"
            >
              Retry
            </button>
          </div>
        </div>
      </div>
    );
  }

  // ✅ Only show full-page loader on initial load
  if (loading && !initialLoadComplete) {
    return (
      <div className="flex items-center justify-center h-screen bg-gray-50 dark:bg-gray-900">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500 mx-auto"></div>
          <p className="mt-4 text-gray-600 dark:text-gray-400">{t('listPages.loading')}</p>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="p-4 sm:p-6 bg-gray-50 dark:bg-gray-900 min-h-screen min-w-0 overflow-x-hidden">
        <div className="bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg p-6">
          <h2 className="text-xl font-bold text-yellow-800 dark:text-yellow-300 mb-4">⚠️ Asset API Not Available</h2>
          <div className="text-yellow-700 dark:text-yellow-400 space-y-3">
            <p><strong>The Asset API endpoint is not deployed yet.</strong></p>
            <button 
              onClick={() => navigate('/assets/new')}
              className="mt-2 bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded"
            >
              Try Creating a New Asset (Demo)
            </button>
            <button 
              onClick={refetch}
              className="mt-2 ml-2 bg-gray-600 hover:bg-gray-700 text-white px-4 py-2 rounded"
            >
              Try Again
            </button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="p-4 sm:p-6 bg-gray-50 dark:bg-gray-900 min-h-screen min-w-0 overflow-x-hidden">
      {/* Header */}
      <div className="mb-6 flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between lg:items-center">
        <div>
          <h1 className="text-2xl sm:text-3xl font-bold text-gray-800 dark:text-white break-words">{t('assets.title')}</h1>
          <p className="text-gray-600 dark:text-gray-400 mt-1">
            Total: {totalCount} asset{totalCount !== 1 ? 's' : ''}
            {/* ✅ Show selection count */}
            {selectedRows.size > 0 && (
              <span className="ml-2 text-blue-600 dark:text-blue-400">
                • {selectedRows.size} selected
              </span>
            )}
            {/* ✅ Show loading indicator inline when filtering */}
            {loading && initialLoadComplete && (
              <span className="ml-2 inline-flex items-center gap-1 text-xs text-blue-600 dark:text-blue-400">
                <div className="animate-spin rounded-full h-3 w-3 border-b-2 border-blue-500"></div>
                Updating...
              </span>
            )}
          </p>
        </div>
        <div className="flex gap-3">
          <ScanQRButton label="Scan QR" title="Scan Asset QR" />
          {/* ✅ Updated Export Button */}
          <button
            onClick={() => setShowExportModal(true)}
            className="bg-green-600 hover:bg-green-700 text-white px-4 py-2 rounded-lg flex items-center gap-2 shadow transition-all"
            disabled={totalCount === 0}
          >
            <FaFileExport />
            <span className="font-medium">{t('listPages.export')}</span>
            {selectedRows.size > 0 && (
              <span className="bg-white/20 px-1.5 py-0.5 rounded text-xs">
                {selectedRows.size}
              </span>
            )}
          </button>
          {/* ✅ Conditionally render Add Asset button based on user roles */}
          {/* console.log('🎯 [Button] canAddAsset state:', canAddAsset) */}
          {canAddAsset && (
            <button
              onClick={handleCreateNew}
              className="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg flex items-center gap-2 shadow-lg transition-all hover:shadow-xl"
            >
              <FaPlus />
              <span className="font-medium">{t('assets.addAsset')}</span>
            </button>
          )}
        </div>
      </div>

      {/* Advanced Filter Panel */}
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow-lg border border-gray-200 dark:border-gray-700 mb-4">
        {/* Filter Header */}
        <div className="bg-gradient-to-r from-blue-500 to-blue-600 dark:from-blue-600 dark:to-blue-700 px-4 py-3 rounded-t-lg">
          <div className="flex items-center justify-between gap-4">
            {/* Left Side - Toggle & Title */}
            <div className="flex items-center gap-3 flex-shrink-0">
              <button
                onClick={() => setIsFilterExpanded(!isFilterExpanded)}
                className="text-white hover:bg-white/20 p-2 rounded-lg transition-all"
              >
                {isFilterExpanded ? <FaChevronUp size={14} /> : <FaChevronDown size={14} />}
              </button>
              
              <div className="flex items-center gap-2">
                <FaFilter className="text-white" size={16} />
                <h3 className="text-white font-semibold text-sm">{t('listPages.filters')}</h3>
              </div>
              
              {activeFilterCount > 0 && (
                <span className="bg-white text-blue-600 px-2 py-0.5 rounded-full text-xs font-bold">
                  {activeFilterCount}
                </span>
              )}
            </div>

            {/* Center - Active Filter Tags (scrollable) */}
            {hasActiveFilters && (
              <div className="flex-1 overflow-x-auto scrollbar-hide mx-2">
                <div className="flex items-center gap-2 py-1">
                  {filterAssetId && (
                    <span className="inline-flex items-center gap-1.5 px-2.5 py-1 bg-white/90 text-blue-700 rounded-full text-[10px] font-medium whitespace-nowrap shadow-sm">
                      <span className="font-semibold">Asset ID:</span> {filterAssetId}
                      <button 
                        onClick={(e) => { e.stopPropagation(); setFilterAssetId(''); }} 
                        className="hover:text-red-500 transition-colors"
                      >
                        <FaTimes className="text-[9px]" />
                      </button>
                    </span>
                  )}
                  {filterCompany && (
                    <span className="inline-flex items-center gap-1.5 px-2.5 py-1 bg-white/90 text-green-700 rounded-full text-[10px] font-medium whitespace-nowrap shadow-sm">
                      <span className="font-semibold">Hospital:</span> {filterCompany}
                      <button 
                        onClick={(e) => { e.stopPropagation(); setFilterCompany(''); }} 
                        className="hover:text-red-500 transition-colors"
                      >
                        <FaTimes className="text-[9px]" />
                      </button>
                    </span>
                  )}
                  {filterSite && (
                    <span className="inline-flex items-center gap-1.5 px-2.5 py-1 bg-white/90 text-emerald-700 rounded-full text-[10px] font-medium whitespace-nowrap shadow-sm">
                      <span className="font-semibold">Site:</span> {filterSite}
                      {!siteLocked && (
                        <button 
                          onClick={(e) => { e.stopPropagation(); setFilterSite(''); }} 
                          className="hover:text-red-500 transition-colors"
                        >
                          <FaTimes className="text-[9px]" />
                        </button>
                      )}
                    </span>
                  )}
                  {filterAssetName && (
                    <span className="inline-flex items-center gap-1.5 px-2.5 py-1 bg-white/90 text-cyan-700 rounded-full text-[10px] font-medium whitespace-nowrap shadow-sm">
                      <span className="font-semibold">Name:</span> {filterAssetName}
                      <button 
                        onClick={(e) => { e.stopPropagation(); setFilterAssetName(''); setTempAssetName(''); }} 
                        className="hover:text-red-500 transition-colors"
                      >
                        <FaTimes className="text-[9px]" />
                      </button>
                    </span>
                  )}
                  {filterSerialNumber && (
                    <span className="inline-flex items-center gap-1.5 px-2.5 py-1 bg-white/90 text-lime-700 rounded-full text-[10px] font-medium whitespace-nowrap shadow-sm">
                      <span className="font-semibold">Serial:</span> {filterSerialNumber}
                      <button 
                        onClick={(e) => { e.stopPropagation(); setFilterSerialNumber(''); setTempSerialNumber(''); }} 
                        className="hover:text-red-500 transition-colors"
                      >
                        <FaTimes className="text-[9px]" />
                      </button>
                    </span>
                  )}
                  {filterDeviceStatus && (
                    <span className="inline-flex items-center gap-1.5 px-2.5 py-1 bg-white/90 text-orange-700 rounded-full text-[10px] font-medium whitespace-nowrap shadow-sm">
                      <span className="font-semibold">Status:</span> {filterDeviceStatus}
                      <button 
                        onClick={(e) => { e.stopPropagation(); setFilterDeviceStatus(''); }} 
                        className="hover:text-red-500 transition-colors"
                      >
                        <FaTimes className="text-[9px]" />
                      </button>
                    </span>
                  )}
                  {filterLocation && (
                    <span className="inline-flex items-center gap-1.5 px-2.5 py-1 bg-white/90 text-purple-700 rounded-full text-[10px] font-medium whitespace-nowrap shadow-sm">
                      <span className="font-semibold">Location:</span> {filterLocation}
                      <button 
                        onClick={(e) => { e.stopPropagation(); setFilterLocation(''); }} 
                        className="hover:text-red-500 transition-colors"
                      >
                        <FaTimes className="text-[9px]" />
                      </button>
                    </span>
                  )}
                  {filterDepartment && (
                    <span className="inline-flex items-center gap-1.5 px-2.5 py-1 bg-white/90 text-yellow-700 rounded-full text-[10px] font-medium whitespace-nowrap shadow-sm">
                      <span className="font-semibold">Dept:</span> {filterDepartment}
                      <button 
                        onClick={(e) => { e.stopPropagation(); setFilterDepartment(''); }} 
                        className="hover:text-red-500 transition-colors"
                      >
                        <FaTimes className="text-[9px]" />
                      </button>
                    </span>
                  )}
                  {filterModality && (
                    <span className="inline-flex items-center gap-1.5 px-2.5 py-1 bg-white/90 text-pink-700 rounded-full text-[10px] font-medium whitespace-nowrap shadow-sm">
                      <span className="font-semibold">Modality:</span> {filterModality}
                      <button 
                        onClick={(e) => { e.stopPropagation(); setFilterModality(''); }} 
                        className="hover:text-red-500 transition-colors"
                      >
                        <FaTimes className="text-[9px]" />
                      </button>
                    </span>
                  )}
                  {filterManufacturer && (
                    <span className="inline-flex items-center gap-1.5 px-2.5 py-1 bg-white/90 text-indigo-700 rounded-full text-[10px] font-medium whitespace-nowrap shadow-sm">
                      <span className="font-semibold">Mfr:</span> {filterManufacturer}
                      <button 
                        onClick={(e) => { e.stopPropagation(); setFilterManufacturer(''); }} 
                        className="hover:text-red-500 transition-colors"
                      >
                        <FaTimes className="text-[9px]" />
                      </button>
                    </span>
                  )}
                  {filterSupplier && (
                    <span className="inline-flex items-center gap-1.5 px-2.5 py-1 bg-white/90 text-teal-700 rounded-full text-[10px] font-medium whitespace-nowrap shadow-sm">
                      <span className="font-semibold">Supplier:</span> {filterSupplier}
                      <button 
                        onClick={(e) => { e.stopPropagation(); setFilterSupplier(''); }} 
                        className="hover:text-red-500 transition-colors"
                      >
                        <FaTimes className="text-[9px]" />
                      </button>
                    </span>
                  )}
                </div>
              </div>
            )}

            {/* Right Side - Action Buttons */}
            <div className="flex items-center gap-2 flex-shrink-0">
              {/* Save Filter Button */}
              {activeFilterCount > 0 && (
                <button
                  onClick={() => setShowSaveFilterModal(true)}
                  className="px-3 py-1.5 bg-white text-blue-600 hover:bg-blue-50 rounded-md text-xs font-medium transition-all flex items-center gap-1.5"
                >
                  <FaSave size={12} />
                  <span className="hidden sm:inline">Save</span>
                </button>
              )}

              {/* Clear All Button */}
              {hasActiveFilters && (
                <button
                  onClick={handleClearFilters}
                  className="px-3 py-1.5 bg-red-500 hover:bg-red-600 text-white rounded-md text-xs font-medium transition-all flex items-center gap-1.5"
                >
                  <FaTimes size={12} />
                  <span className="hidden sm:inline">Clear</span>
                </button>
              )}
            </div>
          </div>
        </div>

        {/* Expandable Filter Content */}
        {isFilterExpanded && (
          <div className="p-4">
            {/* Saved Filter Presets */}
            {savedFilters.length > 0 && (
              <div className="mb-4 pb-4 border-b border-gray-200 dark:border-gray-700">
                <h4 className="text-xs font-semibold text-gray-700 dark:text-gray-300 mb-2 flex items-center gap-2">
                  <FaStar className="text-yellow-500" size={12} />
                  Saved Filters
                </h4>
                <div className="flex flex-wrap gap-2">
                  {savedFilters.map((preset) => (
                    <div
                      key={preset.id}
                      className="group relative inline-flex items-center gap-2 px-3 py-1.5 bg-gradient-to-r from-purple-100 to-blue-100 dark:from-purple-900/30 dark:to-blue-900/30 border border-purple-200 dark:border-purple-700 rounded-lg hover:shadow-md transition-all"
                    >
                      <button
                        onClick={() => handleLoadFilterPreset(preset)}
                        className="text-xs font-medium text-purple-700 dark:text-purple-300"
                      >
                        {preset.name}
                      </button>
                      <button
                        onClick={() => handleDeleteFilterPreset(preset.id)}
                        className="opacity-0 group-hover:opacity-100 text-red-500 hover:text-red-700 transition-opacity"
                      >
                        <FaTrash size={10} />
                      </button>
                    </div>
                  ))}
                </div>
              </div>
            )}

            {/* Filter Grid */}
            <div className="space-y-5">
              <div className="bg-gray-50 dark:bg-gray-900/50 p-3 rounded-lg">
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-3">
                  <ListFilterSortControls
                    sortBy={sortBy}
                    dateFilterBy={dateFilterBy}
                    dateStart={dateStart}
                    dateEnd={dateEnd}
                    onSortByChange={setSortBy}
                    onDateFilterByChange={setDateFilterBy}
                    onDateStartChange={setDateStart}
                    onDateEndChange={setDateEnd}
                    includeAssetNameSort
                  />
                  {/* Asset ID */}
                  <div className="relative z-[60]">
                    <LinkField
                      label="Asset ID"
                      doctype="Asset"
                      value={filterAssetId}
                      onChange={(val) => setFilterAssetId(val)}
                      placeholder="Select Asset ID"
                      disabled={false}
                      compact={true}
                    />
                    {filterAssetId && (
                      <button
                        onClick={() => setFilterAssetId('')}
                        className="absolute right-2 top-6 text-gray-400 hover:text-red-500 transition-colors z-10"
                      >
                        <FaTimes size={10} />
                      </button>
                    )}
                  </div>

                  {/* Asset Name */}
                  <div className="relative">
                    <label className="block text-[10px] font-medium text-gray-700 dark:text-gray-300 mb-0.5">
                      Asset Name
                    </label>
                    <input
                      type="text"
                      value={tempAssetName}
                      onChange={(e) => handleAssetNameChange(e.target.value)}
                      onKeyDown={(e) => handleKeyPress(e, 'assetName')}
                      placeholder="Type to search..."
                      className="w-full px-2 py-1 text-xs border border-gray-300 dark:border-gray-600 rounded focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                    />
                    {tempAssetName && tempAssetName !== filterAssetName && (
                      <span className="absolute right-2 top-6 text-[9px] text-blue-500 animate-pulse">
                        typing...
                      </span>
                    )}
                    {filterAssetName && (
                      <button
                        onClick={() => {
                          setFilterAssetName('');
                          setTempAssetName('');
                        }}
                        className="absolute right-2 top-6 text-gray-400 hover:text-red-500 transition-colors"
                      >
                        <FaTimes size={10} />
                      </button>
                    )}
                  </div>

                  {/* Serial Number */}
                  <div className="relative">
                    <label className="block text-[10px] font-medium text-gray-700 dark:text-gray-300 mb-0.5">
                      Serial Number
                    </label>
                    <input
                      type="text"
                      value={tempSerialNumber}
                      onChange={(e) => handleSerialNumberChange(e.target.value)}
                      onKeyDown={(e) => handleKeyPress(e, 'serialNumber')}
                      placeholder="Type to search..."
                      className="w-full px-2 py-1 text-xs border border-gray-300 dark:border-gray-600 rounded focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                    />
                    {tempSerialNumber && tempSerialNumber !== filterSerialNumber && (
                      <span className="absolute right-2 top-6 text-[9px] text-blue-500 animate-pulse">
                        typing...
                      </span>
                    )}
                    {filterSerialNumber && (
                      <button
                        onClick={() => {
                          setFilterSerialNumber('');
                          setTempSerialNumber('');
                        }}
                        className="absolute right-2 top-6 text-gray-400 hover:text-red-500 transition-colors"
                      >
                        <FaTimes size={10} />
                      </button>
                    )}
                  </div>

                  {/* Hospital */}
                  <div className="relative z-[59]">
                    <LinkField
                      label="Hospital"
                      doctype="Company"
                      value={filterCompany}
                      onChange={(val) => {
                        handleHospitalChange(val);
                        setFilterCompany(val);
                      }}
                      placeholder="Select Hospital"
                      disabled={hospitalLocked}
                      compact={true}
                      filters={hospitalLinkFilters}
                    />
                    {filterCompany && !hospitalLocked && (
                      <button
                        onClick={() => {
                          handleHospitalChange('');
                          setFilterCompany('');
                        }}
                        className="absolute right-2 top-6 text-gray-400 hover:text-red-500 transition-colors z-10"
                      >
                        <FaTimes size={10} />
                      </button>
                    )}
                  </div>

                  {/* Site Name - NEW FILTER */}
                  <div className="relative z-[58]">
                    <LinkField
                      label="PHCC Site"
                      doctype="Mobile Team Site"
                      value={filterSite}
                      onChange={(val) => setFilterSite(val)}
                      placeholder="Select Site"
                      disabled={siteLocked}
                      filters={mobileTeamSiteFilters}
                      compact={true}
                    />
                    {filterSite && !siteLocked && (
                      <button
                        onClick={() => setFilterSite('')}
                        className="absolute right-2 top-6 text-gray-400 hover:text-red-500 transition-colors z-10"
                      >
                        <FaTimes size={10} />
                      </button>
                    )}
                  </div>

                  {/* Device Status */}
                  <div className="relative">
                    <label className="block text-[10px] font-medium text-gray-700 dark:text-gray-300 mb-0.5">
                      Device Status
                    </label>
                    <select
                      value={filterDeviceStatus}
                      onChange={(e) => setFilterDeviceStatus(e.target.value)}
                      className="w-full px-2 py-1 text-xs border border-gray-300 dark:border-gray-600 rounded focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                    >
                      <option value="">All Status</option>
                      <option value="Up">✓ Up</option>
                      <option value="Down">⚠ Down</option>
                    </select>
                    {filterDeviceStatus && (
                      <button
                        onClick={() => setFilterDeviceStatus('')}
                        className="absolute right-8 top-6 text-gray-400 hover:text-red-500 transition-colors"
                      >
                        <FaTimes size={10} />
                      </button>
                    )}
                  </div>

                  {/* Location */}
                  <div className="relative z-[57]">
                    <LinkField
                      label="Location"
                      doctype="Location"
                      value={filterLocation}
                      onChange={(val) => setFilterLocation(val)}
                      placeholder="Select Location"
                      disabled={false}
                      compact={true}
                    />
                    {filterLocation && (
                      <button
                        onClick={() => setFilterLocation('')}
                        className="absolute right-2 top-6 text-gray-400 hover:text-red-500 transition-colors z-10"
                      >
                        <FaTimes size={10} />
                      </button>
                    )}
                  </div>

                  {/* Department */}
                  <div className="relative z-[56]">
                    <LinkField
                      label="Department"
                      doctype="Department"
                      value={filterDepartment}
                      onChange={(val) => setFilterDepartment(val)}
                      placeholder="Select Department"
                      disabled={false}
                      compact={true}
                    />
                    {filterDepartment && (
                      <button
                        onClick={() => setFilterDepartment('')}
                        className="absolute right-2 top-6 text-gray-400 hover:text-red-500 transition-colors z-10"
                      >
                        <FaTimes size={10} />
                      </button>
                    )}
                  </div>

                  {/* Modality */}
                  <div className="relative z-[55]">
                    <LinkField
                      label="Modality"
                      doctype="Modality"
                      value={filterModality}
                      onChange={(val) => setFilterModality(val)}
                      placeholder="Select Modality"
                      disabled={false}
                      compact={true}
                    />
                    {filterModality && (
                      <button
                        onClick={() => setFilterModality('')}
                        className="absolute right-2 top-6 text-gray-400 hover:text-red-500 transition-colors z-10"
                      >
                        <FaTimes size={10} />
                      </button>
                    )}
                  </div>

                  {/* Manufacturer */}
                  <div className="relative z-[54]">
                    <LinkField
                      label="Manufacturer"
                      doctype="Manufacturer"
                      value={filterManufacturer}
                      onChange={(val) => setFilterManufacturer(val)}
                      placeholder="Select Manufacturer"
                      disabled={false}
                      compact={true}
                    />
                    {filterManufacturer && (
                      <button
                        onClick={() => setFilterManufacturer('')}
                        className="absolute right-2 top-6 text-gray-400 hover:text-red-500 transition-colors z-10"
                      >
                        <FaTimes size={10} />
                      </button>
                    )}
                  </div>

                  {/* Supplier */}
                  <div className="relative z-[53]">
                    <LinkField
                      label="Supplier"
                      doctype="Supplier"
                      value={filterSupplier}
                      onChange={(val) => setFilterSupplier(val)}
                      placeholder="Select Supplier"
                      disabled={false}
                      compact={true}
                    />
                    {filterSupplier && (
                      <button
                        onClick={() => setFilterSupplier('')}
                        className="absolute right-2 top-6 text-gray-400 hover:text-red-500 transition-colors z-10"
                      >
                        <FaTimes size={10} />
                      </button>
                    )}
                  </div>
                </div>
              </div>
            </div>
          </div>
        )}
      </div>

      {/* Save Filter Modal */}
      {showSaveFilterModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl max-w-md w-full p-6 animate-scale-in">
            <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
              Save Filter Preset
            </h3>
            <input
              type="text"
              value={filterPresetName}
              onChange={(e) => setFilterPresetName(e.target.value)}
              onKeyDown={(e) => {
                if (e.key === 'Enter') {
                  e.preventDefault();
                  handleSaveFilterPreset();
                }
              }}
              placeholder="Enter filter name (e.g., 'My Active Assets')"
              className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white mb-4"
              autoFocus
            />
            <div className="flex gap-2 justify-end">
              <button
                onClick={() => {
                  setShowSaveFilterModal(false);
                  setFilterPresetName('');
                }}
                className="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-md transition-colors"
              >
                Cancel
              </button>
              <button
                onClick={handleSaveFilterPreset}
                className="px-4 py-2 text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 rounded-md transition-colors flex items-center gap-2"
              >
                <FaSave size={12} />
                Save Filter
              </button>
            </div>
          </div>
        </div>
      )}

      {/* ✅ Export Modal */}
      <ExportModal
        isOpen={showExportModal}
        onClose={() => setShowExportModal(false)}
        selectedCount={selectedRows.size}
        totalCount={totalCount}
        pageCount={assets.length}
        onExport={handleExport}
        isExporting={isExporting}
        exportColumns={EXPORT_COLUMNS}
      />

      {/* Assets Table */}
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow overflow-hidden relative">
        {/* ✅ Inline loading overlay for filter changes */}
        {loading && initialLoadComplete && (
          <div className="absolute inset-0 bg-white/60 dark:bg-gray-800/60 flex items-center justify-center z-10 backdrop-blur-[1px]">
            <div className="flex items-center gap-3 bg-white dark:bg-gray-700 px-4 py-2 rounded-lg shadow-lg">
              <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-blue-500"></div>
              <span className="text-sm text-gray-600 dark:text-gray-300">Filtering...</span>
            </div>
          </div>
        )}
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="bg-gray-100 dark:bg-gray-700 border-b border-gray-200 dark:border-gray-600">
              <tr>
                {/* ✅ Select All Checkbox Column */}
                <th className="px-4 py-3 text-left">
                  <button
                    onClick={handleSelectAll}
                    className="text-gray-500 dark:text-gray-400 hover:text-blue-600 dark:hover:text-blue-400 transition-colors"
                    title={isAllSelected ? "Deselect all" : "Select all"}
                  >
                    {isAllSelected ? (
                      <FaCheckSquare className="text-blue-600 dark:text-blue-400" size={18} />
                    ) : isSomeSelected ? (
                      <div className="relative">
                        <FaSquare size={18} />
                        <div className="absolute inset-0 flex items-center justify-center">
                          <div className="w-2 h-0.5 bg-current"></div>
                        </div>
                      </div>
                    ) : (
                      <FaSquare size={18} />
                    )}
                  </button>
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                  Asset Name
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                  Serial No
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                  Company
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                  Location
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                  Status
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                  Updated on
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                  Actions
                </th>
              </tr>
            </thead>
            <tbody className="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
              {assets.length === 0 ? (
                <tr>
                  <td colSpan={8} className="px-6 py-12 text-center text-gray-500 dark:text-gray-400">
                    <div className="flex flex-col items-center">
                      <FaSearch className="text-4xl text-gray-300 dark:text-gray-600 mb-2" />
                      <p>No assets found</p>
                      {hasActiveFilters ? (
                        <button
                          onClick={handleClearFilters}
                          className="mt-4 text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300 underline"
                        >
                          Clear filters
                        </button>
                      ) : canAddAsset ? (
                        <button
                          onClick={handleCreateNew}
                          className="mt-4 text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300 underline"
                        >
                          Create your first asset
                        </button>
                      ) : null}
                    </div>
                  </td>
                </tr>
              ) : (
                assets.map((asset) => (
                  <tr 
                    key={asset.name} 
                    className={`hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors cursor-pointer ${
                      selectedRows.has(asset.name) ? 'bg-blue-50 dark:bg-blue-900/20' : ''
                    }`}
                    onClick={() => handleView(asset.name)}
                  >
                    {/* ✅ Row Checkbox */}
                    <td className="px-4 py-4" onClick={(e) => e.stopPropagation()}>
                      <button
                        onClick={() => handleSelectRow(asset.name)}
                        className="text-gray-500 dark:text-gray-400 hover:text-blue-600 dark:hover:text-blue-400 transition-colors"
                      >
                        {selectedRows.has(asset.name) ? (
                          <FaCheckSquare className="text-blue-600 dark:text-blue-400" size={18} />
                        ) : (
                          <FaSquare size={18} />
                        )}
                      </button>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <div className="font-medium text-gray-900 dark:text-white">{asset.asset_name}</div>
                      <div className="text-sm text-gray-500 dark:text-gray-400">{asset.name}</div>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-700 dark:text-gray-300">
                      {asset.custom_serial_number || '-'}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-700 dark:text-gray-300">
                      {asset.company || '-'}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-700 dark:text-gray-300">
                      {asset.location || '-'}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      {asset.custom_device_status || '-'}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-700 dark:text-gray-300">
                      {formatDate(asset.modified)}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
                      <div className="flex items-center gap-1" onClick={(e) => e.stopPropagation()}>
                        <button
                          onClick={() => handleView(asset.name)}
                          className="text-blue-600 dark:text-blue-400 hover:text-blue-900 dark:hover:text-blue-300 p-2 hover:bg-blue-50 dark:hover:bg-blue-900/30 rounded transition-colors"
                          title="View Details"
                        >
                          <FaEye />
                        </button>
                        <button
                          onClick={() => handleEdit(asset.name)}
                          className="text-green-600 dark:text-green-400 hover:text-green-900 dark:hover:text-green-300 p-2 hover:bg-green-50 dark:hover:bg-green-900/30 rounded transition-colors"
                          title="Edit Asset"
                        >
                          <FaEdit />
                        </button>
                        <button
                          onClick={() => handleDuplicate(asset.name)}
                          className="text-purple-600 dark:text-purple-400 hover:text-purple-900 dark:hover:text-purple-300 p-2 hover:bg-purple-50 dark:hover:bg-purple-900/30 rounded transition-colors"
                          title="Duplicate Asset"
                        >
                          <FaCopy />
                        </button>
                        <button
                          onClick={() => handleCreateWorkOrder(asset)}
                          className="text-orange-600 dark:text-orange-400 hover:text-orange-900 dark:hover:text-orange-300 p-2 hover:bg-orange-50 dark:hover:bg-orange-900/30 rounded transition-colors"
                          title="Create Work Order"
                        >
                          <FaWrench />
                        </button>
                        <button
                          onClick={() => handleViewLinkedWOs(asset.name)}
                          className="text-cyan-600 dark:text-cyan-400 hover:text-cyan-900 dark:hover:text-cyan-300 p-2 hover:bg-cyan-50 dark:hover:bg-cyan-900/30 rounded transition-colors"
                          title="View Linked Work Orders"
                        >
                          <FaClipboardList />
                        </button>
                        <button
                          onClick={() => setDeleteConfirmOpen(asset.name)}
                          className="text-red-600 dark:text-red-400 hover:text-red-900 dark:hover:text-red-300 p-2 hover:bg-red-50 dark:hover:bg-red-900/30 rounded transition-colors"
                          title="Delete Asset"
                          disabled={mutationLoading}
                        >
                          <FaTrash />
                        </button>
                        
                        {/* More Actions Dropdown */}
                        <div className="relative" ref={actionMenuOpen === asset.name ? dropdownRef : null}>
                          <button
                            onClick={() => setActionMenuOpen(actionMenuOpen === asset.name ? null : asset.name)}
                            className="text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200 p-2 hover:bg-gray-50 dark:hover:bg-gray-700 rounded transition-colors"
                            title="More Actions"
                          >
                            <FaEllipsisV />
                          </button>
                          
                          {actionMenuOpen === asset.name && (
                            <div className="absolute right-0 mt-2 w-48 bg-white dark:bg-gray-800 rounded-lg shadow-lg border border-gray-200 dark:border-gray-700 z-10">
                              <button
                                onClick={() => {
                                  handleCreateWorkOrder(asset);
                                  setActionMenuOpen(null);
                                }}
                                className="w-full text-left px-4 py-2 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 flex items-center gap-2 rounded-t-lg"
                              >
                                <FaWrench className="text-orange-500" />
                                Create Work Order
                              </button>
                              <button
                                onClick={() => {
                                  handleViewLinkedWOs(asset.name);
                                  setActionMenuOpen(null);
                                }}
                                className="w-full text-left px-4 py-2 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 flex items-center gap-2"
                              >
                                <FaClipboardList className="text-cyan-500" />
                                View Linked WOs
                              </button>
                              {/* <button
                                onClick={() => {
                                  handleExportSingle(asset);
                                  setActionMenuOpen(null);
                                }}
                                className="w-full text-left px-4 py-2 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 flex items-center gap-2"
                              >
                                <FaDownload className="text-blue-500" />
                                Export as JSON
                              </button> */}
                              <button
                                onClick={() => {
                                  handlePrint(asset.name);
                                  setActionMenuOpen(null);
                                }}
                                className="w-full text-left px-4 py-2 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 flex items-center gap-2 rounded-b-lg"
                              >
                                <FaPrint className="text-purple-500" />
                                Print Asset
                              </button>
                            </div>
                          )}
                        </div>
                      </div>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>

        <ListPagination
          currentPage={page + 1}
          totalCount={totalCount}
          pageSize={limit}
          hasMore={hasMore}
          itemLabel={t('pagination.assets')}
          onPageChange={(p) => setPage(Math.max(0, p - 1))}
        />
      </div>

      {/* Delete Confirmation Modal */}
      {deleteConfirmOpen && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white dark:bg-gray-800 rounded-lg p-6 max-w-md w-full mx-4 shadow-2xl">
            <div className="flex items-start gap-4">
              <div className="flex-shrink-0 w-12 h-12 rounded-full bg-red-100 dark:bg-red-900/30 flex items-center justify-center">
                <FaTrash className="text-red-600 dark:text-red-400 text-xl" />
              </div>
              <div className="flex-1">
                <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-2">
                  Delete Asset
                </h3>
                <p className="text-sm text-gray-600 dark:text-gray-400 mb-4">
                  Are you sure you want to delete this asset? This action cannot be undone.
                </p>
                <div className="bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-md p-3 mb-4">
                  <p className="text-xs text-yellow-800 dark:text-yellow-300">
                    <strong>Asset ID:</strong> {deleteConfirmOpen}
                  </p>
                </div>
                <div className="flex gap-3 justify-end">
                  <button
                    onClick={() => setDeleteConfirmOpen(null)}
                    className="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 rounded-lg transition-colors"
                    disabled={mutationLoading}
                  >
                    Cancel
                  </button>
                  <button
                    onClick={() => handleDelete(deleteConfirmOpen)}
                    className="px-4 py-2 text-sm font-medium text-white bg-red-600 hover:bg-red-700 rounded-lg transition-colors flex items-center gap-2 disabled:opacity-50"
                    disabled={mutationLoading}
                  >
                    {mutationLoading ? (
                      <>
                        <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
                        Deleting...
                      </>
                    ) : (
                      <>
                        <FaTrash />
                        Delete Asset
                      </>
                    )}
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
      )}

      <style>{`
        @keyframes scale-in {
          from {
            transform: scale(0.95);
            opacity: 0;
          }
          to {
            transform: scale(1);
            opacity: 1;
          }
        }
        .animate-scale-in {
          animation: scale-in 0.2s ease-out;
        }
        
        .scrollbar-hide {
          -ms-overflow-style: none;
          scrollbar-width: none;
        }
        .scrollbar-hide::-webkit-scrollbar {
          display: none;
        }
      `}</style>
    </div>
  );
};

export default AssetList;