import React, { useState, useEffect, useRef, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { 
  FaPlus, FaSearch, FaEdit, FaEye, FaTrash, FaEllipsisV, FaCalendarAlt, 
  FaFilter, FaChevronDown, FaChevronUp, FaTimes, FaFileExport, FaDownload,
  FaCheckSquare, FaSquare, FaFileExcel, FaFileCsv, FaPrint
} from 'react-icons/fa';
import * as XLSX from 'xlsx';
import { usePMSchedules, usePMScheduleMutations } from '../hooks/usePMSchedule';
import useUserHospitalFilter from '../hooks/useUserHospitalFilter';
import LinkField from '../components/LinkField';

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

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

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

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

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

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

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

  if (!isOpen) return null;

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

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

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

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

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

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

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

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

// ==================== PRINT MODAL COMPONENT ====================
interface PrintModalProps {
  isOpen: boolean;
  onClose: () => void;
  selectedItems: string[];
  onPrint: (format: string, letterhead: string, noLetterhead: boolean, pageSize: string) => void;
  isPrinting: boolean;
}

const PrintModal: React.FC<PrintModalProps> = ({
  isOpen,
  onClose,
  selectedItems,
  onPrint,
  isPrinting
}) => {
  const { t } = useTranslation();
  const [printFormat, setPrintFormat] = useState('');
  const [useLetterhead, setUseLetterhead] = useState(true);
  const [letterhead, setLetterhead] = useState('');
  const [pageSize, setPageSize] = useState('A4');
  const [printFormats, setPrintFormats] = useState<string[]>([]);
  const [letterheads, setLetterheads] = useState<string[]>([]);
  const [loadingFormats, setLoadingFormats] = useState(false);

  // Fetch print formats for PM Schedule Generator doctype
  useEffect(() => {
    if (isOpen) {
      fetchPrintFormats();
      fetchLetterheads();
    }
  }, [isOpen]);

  const fetchPrintFormats = async () => {
    setLoadingFormats(true);
    try {
      const response = await fetch('/api/method/frappe.client.get_list', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          doctype: 'Print Format',
          filters: { doc_type: 'PM Schedule Generator', disabled: 0 },
          fields: ['name'],
          limit_page_length: 0
        })
      });
      const data = await response.json();
      const formats = (data.message || []).map((f: any) => f.name);
      setPrintFormats(formats);
      if (formats.length > 0 && !printFormat) {
        setPrintFormat(formats[0]);
      }
    } catch (error) {
      console.error('Error fetching print formats:', error);
    } finally {
      setLoadingFormats(false);
    }
  };

  const fetchLetterheads = async () => {
    try {
      const response = await fetch('/api/method/frappe.client.get_list', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          doctype: 'Letter Head',
          filters: { disabled: 0 },
          fields: ['name'],
          limit_page_length: 0
        })
      });
      const data = await response.json();
      const heads = (data.message || []).map((l: any) => l.name);
      setLetterheads(heads);
      if (heads.length > 0 && !letterhead) {
        setLetterhead(heads[0]);
      }
    } catch (error) {
      console.error('Error fetching letterheads:', error);
    }
  };

  const handlePrint = () => {
    if (!printFormat) {
      alert('Please select a print format');
      return;
    }
    onPrint(printFormat, letterhead, !useLetterhead, pageSize);
  };

  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 max-h-[90vh] overflow-hidden animate-scale-in">
        {/* Header */}
        <div className="bg-gradient-to-r from-purple-500 to-purple-600 px-6 py-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              <FaPrint className="text-white text-xl" />
              <h3 className="text-lg font-semibold text-white">Print PM Schedules</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">
          {/* Selected Items Info */}
          <div className="mb-6 p-4 bg-purple-50 dark:bg-purple-900/20 rounded-lg border border-purple-200 dark:border-purple-700">
            <div className="flex items-center gap-2">
              <FaCheckSquare className="text-purple-600 dark:text-purple-400" />
              <span className="font-medium text-purple-800 dark:text-purple-300">
                {selectedItems.length} schedule{selectedItems.length !== 1 ? 's' : ''} selected for printing
              </span>
            </div>
            <div className="mt-2 text-sm text-purple-600 dark:text-purple-400 max-h-20 overflow-y-auto">
              {selectedItems.slice(0, 5).join(', ')}
              {selectedItems.length > 5 && ` and ${selectedItems.length - 5} more...`}
            </div>
          </div>

          {/* Print Format Selection */}
          <div className="mb-4">
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              Print Format <span className="text-red-500">*</span>
            </label>
            {loadingFormats ? (
              <div className="flex items-center gap-2 text-gray-500">
                <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-purple-500"></div>
                Loading formats...
              </div>
            ) : printFormats.length === 0 ? (
              <div className="text-amber-600 dark:text-amber-400 text-sm p-3 bg-amber-50 dark:bg-amber-900/20 rounded-lg">
                No print formats found for PM Schedule Generator. Please create one in ERPNext.
              </div>
            ) : (
              <select
                value={printFormat}
                onChange={(e) => setPrintFormat(e.target.value)}
                className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
              >
                <option value="">Select Print Format</option>
                {printFormats.map((format) => (
                  <option key={format} value={format}>{format}</option>
                ))}
              </select>
            )}
          </div>

          {/* Letterhead Options */}
          <div className="mb-4">
            <label className="flex items-center gap-2 cursor-pointer">
              <input
                type="checkbox"
                checked={useLetterhead}
                onChange={(e) => setUseLetterhead(e.target.checked)}
                className="rounded text-purple-600 focus:ring-purple-500"
              />
              <span className="text-sm font-medium text-gray-700 dark:text-gray-300">
                Use Letterhead
              </span>
            </label>
          </div>

          {useLetterhead && (
            <div className="mb-4">
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                Letterhead
              </label>
              <select
                value={letterhead}
                onChange={(e) => setLetterhead(e.target.value)}
                className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
              >
                <option value="">Default Letterhead</option>
                {letterheads.map((lh) => (
                  <option key={lh} value={lh}>{lh}</option>
                ))}
              </select>
            </div>
          )}

          {/* Page Size */}
          <div className="mb-6">
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              Page Size
            </label>
            <select
              value={pageSize}
              onChange={(e) => setPageSize(e.target.value)}
              className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
            >
              <option value="A4">A4</option>
              <option value="Letter">Letter</option>
              <option value="A3">A3</option>
              <option value="A5">A5</option>
              <option value="Legal">Legal</option>
            </select>
          </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">
          <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={handlePrint}
            disabled={!printFormat || isPrinting || selectedItems.length === 0}
            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>
                Preparing...
              </>
            ) : (
              <>
                <FaPrint />
                Print {selectedItems.length} Schedule{selectedItems.length !== 1 ? 's' : ''}
              </>
            )}
          </button>
        </div>
      </div>
    </div>
  );
};

