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, FaQrcode } from 'react-icons/fa';
import LinkField from '../components/LinkField';
import ListPagination from '../components/ListPagination';
import { buildDateRangeFilters, toFrappeFilterArray } from '../utils/listFilterUtils';
import { useUserPermissions } from '../hooks/useUserPermissions';
import { deleteAssetApi } from '../utils/deleteAssetApi';

import DeleteRequestButton from '../components/DeleteRequestButton';
import type { DeleteStatus } from '../services/deleteRequestService';
import DynamicExportModal from '../components/DynamicExportModal';

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

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

// ============================================================
// ADD THIS: QR Print Modal - place after ExportModal component
// ============================================================

type QRPrintScope = 'selected' | 'all_on_page' | 'all_with_filters';

interface QRPrintModalProps {
  isOpen: boolean;
  onClose: () => void;
  selectedCount: number;
  totalCount: number;
  pageCount: number;
  onPrint: (scope: QRPrintScope) => void;
  isPrinting: boolean;
}

const QRPrintModal: React.FC<QRPrintModalProps> = ({
  isOpen,
  onClose,
  selectedCount,
  totalCount,
  pageCount,
  onPrint,
  isPrinting,
}) => {
  const { t } = useTranslation();
  const [scope, setScope] = useState<QRPrintScope>(selectedCount > 0 ? 'selected' : 'all_with_filters');

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

  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-lg w-full animate-scale-in">
        {/* Header */}
        <div className="bg-gradient-to-r from-purple-500 to-purple-600 px-6 py-4 rounded-t-lg">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              <FaQrcode className="text-white text-xl" />
              <h3 className="text-lg font-semibold text-white">Print QR Codes</h3>
            </div>
            <button onClick={onClose} className="text-white/80 hover:text-white transition-colors" disabled={isPrinting}>
              <FaTimes size={20} />
            </button>
          </div>
        </div>

        <div className="p-6">
          {/* Layout Info */}
          <div className="mb-5 p-3 bg-purple-50 dark:bg-purple-900/20 border border-purple-200 dark:border-purple-700 rounded-lg">
            <p className="text-sm text-purple-700 dark:text-purple-300 flex items-center gap-2">
              <FaQrcode />
              <span>Layout: <strong>2 columns × 5 rows = 10 QR codes per A4 page</strong></span>
            </p>
            <p className="text-xs text-purple-500 dark:text-purple-400 mt-1 ml-6">
              Each QR includes Asset Name and Asset ID
            </p>
          </div>

          {/* Scope Selection */}
          <h4 className="text-sm font-semibold text-gray-700 dark:text-gray-300 mb-3">Select Records</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-purple-500 bg-purple-50 dark:bg-purple-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="qr_scope" value="selected"
                checked={scope === 'selected'}
                onChange={() => setScope('selected')}
                disabled={selectedCount === 0}
                className="text-purple-600 focus:ring-purple-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">{selectedCount} asset(s) selected</div>
              </div>
              {selectedCount > 0 && (
                <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">
                  {selectedCount}
                </span>
              )}
            </label>

            <label className={`flex items-center gap-3 p-3 rounded-lg border cursor-pointer transition-all ${
              scope === 'all_on_page'
                ? 'border-purple-500 bg-purple-50 dark:bg-purple-900/20'
                : 'border-gray-200 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-700/50'
            }`}>
              <input
                type="radio" name="qr_scope" value="all_on_page"
                checked={scope === 'all_on_page'}
                onChange={() => setScope('all_on_page')}
                className="text-purple-600 focus:ring-purple-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">{pageCount} assets on this 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}
              </span>
            </label>

            <label className={`flex items-center gap-3 p-3 rounded-lg border cursor-pointer transition-all ${
              scope === 'all_with_filters'
                ? 'border-purple-500 bg-purple-50 dark:bg-purple-900/20'
                : 'border-gray-200 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-700/50'
            }`}>
              <input
                type="radio" name="qr_scope" value="all_with_filters"
                checked={scope === 'all_with_filters'}
                onChange={() => setScope('all_with_filters')}
                className="text-purple-600 focus:ring-purple-500"
              />
              <div className="flex-1">
                <div className="font-medium text-gray-900 dark:text-white">All Records (with filters)</div>
                <div className="text-sm text-gray-500 dark:text-gray-400">All {totalCount} matching assets</div>
              </div>
              <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">
                {totalCount}
              </span>
            </label>
          </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-end gap-3 rounded-b-lg">
          <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={isPrinting}
          >
            Cancel
          </button>
          <button
            onClick={() => onPrint(scope)}
            disabled={isPrinting}
            className="px-4 py-2 text-sm font-medium text-white bg-purple-600 hover:bg-purple-700 rounded-lg transition-colors flex items-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed"
          >
            {isPrinting ? (
              <>
                <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
                Fetching QR Codes...
              </>
            ) : (
              <>
                <FaQrcode />
                Print QRs
              </>
            )}
          </button>
        </div>
      </div>
    </div>
  );
};


const AssetList: React.FC = () => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const [searchParams, setSearchParams] = useSearchParams();
  const setSearchParamsRef = useRef(setSearchParams);
  const page = useMemo(() => {
    const p = parseInt(searchParams.get('page') || '1', 10);
    return Math.max(0, Number.isNaN(p) ? 0 : p - 1);
  }, [searchParams]);
  const setPage = useCallback((zeroBasedPage: number) => {
    setSearchParamsRef.current((prev) => {
      const next = new URLSearchParams(prev);
      next.set('page', String(zeroBasedPage + 1));
      return next;
    });
  }, []);

  useEffect(() => {
    setSearchParamsRef.current = setSearchParams;
  }, [setSearchParams]);
  const [searchTerm, setSearchTerm] = useState(() => searchParams.get('search') || '');
  const [deleteConfirmOpen, setDeleteConfirmOpen] = useState<string | null>(null);
  const [actionMenuOpen, setActionMenuOpen] = useState<string | null>(null);
  const dropdownRef = useRef<HTMLDivElement>(null);
  const limit = 20;

  // ✅ 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);
  const [deleteLoading, setDeleteLoading] = useState(false);

  // QR Print modal state
  const [showQRPrintModal, setShowQRPrintModal] = useState(false);
  const [isPrinting, setIsPrinting] = useState(false);

  const [userRoles, setUserRoles] = useState<string[]>([]);
  const [listIsSystemManager, setListIsSystemManager] = 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'];
  const ALLOWED_ROLES_FOR_ADD = ['Maintenance Manager', 'Maintenance User', 'System Manager', 'Technician', 'Contractor Engineer', 'Work Control'];
  const BLOCKED_ROLES_FOR_ADD = ['Contractor Supervisor'];

  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);
        // } 
        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);
          
          const userRolesList: string[] = data.message.user_roles || [];
          const isSystemManager = userRolesList.includes('System Manager');
          const hasBlockedRole = BLOCKED_ROLES_FOR_ADD.some(role => userRolesList.includes(role));
          
          // Contractor Supervisor is blocked unless they also have System Manager
          if (hasBlockedRole && !isSystemManager) {
            console.log('🚫 [Role Check] Blocked: Contractor Supervisor without System Manager');
            setCanAddAsset(false);
          } else {
            setCanAddAsset(data.message.has_role);
          }
        } else {
          console.error('❌ [Role Check] Invalid response:', data);
          setCanAddAsset(false);
        }

        // Fetch full roles array for DeleteRequestButton in list rows
        const rolesListResponse = await fetch('/api/method/asset_lite.api.user_roles.get_user_roles', {
          credentials: 'include'
        });
        const rolesListData = await rolesListResponse.json();
        const rolesList = Array.isArray(rolesListData.message) ? rolesListData.message : [];
        setUserRoles(rolesList);
        setListIsSystemManager(rolesList.includes('System Manager'));

      } catch (error) {
        console.error('❌ [Role Check] Error:', error);
        setCanAddAsset(false);
      }
    };

    checkUserRoles();
  }, []);

  // Filter states (init from URL so filters persist when navigating back from detail)
  const [dateFilterBy, setDateFilterBy] = useState<'' | 'creation' | 'modified'>(() => (searchParams.get('date_filter_by') as '' | 'creation' | 'modified') || '');
  const [dateStart, setDateStart] = useState(() => searchParams.get('date_start') || '');
  const [dateEnd, setDateEnd] = useState(() => searchParams.get('date_end') || '');
  const [filterAssetId, setFilterAssetId] = useState(() => searchParams.get('asset_id') || '');
  const [filterCompany, setFilterCompany] = useState(() => searchParams.get('company') || '');
  const [filterManufacturer, setFilterManufacturer] = useState(() => searchParams.get('manufacturer') || '');
  const [filterSupplier, setFilterSupplier] = useState(() => searchParams.get('supplier') || '');
  const [filterLocation, setFilterLocation] = useState(() => searchParams.get('location') || '');
  const [filterDepartment, setFilterDepartment] = useState(() => searchParams.get('department') || '');
  const [filterModality, setFilterModality] = useState(() => searchParams.get('modality') || '');
  const [filterDeviceStatus, setFilterDeviceStatus] = useState(() => searchParams.get('device_status') || '');
  const [filterAssetName, setFilterAssetName] = useState(() => searchParams.get('asset_name') || '');
  const [filterSerialNumber, setFilterSerialNumber] = useState(() => searchParams.get('serial_number') || '');

  // Sort state (init from URL)
  const sortOptions = ['creation desc', 'creation asc', 'modified desc', 'modified asc', 'asset_name asc', 'asset_name desc', 'name asc', 'name desc'] as const;
  const [sortBy, setSortBy] = useState<string>(() => searchParams.get('sort_by') || 'creation desc');

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

  // Temporary states for text inputs (init from URL for persistence)
  const [tempAssetName, setTempAssetName] = useState(() => searchParams.get('asset_name') || '');
  const [tempSerialNumber, setTempSerialNumber] = useState(() => searchParams.get('serial_number') || '');

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

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

  // Update active filter count
  const hasDateFilter = dateFilterBy && (dateStart || dateEnd);
  useEffect(() => {
    const count = [
      filterAssetId,
      filterCompany,
      filterLocation,
      filterDepartment,
      filterModality,
      filterManufacturer,
      filterSupplier,
      filterDeviceStatus,
      filterAssetName,
      filterSerialNumber,
      searchTerm
    ].filter(Boolean).length + (hasDateFilter ? 1 : 0);
    setActiveFilterCount(count);
  }, [
    hasDateFilter,
    dateFilterBy,
    dateStart,
    dateEnd,
    filterAssetId,
    filterCompany,
    filterLocation,
    filterDepartment,
    filterModality,
    filterManufacturer,
    filterSupplier,
    filterDeviceStatus,
    filterAssetName,
    filterSerialNumber,
    searchTerm
  ]);

  // Build filters object
  const filters: Record<string, any> = {};
  if (filterAssetId) filters['name'] = filterAssetId;
  if (filterCompany) filters['company'] = filterCompany;
  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));

  filters['custom_delete_status'] = ['!=', 'Deleted'];

  const orderBy = sortOptions.includes(sortBy as any) ? sortBy : 'creation desc';
  const { assets, totalCount, hasMore, loading, error, refetch } = useAssets(
    filters,
    limit,
    page * limit,
    orderBy,
    permissionFilters
  );

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

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

  // Sync filters to URL when user changes a filter (not on mount/return from detail)
  const filtersChangedOnce = useRef(false);
  useEffect(() => {
    if (!filtersChangedOnce.current) {
      filtersChangedOnce.current = true;
      return;
    }
    setSearchParamsRef.current((prev) => {
      const next = new URLSearchParams(prev);
      if (dateFilterBy) next.set('date_filter_by', dateFilterBy); else next.delete('date_filter_by');
      if (dateStart) next.set('date_start', dateStart); else next.delete('date_start');
      if (dateEnd) next.set('date_end', dateEnd); else next.delete('date_end');
      if (filterAssetId) next.set('asset_id', filterAssetId); else next.delete('asset_id');
      if (filterCompany) next.set('company', filterCompany); else next.delete('company');
      if (filterManufacturer) next.set('manufacturer', filterManufacturer); else next.delete('manufacturer');
      if (filterSupplier) next.set('supplier', filterSupplier); else next.delete('supplier');
      if (filterLocation) next.set('location', filterLocation); else next.delete('location');
      if (filterDepartment) next.set('department', filterDepartment); else next.delete('department');
      if (filterModality) next.set('modality', filterModality); else next.delete('modality');
      if (filterDeviceStatus) next.set('device_status', filterDeviceStatus); else next.delete('device_status');
      if (filterAssetName) next.set('asset_name', filterAssetName); else next.delete('asset_name');
      if (filterSerialNumber) next.set('serial_number', filterSerialNumber); else next.delete('serial_number');
      if (searchTerm) next.set('search', searchTerm); else next.delete('search');
      if (sortBy && sortBy !== 'creation desc') next.set('sort_by', sortBy); else next.delete('sort_by');
      next.set('page', '1');
      return next;
    });
  }, [dateFilterBy, dateStart, dateEnd, filterAssetId, filterCompany, filterManufacturer, filterSupplier, filterLocation, filterDepartment, filterModality,
     filterDeviceStatus, filterAssetName, filterSerialNumber, searchTerm, sortBy]);

  // ✅ Clear selection when filters/page change
  useEffect(() => {
    setSelectedRows(new Set());
  }, [dateFilterBy, dateStart, dateEnd, filterAssetId, filterCompany, 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: {
        dateFilterBy,
        dateStart,
        dateEnd,
        sortBy,
        filterAssetId,
        filterCompany,
        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;
    setDateFilterBy(f.dateFilterBy || ''); setDateStart(f.dateStart || ''); setDateEnd(f.dateEnd || '');
    setSortBy(f.sortBy || 'creation desc');
    setFilterAssetId(f.filterAssetId || '');
    setFilterCompany(f.filterCompany || '');
    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 getDeleteStatusRowClass = (deleteStatus: string | undefined): string => {
    switch (deleteStatus) {
      case 'Delete Request With Supervisor':
        return 'bg-orange-50 dark:bg-orange-900/10';
      case 'Delete Request With CM':
        return 'bg-yellow-50 dark:bg-yellow-900/10';
      case 'Deleted':
        return 'bg-red-50 dark:bg-red-900/10';
      default:
        return '';
    }
  };

  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;

    const mergedFilters = { ...filters, ...permissionFilters };
    const filterArrays = toFrappeFilterArray(mergedFilters);
    while (hasMoreData) {
      try {
        const response = await fetch('/api/method/frappe.client.get_list', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            doctype: 'Asset',
            filters: filterArrays.length > 0 ? filterArrays : {},
            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]);


  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 - fetches full asset data then passes as query params
  const handleCreateWorkOrder = async (asset: any) => {
    try {
      // Show loading state (optional - you can add a loading state if needed)
      console.log('Fetching full asset details for:', asset.name);
      
      // Fetch full asset details to get all fields including building and room
      const response = await fetch(`/api/resource/Asset/${encodeURIComponent(asset.name)}`, {
        method: 'GET',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
      });
      
      const data = await response.json();
      const fullAsset = data.data || asset; // Fallback to list data if fetch fails
      
      console.log('Full asset data:', fullAsset);
      console.log('Building:', fullAsset.custom_building);
      console.log('Room Number:', fullAsset.custom_room_number);
      
      const params = new URLSearchParams();
      
      // Pass asset data to work order form
      if (fullAsset.name) params.append('asset', fullAsset.name);
      if (fullAsset.asset_name) params.append('asset_name', fullAsset.asset_name);
      if (fullAsset.custom_asset_type) params.append('asset_type', fullAsset.custom_asset_type);
      if (fullAsset.custom_manufacturer) params.append('manufacturer', fullAsset.custom_manufacturer);
      if (fullAsset.custom_serial_number) params.append('serial_number', fullAsset.custom_serial_number);
      if (fullAsset.department) params.append('department', fullAsset.department);
      if (fullAsset.custom_site_contractor) params.append('site_contractor', fullAsset.custom_site_contractor);
      if (fullAsset.custom_subcontractor) params.append('subcontractor', fullAsset.custom_subcontractor);
      if (fullAsset.company) params.append('company', fullAsset.company);
      if (fullAsset.custom_service_agreement) params.append('custom_service_agreement', fullAsset.custom_service_agreement);
      if (fullAsset.custom_service_coverage) params.append('custom_service_coverage', fullAsset.custom_service_coverage);
      if (fullAsset.custom_site) params.append('site_name', fullAsset.custom_site);
      if (fullAsset.supplier) params.append('supplier', fullAsset.supplier);
      // Location fields from Asset
      if (fullAsset.custom_building) params.append('building', fullAsset.custom_building);
      if (fullAsset.custom_room_number) params.append('room_no', fullAsset.custom_room_number);
      if (fullAsset.location) params.append('location', fullAsset.location);
      
      navigate(`/work-orders/new?${params.toString()}`);
    } catch (error) {
      console.error('Error fetching asset details:', error);
      // Fallback: navigate with just the asset ID, WorkOrderDetail will fetch the rest
      const params = new URLSearchParams();
      if (asset.name) params.append('asset', asset.name);
      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 handleDelete = async (assetName: string) => {
//   setDeleteLoading(true);
//   try {
//     const result = await deleteAssetApi(assetName);
//     const { details } = result;

//     setDeleteConfirmOpen(null);
//     refetch();

//     const parts: string[] = [];
//     if (details.asset_activities.deleted.length)
//       parts.push(`${details.asset_activities.deleted.length} activity log(s)`);
//     if (details.asset_movements.deleted.length)
//       parts.push(`${details.asset_movements.deleted.length} movement(s)`);
//     if (details.asset_depreciation_schedules.deleted.length)
//       parts.push(`${details.asset_depreciation_schedules.deleted.length} depreciation schedule(s)`);
//     if (details.asset_maintenance.deleted.length)
//       parts.push(`${details.asset_maintenance.deleted.length} maintenance record(s)`);
//     // if (details.asset_repair.deleted.length)
//     //   parts.push(`${details.asset_repair.deleted.length} repair record(s)`);

//     const relatedMsg = parts.length ? `\n\nAlso removed: ${parts.join(', ')}.` : '';
//     alert(`✅ Asset "${assetName}" deleted successfully.${relatedMsg}`);

//   } catch (err) {
//     alert(`❌ Failed to delete asset:\n${err instanceof Error ? err.message : 'Unknown error'}`);
//   } finally {
//     setDeleteLoading(false);
//   }
// };

// ============================================================
  // ADD THIS: QR Print Handler
  // ============================================================
  const handlePrintQRs = async (scope: QRPrintScope) => {
    setIsPrinting(true);

    try {
      // 1. Determine which assets to print
      let assetsToPrint: any[] = [];

      if (scope === 'selected') {
        assetsToPrint = assets.filter(a => selectedRows.has(a.name));
      } else if (scope === 'all_on_page') {
        assetsToPrint = assets;
      } else {
        // all_with_filters — reuse existing fetchAllAssetsForExport
        assetsToPrint = await fetchAllAssetsForExport();
      }

      if (assetsToPrint.length === 0) {
        alert('No assets to print.');
        return;
      }

      // 2. Batch-fetch QR codes from File doctype
      //    attached_to_doctype=Asset, attached_to_field=custom_attach_image
      const assetNames = assetsToPrint.map(a => a.name);

      // Frappe supports OR filters via multiple entries — fetch in one call using 'in'
      const CHUNK_SIZE = 100;
      const fileRecords: any[] = [];

      for (let i = 0; i < assetNames.length; i += CHUNK_SIZE) {
        const chunk = assetNames.slice(i, i + CHUNK_SIZE);

        const fileResponse = await fetch('/api/method/frappe.client.get_list', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          credentials: 'include',
          body: JSON.stringify({
            doctype: 'File',
            filters: [
              ['File', 'attached_to_doctype', '=', 'Asset'],
              ['File', 'attached_to_field', '=', 'custom_attach_image'],
              ['File', 'attached_to_name', 'in', chunk],
            ],
            fields: ['attached_to_name', 'file_url'],
            limit_page_length: CHUNK_SIZE,
          }),
        });

        const fileData = await fileResponse.json();
        const chunkRecords: any[] = fileData?.message || [];
        fileRecords.push(...chunkRecords);
      }

      // Build a map: assetName -> qrUrl
      const qrMap: Record<string, string> = {};
      fileRecords.forEach((f: any) => {
        if (f.attached_to_name && f.file_url) {
          qrMap[f.attached_to_name] = f.file_url;
        }
      });

      // 3. Build the print HTML
      // Layout: 2 columns × 5 rows = 10 per A4 page
      const qrItems = assetsToPrint.map(asset => ({
        name: asset.name,
        asset_name: asset.asset_name || asset.name,
        qrUrl: qrMap[asset.name] || null,
        technical_department: asset.custom_technical_department || '',
      }));

      const itemsHTML = qrItems.map(item => `
        <div class="qr-cell">
          <div class="qr-image-wrapper">
            ${item.qrUrl
              ? `<img src="${item.qrUrl}" alt="QR" class="qr-img" />`
              : `<div class="qr-placeholder">No QR</div>`
            }
          </div>
          <div class="qr-info">
            <div class="qr-asset-name" title="${item.asset_name}">${item.asset_name}</div>
            <div class="qr-asset-id">${item.name}</div>
            ${item.technical_department
              ? `<div class="qr-dept">${item.technical_department}</div>`
              : ''
            }
          </div>
        </div>
      `).join('');

      const printWindow = window.open('', '_blank');
      if (!printWindow) {
        alert('Pop-up blocked. Please allow pop-ups for this site.');
        return;
      }

      printWindow.document.write(`
        <!DOCTYPE html>
        <html>
          <head>
            <title>QR Codes - ${assetsToPrint.length} Assets</title>
            <style>
              @page {
                size: A4;
                margin: 4mm;
              }
              * { margin: 0; padding: 0; box-sizing: border-box; }
              body {
                font-family: Arial, sans-serif;
                background: white;
              }
              .no-print {
                padding: 12px 20px;
                background: #6d28d9;
                color: white;
                display: flex;
                align-items: center;
                gap: 12px;
              }
              .no-print button {
                background: white;
                color: #6d28d9;
                border: none;
                padding: 6px 16px;
                border-radius: 4px;
                font-weight: 600;
                cursor: pointer;
                font-size: 13px;
              }
              .no-print span { font-size: 14px; }
              @media print {
                .no-print { display: none !important; }
              }

              /* Grid: 2 columns, 5 rows per page = 10 per page */
              .qr-grid {
                display: grid;
                grid-template-columns: 1fr 1fr;
                gap: 1mm;
                padding: 0;
              }
              .qr-cell {
                display: flex;
                flex-direction: column;
                align-items: center;
                border: 1px solid #d1d5db;
                border-radius: 6px;
                padding: 2mm 3mm 2mm;
                height: 54mm;
                page-break-inside: avoid;
                overflow: hidden;
              }
              .qr-image-wrapper {
                flex: 1;
                display: flex;
                align-items: center;
                justify-content: center;
                width: 100%;
              }
              .qr-img {
                max-width: 100%;
                max-height: 38mm;
                object-fit: contain;
              }
              .qr-placeholder {
                width: 32mm;
                height: 32mm;
                background: #f3f4f6;
                border: 2px dashed #d1d5db;
                display: flex;
                align-items: center;
                justify-content: center;
                color: #9ca3af;
                font-size: 10px;
                border-radius: 4px;
              }
              .qr-info {
                text-align: center;
                margin-top: 1mm;
                width: 100%;
                line-height: 1.3;
              }
              .qr-asset-name {
                font-size: 8pt;
                font-weight: 600;
                color: #111827;
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
                max-width: 100%;
              }
              .qr-asset-id {
                font-size: 7pt;
                color: #6b7280;
                margin-top: 1mm;
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
              }
              .qr-dept {
                font-size: 7pt;
                color: #2563eb;
                margin-top: 0.5mm;
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
                font-weight: 500;
              }
            </style>
          </head>
          <body>
            <div class="no-print">
              <span>📄 ${assetsToPrint.length} QR code(s)</span>
              <button onclick="window.print()">🖨️ Print / Save PDF</button>
              <button onclick="window.close()" style="background:#e5e7eb;color:#374151;margin-left:4px;">✕ Close</button>
            </div>
            <div class="qr-grid">
              ${itemsHTML}
            </div>
          </body>
        </html>
      `);

      printWindow.document.close();
      setShowQRPrintModal(false);

    } catch (err) {
      console.error('QR print error:', err);
      alert(`Failed to print QR codes: ${err instanceof Error ? err.message : 'Unknown error'}`);
    } finally {
      setIsPrinting(false);
    }
  };

  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 handlePrint = async (assetName: string) => {
  // Try direct QR file URL first
  const directUrl = `/files/${assetName}-qr.png`;

  let qrCodeUrl: string | null = null;

  try {
    const headResponse = await fetch(directUrl, { method: 'HEAD', credentials: 'include' });
    if (headResponse.ok) {
      qrCodeUrl = directUrl;
    } else {
      // Fallback: search File doctype for attached QR
      const fileRes = await fetch(
        `/api/resource/File?filters=[["File","attached_to_name","=","${assetName}"]]`,
        { credentials: 'include' }
      );
      const fileData = await fileRes.json();
      if (fileData?.data?.length > 0) {
        qrCodeUrl = fileData.data[0].file_url;
      }
    }
  } catch (err) {
    console.error('Error fetching QR code:', err);
  }

  // Also get asset name from the current assets list
  const asset = assets.find(a => a.name === assetName);

  const printWindow = window.open('', '_blank');
  if (!printWindow) return;

  printWindow.document.write(`
    <!DOCTYPE html>
    <html>
      <head>
        <title>Print QR Code - ${assetName}</title>
        <style>
          @page { margin: 0.5in; size: auto; }
          * { margin: 0; padding: 0; box-sizing: border-box; }
          body {
            font-family: Arial, sans-serif;
            display: flex;
            align-items: center;
            justify-content: center;
            min-height: 100vh;
          }
          .qr-container {
            text-align: center;
            border: 2px solid #333;
            padding: 20px;
            border-radius: 8px;
            background: white;
            max-width: 400px;
          }
          .qr-image { width: 300px; height: 300px; margin: 15px auto; display: block; }
          h1 { font-size: 20px; margin-bottom: 10px; }
          .asset-info { margin: 10px 0; font-size: 14px; line-height: 1.5; }
          .no-qr { width: 300px; height: 300px; margin: 15px auto; display: flex; align-items: center; justify-content: center; background: #f5f5f5; border: 2px dashed #ccc; border-radius: 8px; color: #999; font-size: 14px; }
        </style>
      </head>
      <body>
        <div class="qr-container">
          <h1>Asset QR Code</h1>
          <div class="asset-info">
            <strong>Asset ID:</strong> ${assetName}<br/>
            <strong>Asset Name:</strong> ${asset?.asset_name || 'N/A'}
          </div>
          ${qrCodeUrl
            ? `<img src="${qrCodeUrl}" alt="QR Code" class="qr-image" onload="window.print();" />`
            : `<div class="no-qr">No QR Code Available</div><script>setTimeout(() => window.print(), 500);<\/script>`
          }
        </div>
      </body>
    </html>
  `);

  printWindow.document.close();
};

  const handleClearFilters = () => {
    setDateFilterBy(''); setDateStart(''); setDateEnd('');
    setSortBy('creation desc');
    setFilterAssetId('');
    setFilterCompany('');
    setFilterManufacturer('');
    setFilterSupplier('');
    setFilterLocation('');
    setFilterDepartment('');
    setFilterModality('');
    setFilterDeviceStatus('');
    setFilterAssetName('');
    setFilterSerialNumber('');
    setTempAssetName('');
    setTempSerialNumber('');
    setSearchTerm('');
    if (assetNameDebounceRef.current) clearTimeout(assetNameDebounceRef.current);
    if (serialNumberDebounceRef.current) clearTimeout(serialNumberDebounceRef.current);
    setSearchParamsRef.current((prev) => {
      const next = new URLSearchParams(prev);
      next.delete('date_filter_by'); next.delete('date_start'); next.delete('date_end');
      next.delete('sort_by');
      next.delete('asset_id'); next.delete('company'); next.delete('manufacturer'); next.delete('supplier');
      next.delete('location'); next.delete('department'); next.delete('modality'); next.delete('device_status');
      next.delete('asset_name'); next.delete('serial_number'); next.delete('search');
      next.set('page', '1');
      return next;
    });
  };

  const hasActiveFilters = hasDateFilter || filterAssetId || filterCompany || 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">{t('assets.loadingPermissions')}</p>
        </div>
      </div>
    );
  }

  // ✅ Error state for permissions
  if (permissionsError) {
    return (
      <div className="p-6 bg-gray-50 dark:bg-gray-900 min-h-screen">
        <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-6 bg-gray-50 dark:bg-gray-900 min-h-screen">
        <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">⚠️ {t('assets.apiNotAvailable')}</h2>
          <div className="text-yellow-700 dark:text-yellow-400 space-y-3">
            <p><strong>{t('assets.apiNotDeployed')}</strong></p>
            <button 
              onClick={() => navigate('/assets/new')}
              className="mt-2 bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded"
            >
              {t('assets.tryCreatingNew')}
            </button>
            <button 
              onClick={refetch}
              className="mt-2 ml-2 bg-gray-600 hover:bg-gray-700 text-white px-4 py-2 rounded"
            >
              {t('common.tryAgain')}
            </button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="p-6 bg-gray-50 dark:bg-gray-900 min-h-screen">
      {/* Header */}
      <div className="mb-6 flex justify-between items-center">
        <div>
          <h1 className="text-3xl font-bold text-gray-800 dark:text-white">{t('assets.title')}</h1>
          <p className="text-gray-600 dark:text-gray-400 mt-1">
            {t('assets.listTotal')} {totalCount} asset{totalCount !== 1 ? 's' : ''}
            {/* ✅ Show selection count */}
            {selectedRows.size > 0 && (
              <span className="ml-2 text-blue-600 dark:text-blue-400">
                • {selectedRows.size} {t('common.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>
                {t('common.updating')}
              </span>
            )}
          </p>
        </div>
        <div className="flex gap-3">
          {/* Print QRs Button */}
          <button
            onClick={() => setShowQRPrintModal(true)}
            className="bg-purple-600 hover:bg-purple-700 text-white px-4 py-2 rounded-lg flex items-center gap-2 shadow transition-all"
            disabled={totalCount === 0}
          >
            <FaQrcode />
            <span className="font-medium">Print QRs</span>
            {selectedRows.size > 0 && (
              <span className="bg-white/20 px-1.5 py-0.5 rounded text-xs">
                {selectedRows.size}
              </span>
            )}
          </button>

          {/* ✅ 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"> */}

      <div className="isolate 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">
                  {hasDateFilter && (
                    <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">{t('filters.filterBy')}:</span> {dateFilterBy === 'creation' ? t('filters.createdDate') : t('filters.latestModifiedDate')} {dateStart && ` ${dateStart}`} {dateEnd && ` - ${dateEnd}`}
                      <button onClick={(e) => { e.stopPropagation(); setDateFilterBy(''); setDateStart(''); setDateEnd(''); }} className="hover:text-red-500 transition-colors"><FaTimes className="text-[9px]" /></button>
                    </span>
                  )}
                  {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">{t('commonFields.assetId')}:</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">{t('assets.selectHospital')}:</span> {filterCompany}
                      <button 
                        onClick={(e) => { e.stopPropagation(); setFilterCompany(''); }} 
                        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">{t('commonFields.assetName')}:</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">{t('commonFields.serialNumber')}:</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">{t('assets.table.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">{t('filters.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">{t('filters.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">{t('filters.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">{t('filters.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">{t('filters.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>
            )}

            {/* Sort + 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">
                  {/* Sort By */}
                  <div className="relative">
                    <label className="block text-[10px] font-medium text-gray-700 dark:text-gray-300 mb-0.5">{t('filters.sortBy')}</label>
                    <select
                      value={sortBy}
                      onChange={(e) => setSortBy(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="creation desc">{t('filters.sortCreationNewest')}</option>
                      <option value="creation asc">{t('filters.sortCreationOldest')}</option>
                      <option value="modified desc">{t('filters.sortModifiedNewest')}</option>
                      <option value="modified asc">{t('filters.sortModifiedOldest')}</option>
                      <option value="asset_name asc">{t('filters.sortAssetNameAsc')}</option>
                      <option value="asset_name desc">{t('filters.sortAssetNameDesc')}</option>
                      <option value="name asc">{t('filters.sortNameAsc')}</option>
                      <option value="name desc">{t('filters.sortNameDesc')}</option>
                    </select>
                  </div>
                  {/* Date range: Filter By + Start / End */}
                  <div className="relative">
                    <label className="block text-[10px] font-medium text-gray-700 dark:text-gray-300 mb-0.5">{t('filters.filterBy')}</label>
                    <select value={dateFilterBy} onChange={(e) => { const v = e.target.value as '' | 'creation' | 'modified'; setDateFilterBy(v); }} 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="">{t('filters.filterBy')}</option>
                      <option value="creation">{t('filters.createdDate')}</option>
                      <option value="modified">{t('filters.latestModifiedDate')}</option>
                    </select>
                  </div>
                  {dateFilterBy && (
                    <>
                      <div className="relative">
                        <label className="block text-[10px] font-medium text-gray-700 dark:text-gray-300 mb-0.5">{t('filters.startDate')}</label>
                        <input type="date" value={dateStart} onChange={(e) => { const v = e.target.value; setDateStart(v); if (dateEnd && v > dateEnd) setDateEnd(v); }} 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" />
                      </div>
                      <div className="relative">
                        <label className="block text-[10px] font-medium text-gray-700 dark:text-gray-300 mb-0.5">{t('filters.endDate')}</label>
                        <input type="date" value={dateEnd} onChange={(e) => setDateEnd(e.target.value)} min={dateStart || undefined} 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" />
                      </div>
                    </>
                  )}
                  {/* Asset ID */}
                  <div className="relative z-[60]">
                    <LinkField
                      label={t('commonFields.assetId')}
                      doctype="Asset"
                      value={filterAssetId}
                      onChange={(val) => setFilterAssetId(val)}
                      placeholder={t('assets.selectAssetId')}
                      disabled={false}
                      compact={true}
                      filters={{ custom_delete_status: ['!=', 'Deleted'] }}
                    />
                    {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">
                      {t('commonFields.assetName')}
                    </label>
                    <input
                      type="text"
                      value={tempAssetName}
                      onChange={(e) => handleAssetNameChange(e.target.value)}
                      onKeyDown={(e) => handleKeyPress(e, 'assetName')}
                      placeholder={t('common.typeToSearch')}
                      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">
                        {t('common.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">
                      {t('commonFields.serialNumber')}
                    </label>
                    <input
                      type="text"
                      value={tempSerialNumber}
                      onChange={(e) => handleSerialNumberChange(e.target.value)}
                      onKeyDown={(e) => handleKeyPress(e, 'serialNumber')}
                      placeholder={t('common.typeToSearch')}
                      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">
                        {t('common.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={t('assets.selectHospital')}
                      doctype="Company"
                      value={filterCompany}
                      onChange={(val) => setFilterCompany(val)}
                      placeholder={t('linkField.selectLabel', { label: t('assets.selectHospital') })}
                      disabled={false}
                      compact={true}
                      filters={{ domain: 'Healthcare' }}
                    />
                    {filterCompany && (
                      <button
                        onClick={() => setFilterCompany('')}
                        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">
                      {t('assets.deviceStatus')}
                    </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="">{t('filters.allStatuses')}</option>
                      <option value="Up">✓ {t('assets.status.up')}</option>
                      <option value="Down">⚠ {t('assets.status.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-[58]">
                    <LinkField
                      label={t('filters.location')}
                      doctype="Location"
                      value={filterLocation}
                      onChange={(val) => setFilterLocation(val)}
                      placeholder={t('linkField.selectLabel', { label: t('filters.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-[57]">
                    <LinkField
                      label={t('filters.dept')}
                      doctype="Department"
                      value={filterDepartment}
                      onChange={(val) => setFilterDepartment(val)}
                      placeholder={t('linkField.selectLabel', { label: t('filters.dept') })}
                      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-[56]">
                    <LinkField
                      label={t('filters.modality')}
                      doctype="Modality"
                      value={filterModality}
                      onChange={(val) => setFilterModality(val)}
                      placeholder={t('linkField.selectLabel', { label: t('filters.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-[55]">
                    <LinkField
                      label={t('filters.mfr')}
                      doctype="Manufacturer"
                      value={filterManufacturer}
                      onChange={(val) => setFilterManufacturer(val)}
                      placeholder={t('linkField.selectLabel', { label: t('filters.mfr') })}
                      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-[54]">
                    <LinkField
                      label={t('filters.supplier')}
                      doctype="Supplier"
                      value={filterSupplier}
                      onChange={(val) => setFilterSupplier(val)}
                      placeholder={t('linkField.selectLabel', { label: t('filters.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">
              {t('common.saveFilterPreset')}
            </h3>
            <input
              type="text"
              value={filterPresetName}
              onChange={(e) => setFilterPresetName(e.target.value)}
              onKeyDown={(e) => {
                if (e.key === 'Enter') {
                  e.preventDefault();
                  handleSaveFilterPreset();
                }
              }}
              placeholder={t('common.enterFilterNameExample')}
              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"
              >
                {t('common.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} />
                {t('common.saveFilter')}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* QR Print Modal */}
      <QRPrintModal
        isOpen={showQRPrintModal}
        onClose={() => setShowQRPrintModal(false)}
        selectedCount={selectedRows.size}
        totalCount={totalCount}
        pageCount={assets.length}
        onPrint={handlePrintQRs}
        isPrinting={isPrinting}
      />

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

      {/* ✅ Export Modal - Dynamic */}
      <DynamicExportModal
        isOpen={showExportModal}
        onClose={() => setShowExportModal(false)}
        doctype="Asset"

        selectedCount={selectedRows.size}
        pageCount={assets.length}
        totalCount={totalCount}

        pageData={assets}
        selectedRows={selectedRows}
        rowKey="name"

        onFetchAll={fetchAllAssetsForExport}
        fileNamePrefix="assets"

        defaultColumns={[
          'name', 'asset_name', 'custom_serial_number', 'company',
          'location', 'custom_device_status', 'modified'
        ]}

        hiddenColumns={['docstatus', 'idx', 'amended_from', 'naming_series']}
      />

      {/* 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">{t('common.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 ? t('common.deselectAllTitle') : t('common.selectAllTitle')}
                  >
                    {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">
                  {t('assets.table.assetName')}
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                  {t('assets.table.serialNo')}
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                  {t('assets.table.company')}
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                  {t('assets.table.location')}
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                  {t('assets.table.status')}
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                  {t('assets.table.updatedOn')}
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                  {t('assets.table.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>{t('assets.noAssetsFound')}</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"
                        >
                          {t('listPages.clearFilters')}
                        </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"
                        >
                          {t('assets.createFirstAsset')}
                        </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'
                        : getDeleteStatusRowClass(asset.custom_delete_status)
                    }`}
                    title={asset.custom_delete_status ? `Delete Status: ${asset.custom_delete_status}` : undefined}
                    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>
                      {/* {asset.custom_technical_department && (
                        <div className="text-xs text-blue-600 dark:text-blue-400 mt-0.5">
                          {asset.custom_technical_department}
                        </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={t('assets.viewDetails')}
                        >
                          <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={t('assets.editAsset')}
                        >
                          <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={t('assets.duplicateAsset')}
                        >
                          <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={t('assets.createWorkOrder')}
                        >
                          <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={t('assets.viewLinkedWOs')}
                        >
                          <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={t('assets.deleteConfirmTitle')}
                          disabled={mutationLoading}
                        >
                          <FaTrash />
                        </button> */}

                        <div onClick={(e) => e.stopPropagation()}>
                          <DeleteRequestButton
                            doctype="Asset"
                            docname={asset.name}
                            currentDeleteStatus={(asset.custom_delete_status ?? null) as DeleteStatus}
                            userRoles={userRoles}
                            isSystemManager={listIsSystemManager}
                            triggerMode
                            redirectOnDelete="/assets"
                            onStatusChange={() => refetch()}
                          />
                        </div>
                        
                        {/* 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={t('assets.moreActions')}
                          >
                            <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" />
                                {t('assets.createWorkOrder')}
                              </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" />
                                {t('assets.viewLinkedWOs')}
                              </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" />
                                {t('assets.exportAsJson')}
                              </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" />
                                {t('assets.printAsset')}
                              </button>
                            </div>
                          )}
                        </div>
                      </div>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>

        {/* Pagination */}
        <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">
                  {t('assets.deleteConfirmTitle')}
                </h3>
                <p className="text-sm text-gray-600 dark:text-gray-400 mb-4">
                  {t('assets.deleteConfirmMessage')}
                </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>{t('commonFields.assetId')}:</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}
                  >
                    {t('common.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>
                        {t('common.deleting')}
                      </>
                    ) : (
                      <>
                        <FaTrash />
                        {t('assets.deleteConfirmTitle')}
                      </>
                    )}
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Delete Confirmation Modal */}
      {/* {deleteConfirmOpen && (
        <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-xl shadow-2xl max-w-md w-full animate-scale-in">

            <div className="bg-gradient-to-r from-red-500 to-red-600 px-6 py-4 rounded-t-xl">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 rounded-full bg-white/20 flex items-center justify-center flex-shrink-0">
                  <FaTrash className="text-white text-lg" />
                </div>
                <div>
                  <h3 className="text-lg font-semibold text-white">
                    {t('assets.deleteConfirmTitle')}
                  </h3>
                  <p className="text-red-100 text-xs mt-0.5">This action cannot be undone</p>
                </div>
              </div>
            </div>

            <div className="p-6">
              <p className="text-sm text-gray-600 dark:text-gray-400 mb-4">
                {t('assets.deleteConfirmMessage')}
              </p>

              <div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-3 mb-4">
                <p className="text-xs text-red-800 dark:text-red-300">
                  <strong>{t('commonFields.assetId')}:</strong>{' '}
                  <span className="font-mono">{deleteConfirmOpen}</span>
                </p>
              </div>

              <div className="bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded-lg p-3 mb-5">
                <p className="text-xs text-amber-800 dark:text-amber-300 leading-relaxed">
                  ⚠️ All linked records will also be permanently removed — including
                  activity logs, movements, depreciation schedules, maintenance logs,
                  and repair records.
                </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={deleteLoading}
                >
                  {t('common.cancel')}
                </button>
                <button
                  onClick={() => handleDelete(deleteConfirmOpen)}
                  disabled={deleteLoading}
                  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:cursor-not-allowed"
                >
                  {deleteLoading ? (
                    <>
                      <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white" />
                      {t('common.deleting')}
                    </>
                  ) : (
                    <>
                      <FaTrash size={13} />
                      {t('assets.deleteConfirmTitle')}
                    </>
                  )}
                </button>
              </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;