// ==================== MAIN COMPONENT ====================
const PPMPlannerList: React.FC = () => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const [page, setPage] = useState(0);
  const [searchTerm, setSearchTerm] = useState('');
  const [deleteConfirmOpen, setDeleteConfirmOpen] = useState<string | null>(null);
  const [actionMenuOpen, setActionMenuOpen] = useState<string | null>(null);
  const dropdownRef = useRef<HTMLDivElement>(null);
  
  // Filters
  const [isFilterExpanded, setIsFilterExpanded] = useState(false);
  const { filterHospital, filtersLocked, handleHospitalChange } = useUserHospitalFilter();
  const [filterModality, setFilterModality] = useState('');
  const [filterManufacturer, setFilterManufacturer] = useState('');
  const [filterPeriodicity, setFilterPeriodicity] = useState('');
  
  // Row selection state
  const [selectedRows, setSelectedRows] = useState<Set<string>>(new Set());
  
  // Export modal state
  const [showExportModal, setShowExportModal] = useState(false);
  const [isExporting, setIsExporting] = useState(false);
  
  // Print modal state
  const [showPrintModal, setShowPrintModal] = useState(false);
  const [isPrinting, setIsPrinting] = useState(false);
  
  const limit = 20;

  // Export columns configuration
  const EXPORT_COLUMNS = [
    { key: 'name', label: t('commonFields.pmId'), default: true },
    { key: 'pm_for', label: t('commonFields.name'), default: true },
    { key: 'hospital', label: t('commonFields.hospital'), default: true },
    { key: 'modality', label: t('commonFields.modality'), default: true },
    { key: 'manufacturer', label: t('commonFields.manufacturer'), default: true },
    { key: 'periodicity', label: t('ppm.periodicity'), default: true },
    { key: 'maintenance_team', label: 'Maintenance Team', default: false },
    { key: 'docstatus', label: t('commonFields.status'), default: true },
    { key: 'creation', label: t('commonFields.createdOn'), default: false },
    { key: 'modified', label: t('commonFields.modifiedOn'), default: false },
    { key: 'owner', label: t('commonFields.createdBy'), default: false },
    { key: 'modified_by', label: t('commonFields.modifiedBy'), default: false },
  ];

  // Build filters
  const filters: Record<string, any> = {};
  if (filterHospital) filters['hospital'] = filterHospital;
  if (filterModality) filters['modality'] = filterModality;
  if (filterManufacturer) filters['manufacturer'] = filterManufacturer;
  if (filterPeriodicity) filters['periodicity'] = filterPeriodicity;
  
  const { pmSchedules, totalCount, hasMore, loading, error, refetch } = usePMSchedules(
    filters,
    limit,
    page * limit,
    'creation desc'
  );

  const { deletePMSchedule, loading: mutationLoading } = usePMScheduleMutations();

  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]);

  // Clear selection when filters/page change
  useEffect(() => {
    setSelectedRows(new Set());
  }, [filterHospital, filterModality, filterManufacturer, filterPeriodicity, searchTerm, page]);

  // Filter schedules by search term - defined early so export handlers can use it
  const filteredSchedules = pmSchedules.filter(schedule => {
    if (!searchTerm) return true;
    const term = searchTerm.toLowerCase();
    return (
      schedule.name?.toLowerCase().includes(term) ||
      schedule.pm_for?.toLowerCase().includes(term) ||
      schedule.hospital?.toLowerCase().includes(term) ||
      schedule.modality?.toLowerCase().includes(term) ||
      schedule.manufacturer?.toLowerCase().includes(term) ||
      schedule.maintenance_team?.toLowerCase().includes(term)
    );
  });

  // Selection helpers
  const handleSelectAll = () => {
    if (selectedRows.size === filteredSchedules.length) {
      setSelectedRows(new Set());
    } else {
      setSelectedRows(new Set(filteredSchedules.map(s => s.name)));
    }
  };

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

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

  // Fetch all schedules for export (bypassing pagination)
  const fetchAllSchedulesForExport = useCallback(async (): Promise<any[]> => {
    const allSchedules: any[] = [];
    let currentPage = 0;
    const pageSize = 100;
    let hasMoreData = true;

    while (hasMoreData) {
      try {
        const response = await fetch('/api/method/frappe.client.get_list', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            doctype: 'PM Schedule Generator',
            filters: filters,
            fields: ['*'],
            limit_start: currentPage * pageSize,
            limit_page_length: pageSize,
            order_by: 'creation desc'
          })
        });

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

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

    return allSchedules;
  }, [filters]);

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

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

      switch (scope) {
        case 'selected':
          dataToExport = filteredSchedules.filter(s => selectedRows.has(s.name));
          break;
        case 'all_on_page':
          dataToExport = filteredSchedules;
          break;
        case 'all_with_filters':
          dataToExport = await fetchAllSchedulesForExport();
          break;
      }

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

      // Process data - convert docstatus to readable format
      const processedData = dataToExport.map(item => {
        const processed = { ...item };
        if (columns.includes('docstatus')) {
          const status = getDocstatus(item);
          processed.docstatus = status === 1 ? 'Submitted' : status === 2 ? 'Cancelled' : 'Draft';
        }
        return processed;
      });

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

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

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

      } else if (format === 'excel') {
        // Create Excel workbook using SheetJS
        const worksheetData = [
          columnLabels,
          ...processedData.map(schedule =>
            columns.map(key => schedule[key] || '')
          )
        ];

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

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

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

  // Print handler - opens multi-PDF download URL
  const handlePrint = (format: string, letterhead: string, noLetterhead: boolean, pageSize: string) => {
    setIsPrinting(true);
    
    try {
      const selectedNames = Array.from(selectedRows);
      
      if (selectedNames.length === 0) {
        alert('No schedules selected for printing');
        return;
      }

      // Build the URL for frappe's multi-PDF download
      const baseUrl = window.location.origin;
      const params = new URLSearchParams();
      
      params.append('doctype', 'PM Schedule Generator');
      params.append('name', JSON.stringify(selectedNames));
      params.append('format', format);
      params.append('no_letterhead', noLetterhead ? '1' : '0');
      
      if (letterhead && !noLetterhead) {
        params.append('letterhead', letterhead);
      }
      
      params.append('options', JSON.stringify({ 'page-size': pageSize }));

      const printUrl = `${baseUrl}/api/method/frappe.utils.print_format.download_multi_pdf?${params.toString()}`;
      
      // Open in new tab to download/print
      window.open(printUrl, '_blank');
      
      setShowPrintModal(false);
      
    } catch (error) {
      console.error('Print failed:', error);
      alert(`Print failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
    } finally {
      setIsPrinting(false);
    }
  };

  const handleCreateNew = () => {
    navigate('/ppm-planner/new');
  };

  const handleView = (scheduleName: string) => {
    navigate(`/ppm-planner/${scheduleName}`);
  };

  const handleEdit = (scheduleName: string) => {
    navigate(`/ppm-planner/${scheduleName}`);
  };

  const handleDelete = async (scheduleName: string) => {
    try {
      await deletePMSchedule(scheduleName);
      refetch();
      setDeleteConfirmOpen(null);
    } catch (err) {
      console.error('Error deleting PM Schedule:', err);
      alert('Failed to delete PM Schedule');
    }
  };

  const handleClearFilters = () => {
    if (!filtersLocked) {
      handleHospitalChange('');
    }
    setFilterModality('');
    setFilterManufacturer('');
    setFilterPeriodicity('');
    setPage(0);
  };

  // Helper function for docstatus
  const getDocstatus = (schedule: any): number => {
    if (schedule.docstatus !== undefined) {
      return Number(schedule.docstatus);
    }
    if (schedule.maintenance_entries?.length > 0) {
      return Number(schedule.maintenance_entries[0].docstatus);
    }
    return 0;
  };

  const hasActiveFilters = filterHospital || filterModality || filterManufacturer || filterPeriodicity;
  const activeFilterCount = [filterHospital, filterModality, filterManufacturer, filterPeriodicity].filter(Boolean).length;

  const totalPages = Math.ceil(totalCount / limit);

  return (
    <div className="flex flex-col h-screen bg-gray-50 dark:bg-gray-900">
      {/* Header */}
      <div className="flex-shrink-0 bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700 px-4 py-3 lg:px-6">
        <div className="flex justify-between items-center mb-3">
          <div className="flex items-center gap-3">
            <FaCalendarAlt className="text-blue-600 dark:text-blue-400" size={24} />
            <div>
              <h1 className="text-xl font-bold text-gray-800 dark:text-white">{t('sidebar.ppmPlanner')}</h1>
              <p className="text-xs text-gray-600 dark:text-gray-400">
                {t('ppm.manageSchedules')}
                {selectedRows.size > 0 && (
                  <span className="ml-2 text-blue-600 dark:text-blue-400">
                    • {selectedRows.size} selected
                  </span>
                )}
              </p>
            </div>
          </div>
          <div className="flex gap-2">
            {/* Export Button */}
            <button
              onClick={() => setShowExportModal(true)}
              className="px-3 py-1.5 bg-green-600 hover:bg-green-700 text-white rounded-lg transition-colors flex items-center gap-2 text-sm"
              disabled={totalCount === 0}
            >
              <FaFileExport />
              <span>{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>
            {/* Print Button */}
            <button
              onClick={() => setShowPrintModal(true)}
              className="px-3 py-1.5 bg-purple-600 hover:bg-purple-700 text-white rounded-lg transition-colors flex items-center gap-2 text-sm disabled:opacity-50 disabled:cursor-not-allowed"
              disabled={selectedRows.size === 0}
              title={selectedRows.size === 0 ? 'Select schedules to print' : `Print ${selectedRows.size} selected`}
            >
              <FaPrint />
              <span>Print</span>
              {selectedRows.size > 0 && (
                <span className="bg-white/20 px-1.5 py-0.5 rounded text-xs">
                  {selectedRows.size}
                </span>
              )}
            </button>
            <button
              onClick={handleCreateNew}
              className="px-3 py-1.5 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors flex items-center gap-2 text-sm"
            >
              <FaPlus />
              <span>{t('ppm.addPPM')}</span>
            </button>
          </div>
        </div>

        {/* Search and Filters */}
        <div className="flex gap-2">
          <div className="flex-1 relative">
            <FaSearch className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" size={14} />
            <input
              type="text"
              placeholder={t('listPages.searchPlaceholder')}
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="w-full pl-9 pr-3 py-1.5 text-sm border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
            />
          </div>
          <button
            onClick={() => setIsFilterExpanded(!isFilterExpanded)}
            className={`px-3 py-1.5 border rounded-lg transition-colors flex items-center gap-2 text-sm ${
              hasActiveFilters
                ? 'border-blue-500 bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400'
                : 'border-gray-300 dark:border-gray-600 hover:bg-gray-50 dark:hover:bg-gray-700 text-gray-700 dark:text-gray-300'
            }`}
          >
            <FaFilter />
            <span>{t('listPages.filters')}</span>
            {activeFilterCount > 0 && (
              <span className="bg-blue-600 text-white rounded-full w-5 h-5 flex items-center justify-center text-xs">
                {activeFilterCount}
              </span>
            )}
            {isFilterExpanded ? <FaChevronUp /> : <FaChevronDown />}
          </button>
        </div>

        {/* Filter Panel */}
        {isFilterExpanded && (
          <div className="mt-3 p-3 bg-gray-50 dark:bg-gray-700/50 rounded-lg border border-gray-200 dark:border-gray-600">
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-3">
              <div>
                <LinkField
                  label={t('commonFields.hospital')}
                  doctype="Company"
                  value={filterHospital}
                  onChange={handleHospitalChange}
                  placeholder={t('filters.allHospitals')}
                  filters={{ domain: "Healthcare" }}
                  disabled={filtersLocked}
                />
              </div>
              <div>
                <LinkField
                  label={t('commonFields.modality')}
                  doctype="Modality"
                  value={filterModality}
                  onChange={setFilterModality}
                  placeholder={t('filters.allModalities')}
                  filters={{}}
                />
              </div>
              <div>
                <LinkField
                  label={t('commonFields.manufacturer')}
                  doctype="Manufacturer"
                  value={filterManufacturer}
                  onChange={setFilterManufacturer}
                  placeholder={t('filters.allManufacturers')}
                  filters={{}}
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                  {t('ppm.periodicity')}
                </label>
                <select
                  value={filterPeriodicity}
                  onChange={(e) => setFilterPeriodicity(e.target.value)}
                  className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg 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('listPages.all')}</option>
                  <option value="Daily">Daily</option>
                  <option value="Weekly">Weekly</option>
                  <option value="Monthly">Monthly</option>
                  <option value="Quarterly">Quarterly</option>
                  <option value="Half-yearly">Half-yearly</option>
                  <option value="Yearly">Yearly</option>
                </select>
              </div>
            </div>
            {hasActiveFilters && (
              <div className="mt-4 flex justify-end">
                <button
                  onClick={handleClearFilters}
                  className="px-4 py-2 text-sm text-gray-600 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200 flex items-center gap-2"
                >
                  <FaTimes />
                  {t('listPages.clearFilters')}
                </button>
              </div>
            )}
          </div>
        )}
      </div>

      {/* Content */}
      <div className="flex-1 overflow-auto p-4 lg:p-5">
        {loading && page === 0 ? (
          <div className="flex items-center justify-center h-full">
            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500"></div>
            <span className="ml-3 text-gray-600 dark:text-gray-400">{t('listPages.loading')}</span>
          </div>
        ) : error ? (
          <div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-4">
            <p className="text-red-600 dark:text-red-400">{error}</p>
          </div>
        ) : filteredSchedules.length === 0 ? (
          <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-8 text-center">
            <FaCalendarAlt className="mx-auto text-gray-400 mb-4" size={48} />
            <h3 className="text-lg font-semibold text-gray-700 dark:text-gray-300 mb-2">
              {t('listPages.noResults')}
            </h3>
            <p className="text-gray-600 dark:text-gray-400 mb-4">
              {searchTerm || hasActiveFilters
                ? t('listPages.tryAdjustingFilters')
                : t('listPages.getStartedCreateFirst')}
            </p>
            {!searchTerm && !hasActiveFilters && (
              <button
                onClick={handleCreateNew}
                className="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors"
              >
                {t('ppm.addPPM')}
              </button>
            )}
          </div>
        ) : (
          <div className="bg-white dark:bg-gray-800 rounded-lg shadow overflow-hidden">
            <table className="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
              <thead className="bg-gray-50 dark:bg-gray-700">
                <tr>
                  {/* Select All Checkbox Column */}
                  <th className="px-4 py-3 text-left">
                    <button
                      onClick={handleSelectAll}
                      className="text-gray-500 dark:text-gray-400 hover:text-blue-600 dark:hover:text-blue-400 transition-colors"
                      title={isAllSelected ? "Deselect all" : "Select all"}
                    >
                      {isAllSelected ? (
                        <FaCheckSquare className="text-blue-600 dark:text-blue-400" size={18} />
                      ) : isSomeSelected ? (
                        <div className="relative">
                          <FaSquare size={18} />
                          <div className="absolute inset-0 flex items-center justify-center">
                            <div className="w-2 h-0.5 bg-current"></div>
                          </div>
                        </div>
                      ) : (
                        <FaSquare size={18} />
                      )}
                    </button>
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                    {t('commonFields.pmId')}
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                    {t('commonFields.name')}
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                    {t('commonFields.hospital')}
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                    {t('commonFields.modality')}
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                    {t('commonFields.manufacturer')}
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                    {t('ppm.periodicity')}
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                    {t('commonFields.status')}
                  </th>
                  <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                    {t('listPages.actions')}
                  </th>
                </tr>
              </thead>
              <tbody className="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
                {filteredSchedules.map((schedule) => (
                  <tr 
                    key={schedule.name} 
                    className={`hover:bg-gray-50 dark:hover:bg-gray-700/50 transition-colors ${
                      selectedRows.has(schedule.name) ? 'bg-blue-50 dark:bg-blue-900/20' : ''
                    }`}
                  >
                    {/* Row Checkbox */}
                    <td className="px-4 py-4">
                      <button
                        onClick={() => handleSelectRow(schedule.name)}
                        className="text-gray-500 dark:text-gray-400 hover:text-blue-600 dark:hover:text-blue-400 transition-colors"
                      >
                        {selectedRows.has(schedule.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">
                      <button
                        onClick={() => handleView(schedule.name)}
                        className="text-blue-600 dark:text-blue-400 hover:underline font-medium"
                      >
                        {schedule.name}
                      </button>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-700 dark:text-gray-300">
                      {schedule.pm_for || '-'}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-700 dark:text-gray-300">
                      {schedule.hospital || '-'}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-700 dark:text-gray-300">
                      {schedule.modality || '-'}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-700 dark:text-gray-300">
                      {schedule.manufacturer || '-'}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-700 dark:text-gray-300">
                      {schedule.periodicity || '-'}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      {(() => {
                        const status = getDocstatus(schedule);
                        return (
                          <span className={`px-2 py-1 text-xs font-semibold rounded-full ${
                            status === 1
                              ? 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400'
                              : status === 0
                              ? 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400'
                              : 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-400'
                          }`}>
                            {status === 1 ? 'Submitted' : status === 2 ? 'Cancelled' : 'Draft'}
                          </span>
                        );
                      })()}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                      <div className="relative inline-block" ref={actionMenuOpen === schedule.name ? dropdownRef : null}>
                        <button
                          onClick={() => setActionMenuOpen(actionMenuOpen === schedule.name ? null : schedule.name)}
                          className="text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200 p-2"
                        >
                          <FaEllipsisV />
                        </button>
                        {actionMenuOpen === schedule.name && (
                          <div className="absolute right-0 mt-2 w-48 bg-white dark:bg-gray-700 rounded-lg shadow-lg border border-gray-200 dark:border-gray-600 z-10">
                            <button
                              onClick={() => {
                                handleView(schedule.name);
                                setActionMenuOpen(null);
                              }}
                              className="w-full px-4 py-2 text-left text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-600 flex items-center gap-2"
                            >
                              <FaEye /> {t('listPages.view')}
                            </button>
                            <button
                              onClick={() => {
                                handleEdit(schedule.name);
                                setActionMenuOpen(null);
                              }}
                              className="w-full px-4 py-2 text-left text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-600 flex items-center gap-2"
                            >
                              <FaEdit /> {t('listPages.edit')}
                            </button>
                            <button
                              onClick={() => {
                                setDeleteConfirmOpen(schedule.name);
                                setActionMenuOpen(null);
                              }}
                              className="w-full px-4 py-2 text-left text-sm text-red-600 dark:text-red-400 hover:bg-gray-100 dark:hover:bg-gray-600 flex items-center gap-2"
                            >
                              <FaTrash /> {t('listPages.delete')}
                            </button>
                          </div>
                        )}
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>

            {/* Pagination */}
            {totalPages > 1 && (
              <div className="px-6 py-4 border-t border-gray-200 dark:border-gray-700 flex items-center justify-between">
                <div className="text-sm text-gray-600 dark:text-gray-400">
                  {t('listPages.showing')} {page * limit + 1} {t('listPages.to')} {Math.min((page + 1) * limit, totalCount)} {t('listPages.of')} {totalCount} {t('listPages.results')}
                </div>
                <div className="flex gap-2">
                  <button
                    onClick={() => setPage(Math.max(0, page - 1))}
                    disabled={page === 0}
                    className="px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 disabled:opacity-50 disabled:cursor-not-allowed text-gray-700 dark:text-gray-300"
                  >
                    Previous
                  </button>
                  <button
                    onClick={() => setPage(page + 1)}
                    disabled={!hasMore}
                    className="px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 disabled:opacity-50 disabled:cursor-not-allowed text-gray-700 dark:text-gray-300"
                  >
                    Next
                  </button>
                </div>
              </div>
            )}
          </div>
        )}
      </div>

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

      {/* Print Modal */}
      <PrintModal
        isOpen={showPrintModal}
        onClose={() => setShowPrintModal(false)}
        selectedItems={Array.from(selectedRows)}
        onPrint={handlePrint}
        isPrinting={isPrinting}
      />

      {/* Delete Confirmation Modal */}
      {deleteConfirmOpen && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl p-6 max-w-md">
            <h3 className="text-lg font-semibold text-gray-800 dark:text-white mb-4">
              {t('confirmations.confirmDelete')}
            </h3>
            <p className="text-gray-600 dark:text-gray-400 mb-6">
              {t('confirmations.cannotUndo')}
            </p>
            <div className="flex gap-3 justify-end">
              <button
                onClick={() => setDeleteConfirmOpen(null)}
                className="px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 text-gray-700 dark:text-gray-300"
                disabled={mutationLoading}
              >
                {t('common.cancel')}
              </button>
              <button
                onClick={() => handleDelete(deleteConfirmOpen)}
                className="px-4 py-2 bg-red-600 hover:bg-red-700 text-white rounded-lg transition-colors"
                disabled={mutationLoading}
              >
                {mutationLoading ? t('common.deleting') : t('common.delete')}
              </button>
            </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;
        }
      `}</style>
    </div>
  );
};

export default PPMPlannerList;