import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { usePMScheduleDetails, usePMScheduleMutations } from '../hooks/usePMSchedule';
import { useAssetMaintenanceLogs } from '../hooks/useAssetMaintenance';
import { FaArrowLeft, FaSave, FaEdit, FaCalendarAlt, FaTrash, FaSpinner, FaCheckCircle, FaHistory, FaUser, FaClock, FaClipboardCheck, FaThumbsUp } from 'react-icons/fa';
import LinkField from '../components/LinkField';
import useDefaultHospital from '../hooks/useDefaultHospital';

// Activity Log interface
interface ActivityLog {
  id: string;
  user: string;
  timestamp: string;
  action: 'Applied' | 'Approved' | 'Rejected';
  entriesCount: number;
  completionDate?: string;
  earlyReason?: string;
  entries?: string[];
}

// Workflow state type
type WorkflowState = 'Planned' | 'Applied' | 'Approved';

const PPMPlannerDetail: React.FC = () => {
  const { t } = useTranslation();
  const { scheduleName } = useParams<{ scheduleName: string }>();
  const navigate = useNavigate();
  
  const { pmSchedule, loading, error, refetch } = usePMScheduleDetails(scheduleName || null);
  const { updatePMSchedule, deletePMSchedule, submitPMSchedule, cancelPMSchedule, loading: saving } = usePMScheduleMutations();
  
  // Fetch all maintenance logs to link with assets
  const { logs: maintenanceLogs, refetch: refetchLogs } = useAssetMaintenanceLogs({}, 10000, 0);
  
  const [isEditing, setIsEditing] = useState(false);
  const [deleteConfirmOpen, setDeleteConfirmOpen] = useState(false);
  
  // Apply (Mark Complete) Modal State
  const [showApplyModal, setShowApplyModal] = useState(false);
  const [completionDate, setCompletionDate] = useState('');
  const [earlyCompletionReason, setEarlyCompletionReason] = useState('');
  const [isEarlyCompletion, setIsEarlyCompletion] = useState(false);
  const [applyingComplete, setApplyingComplete] = useState(false);
  const [selectedEntriesToApply, setSelectedEntriesToApply] = useState<Set<string>>(new Set());
  
  // Approve Modal State
  const [showApproveModal, setShowApproveModal] = useState(false);
  const [approving, setApproving] = useState(false);
  const [selectedEntriesToApprove, setSelectedEntriesToApprove] = useState<Set<string>>(new Set());
  
  // Entries States
  const [plannedEntries, setPlannedEntries] = useState<any[]>([]);
  const [appliedEntries, setAppliedEntries] = useState<any[]>([]);
  
  // Activity Log State
  const [activityLogs, setActivityLogs] = useState<ActivityLog[]>([]);
  
  // Current User State
  const [currentUser, setCurrentUser] = useState<string>('');

  const [formData, setFormData] = useState({
    hospital: '',
    modality: '',
    device_status: '',
    start_date: '',
    end_date: '',
    maintenance_team: '',
    maintenance_manager: '',
    periodicity: 'Monthly',
    assign_to: '',
    due_date: '',
    next_pm_date: '',
    manufacturer: '',
    model: '',
    pm_for: '',
    asset_name: '',
    no_of_pms: ''
  });

  useDefaultHospital(setFormData, {
    enabled: !!pmSchedule && !pmSchedule.hospital,
    fields: ['hospital'],
  });

  // Fetch current user on mount
  useEffect(() => {
    const fetchCurrentUser = async () => {
      try {
        const response = await fetch('/api/method/frappe.auth.get_logged_user', {
          method: 'GET',
          credentials: 'include'
        });
        const data = await response.json();
        if (data.message) {
          setCurrentUser(data.message);
        }
      } catch (error) {
        console.error('Error fetching current user:', error);
      }
    };
    fetchCurrentUser();
  }, []);

  // Load activity logs from localStorage
  useEffect(() => {
    if (scheduleName) {
      const savedLogs = localStorage.getItem(`ppm_activity_${scheduleName}`);
      if (savedLogs) {
        setActivityLogs(JSON.parse(savedLogs));
      }
    }
  }, [scheduleName]);

  // Find planned and applied maintenance entries when logs change
  useEffect(() => {
    if (pmSchedule?.maintenance_entries && maintenanceLogs.length > 0) {
      const planned: any[] = [];
      const applied: any[] = [];
      
      pmSchedule.maintenance_entries.forEach((entry: any) => {
        const assetLogs = maintenanceLogs.filter(log => log.asset_name === entry.asset);
        
        // Separate by workflow state
        assetLogs.forEach(log => {
          if (log.workflow_state === 'Applied') {
            applied.push({
              ...log,
              asset_display_name: entry.asset_name || entry.asset // Add asset display name
            });
          } else if (log.maintenance_status === 'Planned' && (!log.workflow_state || log.workflow_state === 'Draft')) {
            planned.push({
              ...log,
              asset_display_name: entry.asset_name || entry.asset // Add asset display name
            });
          }
        });
      });
      
      setPlannedEntries(planned);
      setAppliedEntries(applied);
    }
  }, [pmSchedule, maintenanceLogs]);

  // Helper function to calculate next PM date for an asset
  const calculateNextPMDateForAsset = (assetName: string, periodicity: string, defaultDueDate: string): string | null => {
    if (!periodicity || !defaultDueDate) {
      return null;
    }

    const assetLogs = maintenanceLogs.filter(log => log.asset_name === assetName);
    
    const completedLogs = assetLogs
      .filter(log => (log.maintenance_status === 'Completed' || log.workflow_state === 'Approved') && log.completion_date)
      .sort((a, b) => {
        const dateA = new Date(a.completion_date || 0).getTime();
        const dateB = new Date(b.completion_date || 0).getTime();
        return dateB - dateA;
      });

    if (completedLogs.length === 0) {
      return defaultDueDate;
    }

    const lastCompletedLog = completedLogs[0];
    const lastDueDate = new Date(lastCompletedLog.due_date || defaultDueDate);
    const lastCompletionDate = new Date(lastCompletedLog.completion_date!);
    
    const delayDays = Math.max(0, Math.floor((lastCompletionDate.getTime() - lastDueDate.getTime()) / (1000 * 60 * 60 * 24)));
    
    const nextDueDate = new Date(lastCompletionDate);
    
    switch (periodicity) {
      case 'Daily':
        nextDueDate.setDate(nextDueDate.getDate() + 1);
        break;
      case 'Weekly':
        nextDueDate.setDate(nextDueDate.getDate() + 7);
        break;
      case 'Monthly':
        nextDueDate.setMonth(nextDueDate.getMonth() + 1);
        break;
      case 'Quarterly':
        nextDueDate.setMonth(nextDueDate.getMonth() + 3);
        break;
      case 'Half-yearly':
        nextDueDate.setMonth(nextDueDate.getMonth() + 6);
        break;
      case 'Yearly':
        nextDueDate.setFullYear(nextDueDate.getFullYear() + 1);
        break;
      case '2 Yearly':
        nextDueDate.setFullYear(nextDueDate.getFullYear() + 2);
        break;
      case '3 Yearly':
        nextDueDate.setFullYear(nextDueDate.getFullYear() + 3);
        break;
      default:
        return defaultDueDate;
    }
    
    nextDueDate.setDate(nextDueDate.getDate() + delayDays);
    
    const year = nextDueDate.getFullYear();
    const month = String(nextDueDate.getMonth() + 1).padStart(2, '0');
    const day = String(nextDueDate.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  };

  // ✅ FIXED: Calculate form-level Next PM Date from minimum due_date in pending entries
  useEffect(() => {
    if (maintenanceLogs.length > 0 && pmSchedule?.maintenance_entries) {
      // Get all pending entries (Planned or Applied) for assets in this schedule
      const pendingDueDates: string[] = [];
      
      pmSchedule.maintenance_entries.forEach((entry: any) => {
        const assetLogs = maintenanceLogs.filter(log => log.asset_name === entry.asset);
        
        // Get Planned and Applied logs with due_date
        assetLogs.forEach(log => {
          const isPlanned = log.maintenance_status === 'Planned' && (!log.workflow_state || log.workflow_state === 'Draft');
          const isApplied = log.workflow_state === 'Applied';
          
          if ((isPlanned || isApplied) && log.due_date) {
            pendingDueDates.push(log.due_date);
          }
        });
      });
      
      if (pendingDueDates.length > 0) {
        // Find the minimum (earliest) due date
        const earliestDueDate = pendingDueDates.sort((a, b) => 
          new Date(a).getTime() - new Date(b).getTime()
        )[0];
        
        console.log('📅 Pending due dates:', pendingDueDates);
        console.log('📅 Earliest (Next PM Date):', earliestDueDate);
        
        setFormData(prev => {
          if (prev.next_pm_date !== earliestDueDate) {
            return {
              ...prev,
              next_pm_date: earliestDueDate
            };
          }
          return prev;
        });
      } else {
        // No pending entries - show fallback or empty
        console.log('📅 No pending entries found - all completed');
        setFormData(prev => ({
          ...prev,
          next_pm_date: '' // Or keep pmSchedule.next_pm_date if you prefer
        }));
      }
    }
  }, [pmSchedule, maintenanceLogs]);

  useEffect(() => {
    if (pmSchedule) {
      setFormData({
        hospital: pmSchedule.hospital || '',
        modality: pmSchedule.modality || '',
        device_status: pmSchedule.device_status || '',
        start_date: pmSchedule.start_date || '',
        end_date: pmSchedule.end_date || '',
        maintenance_team: pmSchedule.maintenance_team || '',
        maintenance_manager: pmSchedule.maintenance_manager || '',
        periodicity: pmSchedule.periodicity || 'Monthly',
        assign_to: pmSchedule.assign_to || '',
        due_date: pmSchedule.due_date || '',
        next_pm_date: pmSchedule.next_pm_date || '',
        manufacturer: pmSchedule.manufacturer || '',
        model: pmSchedule.model || '',
        pm_for: pmSchedule.pm_for || '',
        asset_name: pmSchedule.asset_name || '',
        no_of_pms: pmSchedule.no_of_pms || ''
      });
    }
  }, [pmSchedule]);

  // Check if completion is early when date changes
  useEffect(() => {
    if (completionDate && formData.next_pm_date) {
      const completion = new Date(completionDate);
      const nextPM = new Date(formData.next_pm_date);
      setIsEarlyCompletion(completion < nextPM);
    } else {
      setIsEarlyCompletion(false);
    }
  }, [completionDate, formData.next_pm_date]);

  // Helper function to calculate end_date
  const calculateEndDate = (startDate: string, periodicity: string, noOfPms: string): string | null => {
    if (!startDate || !periodicity || !noOfPms) {
      return null;
    }

    const noOfPmsNum = parseInt(noOfPms, 10);
    if (isNaN(noOfPmsNum) || noOfPmsNum < 1) {
      return null;
    }

    const occurrences = noOfPmsNum - 1;
    if (occurrences < 0) {
      return null;
    }

    const start = new Date(startDate);
    const end = new Date(start);

    switch (periodicity) {
      case 'Daily':
        end.setDate(end.getDate() + occurrences);
        break;
      case 'Weekly':
        end.setDate(end.getDate() + (occurrences * 7));
        break;
      case 'Monthly':
        end.setMonth(end.getMonth() + occurrences);
        break;
      case 'Quarterly':
        end.setMonth(end.getMonth() + (occurrences * 3));
        break;
      case 'Half-yearly':
        end.setMonth(end.getMonth() + (occurrences * 6));
        break;
      case 'Yearly':
        end.setFullYear(end.getFullYear() + occurrences);
        break;
      case '2 Yearly':
        end.setFullYear(end.getFullYear() + (occurrences * 2));
        break;
      case '3 Yearly':
        end.setFullYear(end.getFullYear() + (occurrences * 3));
        break;
      default:
        return null;
    }

    const year = end.getFullYear();
    const month = String(end.getMonth() + 1).padStart(2, '0');
    const day = String(end.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  };

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target;
    
    setFormData(prev => {
      const updated = {
        ...prev,
        [name]: value
      };

      if (name === 'start_date' || name === 'periodicity' || name === 'no_of_pms') {
        const calculatedEndDate = calculateEndDate(
          name === 'start_date' ? value : prev.start_date,
          name === 'periodicity' ? value : prev.periodicity,
          name === 'no_of_pms' ? value : prev.no_of_pms
        );
        
        if (calculatedEndDate) {
          updated.end_date = calculatedEndDate;
        }
      }

      return updated;
    });
  };

  const handleSave = async () => {
    if (!scheduleName) return;
    
    try {
      await updatePMSchedule(scheduleName, formData);
      setIsEditing(false);
      refetch();
      alert('PPM Planner updated successfully');
    } catch (err) {
      console.error('Error updating PPM Planner:', err);
      alert('Failed to update PPM Planner');
    }
  };

  const handleDelete = async () => {
    if (!scheduleName) return;
    
    try {
      await deletePMSchedule(scheduleName);
      navigate('/ppm-planner');
    } catch (err) {
      console.error('Error deleting PPM Planner:', err);
      alert('Failed to delete PPM Planner');
    }
  };

  const handleSubmit = async () => {
    if (!scheduleName) return;
    
    try {
      await submitPMSchedule(scheduleName);
      refetch();
      alert('PPM Planner submitted successfully');
    } catch (err) {
      console.error('Error submitting PPM Planner:', err);
      alert('Failed to submit PPM Planner');
    }
  };

  const handleCancel = async () => {
    if (!scheduleName) return;
    
    try {
      await cancelPMSchedule(scheduleName);
      refetch();
      alert('PPM Planner cancelled successfully');
    } catch (err) {
      console.error('Error cancelling PPM Planner:', err);
      alert('Failed to cancel PPM Planner');
    }
  };

  // Open Apply (Mark Complete) Modal
  const handleOpenApplyModal = () => {
    if (plannedEntries.length === 0) {
      alert('No planned maintenance entries found to apply.');
      return;
    }
    
    const today = new Date().toISOString().split('T')[0];
    setCompletionDate(today);
    setEarlyCompletionReason('');
    // Select all entries by default
    setSelectedEntriesToApply(new Set(plannedEntries.map(e => e.name)));
    setShowApplyModal(true);
  };

  // Toggle single entry selection for Apply
  const toggleApplyEntrySelection = (entryName: string) => {
    setSelectedEntriesToApply(prev => {
      const newSet = new Set(prev);
      if (newSet.has(entryName)) {
        newSet.delete(entryName);
      } else {
        newSet.add(entryName);
      }
      return newSet;
    });
  };

  // Select all entries for Apply
  const selectAllApplyEntries = () => {
    setSelectedEntriesToApply(new Set(plannedEntries.map(e => e.name)));
  };

  // Deselect all entries for Apply
  const deselectAllApplyEntries = () => {
    setSelectedEntriesToApply(new Set());
  };

  // Handle Apply (Mark Complete) - Sets state to "Applied"
  const handleApply = async () => {
    if (!completionDate) {
      alert('Please enter a completion date.');
      return;
    }

    if (isEarlyCompletion && !earlyCompletionReason.trim()) {
      alert('Please provide a reason for early completion.');
      return;
    }

    if (selectedEntriesToApply.size === 0) {
      alert('Please select at least one entry to complete.');
      return;
    }

    setApplyingComplete(true);

    try {
      let successCount = 0;
      let failCount = 0;
      const appliedEntryNames: string[] = [];

      // Only process selected entries
      const entriesToProcess = plannedEntries.filter(e => selectedEntriesToApply.has(e.name));

      // Update each selected planned entry to "Applied" state
      for (const entry of entriesToProcess) {
        try {
          const updateData: any = {
            maintenance_status: 'Completed',
            workflow_state: 'Applied',
            completion_date: completionDate
          };

          if (isEarlyCompletion && earlyCompletionReason) {
            updateData.custom_early_completion_reason = earlyCompletionReason;
            updateData.custom_early_completion = 'Yes';
          }

          const response = await fetch('/api/method/frappe.client.set_value', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            },
            credentials: 'include',
            body: JSON.stringify({
              doctype: 'Asset Maintenance Log',
              name: entry.name,
              fieldname: updateData
            })
          });

          const result = await response.json();
          
          if (result.message) {
            successCount++;
            appliedEntryNames.push(entry.name);
          } else {
            failCount++;
            console.error(`Failed to apply ${entry.name}:`, result);
          }
        } catch (err) {
          failCount++;
          console.error(`Error applying ${entry.name}:`, err);
        }
      }

      // Log the activity
      const newActivity: ActivityLog = {
        id: Date.now().toString(),
        user: currentUser || 'Unknown User',
        timestamp: new Date().toISOString(),
        action: 'Applied',
        entriesCount: successCount,
        completionDate: completionDate,
        earlyReason: isEarlyCompletion ? earlyCompletionReason : undefined,
        entries: appliedEntryNames
      };

      const updatedLogs = [newActivity, ...activityLogs];
      setActivityLogs(updatedLogs);
      
      if (scheduleName) {
        localStorage.setItem(`ppm_activity_${scheduleName}`, JSON.stringify(updatedLogs));
      }

      setShowApplyModal(false);
      setCompletionDate('');
      setEarlyCompletionReason('');
      setSelectedEntriesToApply(new Set());
      
      refetchLogs();
      refetch();

      if (failCount === 0) {
        alert(`Successfully applied ${successCount} maintenance entries. They are now pending approval.`);
      } else {
        alert(`Applied ${successCount} entries. Failed to apply ${failCount} entries.`);
      }

    } catch (err) {
      console.error('Error applying entries:', err);
      alert('Failed to apply entries.');
    } finally {
      setApplyingComplete(false);
    }
  };

  // Open Approve Modal
  const handleOpenApproveModal = () => {
    if (appliedEntries.length === 0) {
      alert('No entries pending approval.');
      return;
    }
    // Select all entries by default
    setSelectedEntriesToApprove(new Set(appliedEntries.map(e => e.name)));
    setShowApproveModal(true);
  };

  // Toggle single entry selection for Approve
  const toggleApproveEntrySelection = (entryName: string) => {
    setSelectedEntriesToApprove(prev => {
      const newSet = new Set(prev);
      if (newSet.has(entryName)) {
        newSet.delete(entryName);
      } else {
        newSet.add(entryName);
      }
      return newSet;
    });
  };

  // Select all entries for Approve
  const selectAllApproveEntries = () => {
    setSelectedEntriesToApprove(new Set(appliedEntries.map(e => e.name)));
  };

  // Deselect all entries for Approve
  const deselectAllApproveEntries = () => {
    setSelectedEntriesToApprove(new Set());
  };

  // ✅ FIXED: Handle Approve - Sets state to "Approved" and submits (docstatus = 1)
  const handleApprove = async () => {
    if (selectedEntriesToApprove.size === 0) {
      alert('Please select at least one entry to approve.');
      return;
    }

    setApproving(true);

    try {
      let successCount = 0;
      let failCount = 0;
      const approvedEntryNames: string[] = [];

      // Only process selected entries
      const entriesToProcess = appliedEntries.filter(e => selectedEntriesToApprove.has(e.name));

      for (const entry of entriesToProcess) {
        try {
          // Step 1: First get the full document
          const getDocResponse = await fetch(`/api/resource/Asset Maintenance Log/${encodeURIComponent(entry.name)}`, {
            method: 'GET',
            headers: {
              'Content-Type': 'application/json',
            },
            credentials: 'include'
          });

          const docData = await getDocResponse.json();
          
          if (!docData.data) {
            console.error(`Failed to get document ${entry.name}`);
            failCount++;
            continue;
          }

          // Step 2: Update the document with workflow_state = Approved and docstatus = 1
          const fullDoc = {
            ...docData.data,
            workflow_state: 'Approved',
            docstatus: 1
          };

          // Step 3: Save the document with docstatus = 1 (submit)
          const saveResponse = await fetch(`/api/resource/Asset Maintenance Log/${encodeURIComponent(entry.name)}`, {
            method: 'PUT',
            headers: {
              'Content-Type': 'application/json',
            },
            credentials: 'include',
            body: JSON.stringify(fullDoc)
          });

          const saveResult = await saveResponse.json();

          if (saveResult.data && saveResult.data.docstatus === 1) {
            successCount++;
            approvedEntryNames.push(entry.name);
            console.log(`✅ Successfully approved and submitted: ${entry.name}`);
          } else {
            // Try alternative method using frappe.call
            console.log(`Trying alternative submit method for ${entry.name}...`);
            
            const submitResponse = await fetch('/api/method/frappe.desk.form.utils.get_next', {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json',
              },
              credentials: 'include',
              body: JSON.stringify({
                doctype: 'Asset Maintenance Log',
                name: entry.name,
                workflow_action: 'Approve'
              })
            });

            // Alternative: Direct submit via run_doc_method
            const directSubmitResponse = await fetch('/api/method/run_doc_method', {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json',
              },
              credentials: 'include',
              body: JSON.stringify({
                dt: 'Asset Maintenance Log',
                dn: entry.name,
                method: 'submit'
              })
            });

            const directSubmitResult = await directSubmitResponse.json();
            
            if (directSubmitResult.message || !directSubmitResult.exc) {
              successCount++;
              approvedEntryNames.push(entry.name);
              console.log(`✅ Successfully submitted via run_doc_method: ${entry.name}`);
            } else {
              failCount++;
              console.error(`Failed to submit ${entry.name}:`, directSubmitResult);
            }
          }
        } catch (err) {
          failCount++;
          console.error(`Error approving ${entry.name}:`, err);
        }
      }

      // Log the activity
      const newActivity: ActivityLog = {
        id: Date.now().toString(),
        user: currentUser || 'Unknown User',
        timestamp: new Date().toISOString(),
        action: 'Approved',
        entriesCount: successCount,
        entries: approvedEntryNames
      };

      const updatedLogs = [newActivity, ...activityLogs];
      setActivityLogs(updatedLogs);
      
      if (scheduleName) {
        localStorage.setItem(`ppm_activity_${scheduleName}`, JSON.stringify(updatedLogs));
      }

      setShowApproveModal(false);
      setSelectedEntriesToApprove(new Set());
      
      // Wait a moment for Frappe to process and create next logs
      setTimeout(() => {
        refetchLogs();
        refetch();
      }, 1000);

      if (failCount === 0) {
        alert(`Successfully approved and submitted ${successCount} maintenance entries. New planned entries should be created automatically.`);
      } else {
        alert(`Approved ${successCount} entries. Failed to approve ${failCount} entries.`);
      }

    } catch (err) {
      console.error('Error approving entries:', err);
      alert('Failed to approve entries.');
    } finally {
      setApproving(false);
    }
  };

  // Get workflow state badge color
  const getWorkflowStateBadge = (state: string) => {
    switch (state) {
      case 'Planned':
        return 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400';
      case 'Applied':
        return 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400';
      case 'Approved':
        return 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400';
      default:
        return 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300';
    }
  };

  // ✅ NEW: Filter maintenance entries to show only Planned and Applied (not Approved)
  const getFilteredEntriesForAsset = (assetId: string) => {
    const assetLogs = maintenanceLogs.filter(log => log.asset_name === assetId);
    
    // Filter: Only show Planned or Applied entries (not Approved/Submitted)
    return assetLogs.filter(log => {
      const isPlanned = log.maintenance_status === 'Planned' && (!log.workflow_state || log.workflow_state === 'Draft');
      const isApplied = log.workflow_state === 'Applied';
      return isPlanned || isApplied;
    });
  };

  // ✅ NEW: Check if an asset has any pending entries (Planned or Applied)
  const assetHasPendingEntries = (assetId: string) => {
    const filteredLogs = getFilteredEntriesForAsset(assetId);
    return filteredLogs.length > 0;
  };

  // ✅ NEW: Get filtered maintenance entries (only show assets with Planned/Applied logs)
  const getFilteredMaintenanceEntries = () => {
    if (!pmSchedule?.maintenance_entries) return [];
    
    return pmSchedule.maintenance_entries.filter((entry: any) => {
      return assetHasPendingEntries(entry.asset);
    });
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-screen bg-gray-50 dark:bg-gray-900">
        <div className="flex items-center gap-3">
          <FaSpinner className="animate-spin text-blue-600" size={24} />
          <span className="text-gray-600 dark:text-gray-400">Loading PPM Planner...</span>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex items-center justify-center h-screen bg-gray-50 dark:bg-gray-900">
        <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>
          <button
            onClick={() => navigate('/ppm-planner')}
            className="mt-4 px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors"
          >
            Back to List
          </button>
        </div>
      </div>
    );
  }

  if (!pmSchedule) {
    return (
      <div className="flex items-center justify-center h-screen bg-gray-50 dark:bg-gray-900">
        <div className="bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg p-4">
          <p className="text-yellow-600 dark:text-yellow-400">PPM Planner not found</p>
          <button
            onClick={() => navigate('/ppm-planner')}
            className="mt-4 px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors"
          >
            Back to List
          </button>
        </div>
      </div>
    );
  }

  const isDraft = pmSchedule.docstatus === 0;
  const isSubmitted = pmSchedule.docstatus === 1;
  const isCancelled = pmSchedule.docstatus === 2;

  // ✅ Use filtered entries
  const filteredMaintenanceEntries = getFilteredMaintenanceEntries();

  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-6 py-4">
        <div className="flex justify-between items-center mb-4">
          <div className="flex items-center gap-3">
            <button
              onClick={() => navigate('/ppm-planner')}
              className="p-2 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
            >
              <FaArrowLeft className="text-gray-600 dark:text-gray-400" />
            </button>
            <FaCalendarAlt className="text-blue-600 dark:text-blue-400" size={28} />
            <div>
              <h1 className="text-2xl font-bold text-gray-800 dark:text-white">{pmSchedule.name}</h1>
              <p className="text-sm text-gray-600 dark:text-gray-400">
                PPM Planner Details
              </p>
            </div>
            <span className={`ml-4 px-3 py-1 text-sm font-semibold rounded-full ${
              isSubmitted
                ? 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400'
                : isDraft
                ? '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'
            }`}>
              {isSubmitted ? 'Submitted' : isDraft ? 'Draft' : 'Cancelled'}
            </span>
          </div>
          
          <div className="flex gap-2">
            {/* Workflow Action Buttons */}
            {isSubmitted && (
              <div className="flex gap-2 mr-4 pr-4 border-r border-gray-300 dark:border-gray-600">
                {/* Apply Button - Show when there are planned entries */}
                {plannedEntries.length > 0 && (
                  <button
                    onClick={handleOpenApplyModal}
                    className="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors flex items-center gap-2"
                  >
                    <FaClipboardCheck />
                    Bulk Complete({plannedEntries.length})
                  </button>
                )}
                
                {/* Approve Button - Show when there are applied entries */}
                {appliedEntries.length > 0 && (
                  <button
                    onClick={handleOpenApproveModal}
                    className="px-4 py-2 bg-green-600 hover:bg-green-700 text-white rounded-lg transition-colors flex items-center gap-2"
                  >
                    <FaThumbsUp />
                    Approve ({appliedEntries.length})
                  </button>
                )}
              </div>
            )}
            
            {isDraft && !isEditing && (
              <>
                <button
                  onClick={() => setIsEditing(true)}
                  className="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors flex items-center gap-2"
                >
                  <FaEdit />
                  Edit
                </button>
                <button
                  onClick={handleSubmit}
                  disabled={saving}
                  className="px-4 py-2 bg-green-600 hover:bg-green-700 text-white rounded-lg transition-colors flex items-center gap-2 disabled:opacity-50"
                >
                  <FaCheckCircle />
                  Submit
                </button>
                <button
                  onClick={() => setDeleteConfirmOpen(true)}
                  disabled={saving}
                  className="px-4 py-2 bg-red-600 hover:bg-red-700 text-white rounded-lg transition-colors flex items-center gap-2 disabled:opacity-50"
                >
                  <FaTrash />
                  Delete
                </button>
              </>
            )}
            {isEditing && (
              <>
                <button
                  onClick={handleSave}
                  disabled={saving}
                  className="px-4 py-2 bg-green-600 hover:bg-green-700 text-white rounded-lg transition-colors flex items-center gap-2 disabled:opacity-50"
                >
                  {saving ? <FaSpinner className="animate-spin" /> : <FaSave />}
                  Save
                </button>
                <button
                  onClick={() => {
                    setIsEditing(false);
                    setFormData({
                      hospital: pmSchedule.hospital || '',
                      modality: pmSchedule.modality || '',
                      device_status: pmSchedule.device_status || '',
                      start_date: pmSchedule.start_date || '',
                      end_date: pmSchedule.end_date || '',
                      maintenance_team: pmSchedule.maintenance_team || '',
                      maintenance_manager: pmSchedule.maintenance_manager || '',
                      periodicity: pmSchedule.periodicity || 'Monthly',
                      assign_to: pmSchedule.assign_to || '',
                      due_date: pmSchedule.due_date || '',
                      next_pm_date: pmSchedule.next_pm_date || '',
                      manufacturer: pmSchedule.manufacturer || '',
                      model: pmSchedule.model || '',
                      pm_for: pmSchedule.pm_for || '',
                      asset_name: pmSchedule.asset_name || '',
                      no_of_pms: pmSchedule.no_of_pms || ''
                    });
                  }}
                  disabled={saving}
                  className="px-4 py-2 bg-gray-600 hover:bg-gray-700 text-white rounded-lg transition-colors disabled:opacity-50"
                >
                  Cancel
                </button>
              </>
            )}
            {isSubmitted && (
              <button
                onClick={handleCancel}
                disabled={saving}
                className="px-4 py-2 bg-red-600 hover:bg-red-700 text-white rounded-lg transition-colors flex items-center gap-2 disabled:opacity-50"
              >
                Cancel Document
              </button>
            )}
          </div>
        </div>
        
        {/* Workflow Status Summary Bar */}
        {isSubmitted && (
          <div className="flex items-center gap-4 mt-2 pt-3 border-t border-gray-200 dark:border-gray-700">
            <span className="text-sm text-gray-600 dark:text-gray-400">Workflow Status:</span>
            
            {plannedEntries.length > 0 && (
              <span className="px-3 py-1 text-sm font-medium rounded-full bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400">
                {plannedEntries.length} Planned
              </span>
            )}
            
            {appliedEntries.length > 0 && (
              <span className="px-3 py-1 text-sm font-medium rounded-full bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400">
                {appliedEntries.length} Pending Approval
              </span>
            )}
            
            {plannedEntries.length === 0 && appliedEntries.length === 0 && (
              <span className="px-3 py-1 text-sm font-medium rounded-full bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400">
                All Approved ✓
              </span>
            )}
          </div>
        )}
      </div>

      {/* Content - Split Layout */}
      <div className="flex-1 overflow-hidden flex">
        {/* Main Content */}
        <div className="flex-1 overflow-auto p-6">
          <div className="max-w-4xl mx-auto bg-white dark:bg-gray-800 rounded-lg shadow">
            <div className="p-6 space-y-6">
              {/* Basic Information */}
              <div>
                <h2 className="text-lg font-semibold text-gray-800 dark:text-white mb-4">Basic Information</h2>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div>
                    {isEditing ? (
                      <LinkField
                        label="Hospital *"
                        doctype="Company"
                        value={formData.hospital}
                        onChange={(value) => setFormData(prev => ({ ...prev, hospital: value }))}
                        placeholder="Select Hospital"
                        filters={{}}
                      />
                    ) : (
                      <>
                        <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                          Hospital
                        </label>
                        <div className="px-3 py-2 bg-gray-50 dark:bg-gray-700 rounded-lg text-gray-900 dark:text-white">
                          {pmSchedule.hospital || '-'}
                        </div>
                      </>
                    )}
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                      Modality
                    </label>
                    {isEditing ? (
                      <input
                        type="text"
                        name="modality"
                        value={formData.modality}
                        onChange={handleChange}
                        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"
                      />
                    ) : (
                      <div className="px-3 py-2 bg-gray-50 dark:bg-gray-700 rounded-lg text-gray-900 dark:text-white">
                        {pmSchedule.modality || '-'}
                      </div>
                    )}
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                      Device Status
                    </label>
                    {isEditing ? (
                      <input
                        type="text"
                        name="device_status"
                        value={formData.device_status}
                        onChange={handleChange}
                        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"
                      />
                    ) : (
                      <div className="px-3 py-2 bg-gray-50 dark:bg-gray-700 rounded-lg text-gray-900 dark:text-white">
                        {pmSchedule.device_status || '-'}
                      </div>
                    )}
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                      Periodicity *
                    </label>
                    {isEditing ? (
                      <select
                        name="periodicity"
                        value={formData.periodicity}
                        onChange={handleChange}
                        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="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 className="px-3 py-2 bg-gray-50 dark:bg-gray-700 rounded-lg text-gray-900 dark:text-white">
                        {pmSchedule.periodicity || '-'}
                      </div>
                    )}
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                      Manufacturer
                    </label>
                    {isEditing ? (
                      <input
                        type="text"
                        name="manufacturer"
                        value={formData.manufacturer}
                        onChange={handleChange}
                        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"
                      />
                    ) : (
                      <div className="px-3 py-2 bg-gray-50 dark:bg-gray-700 rounded-lg text-gray-900 dark:text-white">
                        {pmSchedule.manufacturer || '-'}
                      </div>
                    )}
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                      Model
                    </label>
                    {isEditing ? (
                      <input
                        type="text"
                        name="model"
                        value={formData.model}
                        onChange={handleChange}
                        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"
                      />
                    ) : (
                      <div className="px-3 py-2 bg-gray-50 dark:bg-gray-700 rounded-lg text-gray-900 dark:text-white">
                        {pmSchedule.model || '-'}
                      </div>
                    )}
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                      PM Name
                    </label>
                    {isEditing ? (
                      <input
                        type="text"
                        name="pm_for"
                        value={formData.pm_for}
                        onChange={handleChange}
                        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"
                      />
                    ) : (
                      <div className="px-3 py-2 bg-gray-50 dark:bg-gray-700 rounded-lg text-gray-900 dark:text-white">
                        {pmSchedule.pm_for || '-'}
                      </div>
                    )}
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                      Asset Name
                    </label>
                    {isEditing ? (
                      <input
                        type="text"
                        name="asset_name"
                        value={formData.asset_name}
                        onChange={handleChange}
                        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"
                      />
                    ) : (
                      <div className="px-3 py-2 bg-gray-50 dark:bg-gray-700 rounded-lg text-gray-900 dark:text-white">
                        {pmSchedule.asset_name || '-'}
                      </div>
                    )}
                  </div>
                </div>
              </div>

              {/* Schedule Dates */}
              <div>
                <h2 className="text-lg font-semibold text-gray-800 dark:text-white mb-4">Schedule Dates</h2>
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                      Start Date *
                    </label>
                    {isEditing ? (
                      <input
                        type="date"
                        name="start_date"
                        value={formData.start_date}
                        onChange={handleChange}
                        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"
                      />
                    ) : (
                      <div className="px-3 py-2 bg-gray-50 dark:bg-gray-700 rounded-lg text-gray-900 dark:text-white">
                        {pmSchedule.start_date ? new Date(pmSchedule.start_date).toLocaleDateString() : '-'}
                      </div>
                    )}
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                      End Date *
                    </label>
                    {isEditing ? (
                      <input
                        type="date"
                        name="end_date"
                        value={formData.end_date}
                        onChange={handleChange}
                        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"
                      />
                    ) : (
                      <div className="px-3 py-2 bg-gray-50 dark:bg-gray-700 rounded-lg text-gray-900 dark:text-white">
                        {pmSchedule.end_date ? new Date(pmSchedule.end_date).toLocaleDateString() : '-'}
                      </div>
                    )}
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                      First PM Date
                    </label>
                    {isEditing ? (
                      <input
                        type="date"
                        name="due_date"
                        value={formData.due_date}
                        onChange={handleChange}
                        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"
                      />
                    ) : (
                      <div className="px-3 py-2 bg-gray-50 dark:bg-gray-700 rounded-lg text-gray-900 dark:text-white">
                        {pmSchedule.due_date ? new Date(pmSchedule.due_date).toLocaleDateString() : '-'}
                      </div>
                    )}
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                      Next PM Date
                    </label>
                    {isEditing ? (
                      <input
                        type="date"
                        name="next_pm_date"
                        value={formData.next_pm_date}
                        onChange={handleChange}
                        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"
                      />
                    ) : (
                      <div className="px-3 py-2 bg-gray-50 dark:bg-gray-700 rounded-lg text-gray-900 dark:text-white">
                        {formData.next_pm_date ? new Date(formData.next_pm_date).toLocaleDateString() : (pmSchedule.next_pm_date ? new Date(pmSchedule.next_pm_date).toLocaleDateString() : '-')}
                      </div>
                    )}
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                      No. of PMs
                    </label>
                    {isEditing ? (
                      <input
                        type="number"
                        name="no_of_pms"
                        value={formData.no_of_pms}
                        onChange={handleChange}
                        min="1"
                        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"
                        placeholder="Enter number of PMs"
                      />
                    ) : (
                      <div className="px-3 py-2 bg-gray-50 dark:bg-gray-700 rounded-lg text-gray-900 dark:text-white">
                        {pmSchedule.no_of_pms || '-'}
                      </div>
                    )}
                  </div>
                </div>
              </div>

              {/* Assignment */}
              <div>
                <h2 className="text-lg font-semibold text-gray-800 dark:text-white mb-4">Assignment</h2>
                <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                      Maintenance Team
                    </label>
                    {isEditing ? (
                      <input
                        type="text"
                        name="maintenance_team"
                        value={formData.maintenance_team}
                        onChange={handleChange}
                        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"
                      />
                    ) : (
                      <div className="px-3 py-2 bg-gray-50 dark:bg-gray-700 rounded-lg text-gray-900 dark:text-white">
                        {pmSchedule.maintenance_team || '-'}
                      </div>
                    )}
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                      Maintenance Manager
                    </label>
                    {isEditing ? (
                      <input
                        type="text"
                        name="maintenance_manager"
                        value={formData.maintenance_manager}
                        onChange={handleChange}
                        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"
                      />
                    ) : (
                      <div className="px-3 py-2 bg-gray-50 dark:bg-gray-700 rounded-lg text-gray-900 dark:text-white">
                        {pmSchedule.maintenance_manager || '-'}
                      </div>
                    )}
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                      Assign To
                    </label>
                    {isEditing ? (
                      <input
                        type="text"
                        name="assign_to"
                        value={formData.assign_to}
                        onChange={handleChange}
                        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"
                      />
                    ) : (
                      <div className="px-3 py-2 bg-gray-50 dark:bg-gray-700 rounded-lg text-gray-900 dark:text-white">
                        {pmSchedule.assign_to || '-'}
                      </div>
                    )}
                  </div>
                </div>
              </div>

              {/* ✅ UPDATED: Maintenance Entries - Only show Planned and Applied */}
              {filteredMaintenanceEntries.length > 0 && (
                <div>
                  <h2 className="text-lg font-semibold text-gray-800 dark:text-white mb-4">
                    Pending Maintenance Entries
                    <span className="ml-2 text-sm font-normal text-gray-500 dark:text-gray-400">
                      (Showing Planned & Applied only)
                    </span>
                  </h2>
                  <div className="overflow-x-auto">
                    <table className="w-full border-collapse border border-gray-300 dark:border-gray-600">
                      <thead>
                        <tr className="bg-gray-100 dark:bg-gray-700">
                          <th className="border border-gray-300 dark:border-gray-600 px-4 py-2 text-left text-sm font-semibold text-gray-700 dark:text-gray-300">
                            Asset
                          </th>
                          <th className="border border-gray-300 dark:border-gray-600 px-4 py-2 text-left text-sm font-semibold text-gray-700 dark:text-gray-300">
                            Asset Name
                          </th>
                          <th className="border border-gray-300 dark:border-gray-600 px-4 py-2 text-left text-sm font-semibold text-gray-700 dark:text-gray-300">
                            Manufacturer
                          </th>
                          <th className="border border-gray-300 dark:border-gray-600 px-4 py-2 text-left text-sm font-semibold text-gray-700 dark:text-gray-300">
                            Maintenance Log
                          </th>
                          <th className="border border-gray-300 dark:border-gray-600 px-4 py-2 text-left text-sm font-semibold text-gray-700 dark:text-gray-300">
                            Status
                          </th>
                          <th className="border border-gray-300 dark:border-gray-600 px-4 py-2 text-left text-sm font-semibold text-gray-700 dark:text-gray-300">
                            Next PM Date
                          </th>
                        </tr>
                      </thead>
                      <tbody>
                        {filteredMaintenanceEntries.map((entry: any, index: number) => {
                          // Get only Planned and Applied logs for this asset
                          const filteredLogs = getFilteredEntriesForAsset(entry.asset);
                          
                          return filteredLogs.map((log: any, logIndex: number) => (
                            <tr key={`${entry.name}-${log.name}`} className="hover:bg-gray-50 dark:hover:bg-gray-700/50">
                              {logIndex === 0 && (
                                <>
                                  <td 
                                    className="border border-gray-300 dark:border-gray-600 px-4 py-2 text-sm text-gray-900 dark:text-white"
                                    rowSpan={filteredLogs.length}
                                  >
                                    {entry.asset ? (
                                      <button
                                        onClick={() => navigate(`/assets/${entry.asset}`)}
                                        className="text-blue-600 dark:text-blue-400 hover:underline"
                                      >
                                        {entry.asset}
                                      </button>
                                    ) : '-'}
                                  </td>
                                  <td 
                                    className="border border-gray-300 dark:border-gray-600 px-4 py-2 text-sm text-gray-900 dark:text-white"
                                    rowSpan={filteredLogs.length}
                                  >
                                    {entry.asset_name || '-'}
                                  </td>
                                  <td 
                                    className="border border-gray-300 dark:border-gray-600 px-4 py-2 text-sm text-gray-900 dark:text-white"
                                    rowSpan={filteredLogs.length}
                                  >
                                    {entry.manufacturer || '-'}
                                  </td>
                                </>
                              )}
                              <td className="border border-gray-300 dark:border-gray-600 px-4 py-2 text-sm text-gray-900 dark:text-white">
                                <button
                                  onClick={() => navigate(`/maintenance/${log.name}`)}
                                  className="text-blue-600 dark:text-blue-400 hover:underline"
                                >
                                  {log.name}
                                </button>
                              </td>
                              <td className="border border-gray-300 dark:border-gray-600 px-4 py-2 text-sm">
                                <span className={`px-2 py-1 rounded-full text-xs font-medium ${
                                  log.workflow_state === 'Applied' 
                                    ? getWorkflowStateBadge('Applied')
                                    : getWorkflowStateBadge('Planned')
                                }`}>
                                  {log.workflow_state === 'Applied' ? 'Applied (Pending Approval)' : 'Planned'}
                                </span>
                              </td>
                              <td className="border border-gray-300 dark:border-gray-600 px-4 py-2 text-sm text-gray-900 dark:text-white">
                                {log.due_date ? new Date(log.due_date).toLocaleDateString() : '-'}
                              </td>
                            </tr>
                          ));
                        })}
                      </tbody>
                    </table>
                  </div>
                </div>
              )}

              {/* ✅ Show message when all entries are approved */}
              {isSubmitted && filteredMaintenanceEntries.length === 0 && (
                <div className="bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 rounded-lg p-6 text-center">
                  <FaCheckCircle className="mx-auto text-green-600 dark:text-green-400 text-3xl mb-2" />
                  <h3 className="text-lg font-semibold text-green-800 dark:text-green-300 mb-1">
                    All Maintenance Entries Completed
                  </h3>
                  <p className="text-sm text-green-600 dark:text-green-400">
                    All maintenance entries have been approved. New planned entries will appear when generated.
                  </p>
                </div>
              )}

              {/* Metadata */}
              <div className="pt-4 border-t border-gray-200 dark:border-gray-700">
                <h2 className="text-sm font-semibold text-gray-600 dark:text-gray-400 mb-3">Metadata</h2>
                <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
                  <div>
                    <span className="text-gray-500 dark:text-gray-500">Created:</span>
                    <div className="font-medium text-gray-900 dark:text-white">
                      {pmSchedule.creation ? new Date(pmSchedule.creation).toLocaleString() : '-'}
                    </div>
                  </div>
                  <div>
                    <span className="text-gray-500 dark:text-gray-500">Created By:</span>
                    <div className="font-medium text-gray-900 dark:text-white">{pmSchedule.owner || '-'}</div>
                  </div>
                  <div>
                    <span className="text-gray-500 dark:text-gray-500">Modified:</span>
                    <div className="font-medium text-gray-900 dark:text-white">
                      {pmSchedule.modified ? new Date(pmSchedule.modified).toLocaleString() : '-'}
                    </div>
                  </div>
                  <div>
                    <span className="text-gray-500 dark:text-gray-500">Modified By:</span>
                    <div className="font-medium text-gray-900 dark:text-white">{pmSchedule.modified_by || '-'}</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* Activity Log Sidebar */}
        <div className="w-80 flex-shrink-0 bg-white dark:bg-gray-800 border-l border-gray-200 dark:border-gray-700 overflow-auto">
          <div className="p-4">
            <div className="flex items-center gap-2 mb-4">
              <FaHistory className="text-blue-600 dark:text-blue-400" />
              <h3 className="text-lg font-semibold text-gray-800 dark:text-white">Activity Log</h3>
            </div>
            
            {activityLogs.length === 0 ? (
              <div className="text-center py-8 text-gray-500 dark:text-gray-400">
                <FaHistory className="mx-auto text-3xl mb-2 opacity-50" />
                <p className="text-sm">No activity recorded yet</p>
              </div>
            ) : (
              <div className="space-y-3">
                {activityLogs.map((log) => (
                  <div
                    key={log.id}
                    className={`rounded-lg p-3 border ${
                      log.action === 'Approved' 
                        ? 'bg-green-50 dark:bg-green-900/20 border-green-200 dark:border-green-800'
                        : log.action === 'Applied'
                        ? 'bg-blue-50 dark:bg-blue-900/20 border-blue-200 dark:border-blue-800'
                        : 'bg-gray-50 dark:bg-gray-700 border-gray-200 dark:border-gray-600'
                    }`}
                  >
                    <div className="flex items-start gap-2">
                      <div className={`flex-shrink-0 w-8 h-8 rounded-full flex items-center justify-center ${
                        log.action === 'Approved'
                          ? 'bg-green-100 dark:bg-green-900/30'
                          : log.action === 'Applied'
                          ? 'bg-blue-100 dark:bg-blue-900/30'
                          : 'bg-gray-100 dark:bg-gray-600'
                      }`}>
                        {log.action === 'Approved' ? (
                          <FaThumbsUp className="text-green-600 dark:text-green-400 text-sm" />
                        ) : (
                          <FaClipboardCheck className="text-blue-600 dark:text-blue-400 text-sm" />
                        )}
                      </div>
                      <div className="flex-1 min-w-0">
                        <p className={`text-sm font-medium ${
                          log.action === 'Approved'
                            ? 'text-green-800 dark:text-green-300'
                            : log.action === 'Applied'
                            ? 'text-blue-800 dark:text-blue-300'
                            : 'text-gray-900 dark:text-white'
                        }`}>
                          {log.action}
                        </p>
                        <div className="flex items-center gap-1 mt-1 text-xs text-gray-500 dark:text-gray-400">
                          <FaUser className="text-[10px]" />
                          <span className="truncate">{log.user}</span>
                        </div>
                        <div className="flex items-center gap-1 mt-0.5 text-xs text-gray-500 dark:text-gray-400">
                          <FaClock className="text-[10px]" />
                          <span>{new Date(log.timestamp).toLocaleString()}</span>
                        </div>
                        <div className="mt-2 pt-2 border-t border-gray-200 dark:border-gray-600">
                          <div className="text-xs space-y-1">
                            <div className="flex justify-between">
                              <span className="text-gray-500 dark:text-gray-400">Entries:</span>
                              <span className={`font-medium ${
                                log.action === 'Approved' 
                                  ? 'text-green-600 dark:text-green-400' 
                                  : 'text-blue-600 dark:text-blue-400'
                              }`}>
                                {log.entriesCount}
                              </span>
                            </div>
                            {log.completionDate && (
                              <div className="flex justify-between">
                                <span className="text-gray-500 dark:text-gray-400">Completion Date:</span>
                                <span className="font-medium text-gray-900 dark:text-white">
                                  {new Date(log.completionDate).toLocaleDateString()}
                                </span>
                              </div>
                            )}
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Apply Modal - Updated with Checkboxes and Asset Names */}
      {showApplyModal && (
        <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-lg w-full mx-4">
            <div className="flex items-center gap-3 mb-4">
              <div className="w-10 h-10 bg-blue-100 dark:bg-blue-900/30 rounded-full flex items-center justify-center">
                <FaClipboardCheck className="text-blue-600 dark:text-blue-400" />
              </div>
              <div>
                <h3 className="text-lg font-semibold text-gray-800 dark:text-white">
                  Apply for Approval
                </h3>
                <p className="text-sm text-gray-500 dark:text-gray-400">
                  {selectedEntriesToApply.size} of {plannedEntries.length} {plannedEntries.length === 1 ? 'entry' : 'entries'} selected
                </p>
              </div>
            </div>

            {/* Planned Entries List with Checkboxes */}
            <div className="mb-4">
              <div className="flex items-center justify-between mb-2">
                <p className="text-xs font-medium text-gray-600 dark:text-gray-400">Select Entries to Complete:</p>
                <div className="flex gap-2">
                  <button
                    type="button"
                    onClick={selectAllApplyEntries}
                    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
                    type="button"
                    onClick={deselectAllApplyEntries}
                    className="text-xs text-blue-600 dark:text-blue-400 hover:underline"
                  >
                    Deselect All
                  </button>
                </div>
              </div>
              <div className="max-h-48 overflow-y-auto bg-gray-50 dark:bg-gray-700 rounded-lg p-3 space-y-2">
                {plannedEntries.map((entry, idx) => (
                  <label
                    key={entry.name}
                    className={`flex items-center gap-3 p-2 rounded-lg cursor-pointer transition-all ${
                      selectedEntriesToApply.has(entry.name)
                        ? 'bg-blue-50 dark:bg-blue-900/30 border border-blue-200 dark:border-blue-700'
                        : 'bg-white dark:bg-gray-600 border border-gray-200 dark:border-gray-500 hover:bg-gray-50 dark:hover:bg-gray-550'
                    }`}
                  >
                    <input
                      type="checkbox"
                      checked={selectedEntriesToApply.has(entry.name)}
                      onChange={() => toggleApplyEntrySelection(entry.name)}
                      className="w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600"
                    />
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2">
                        <span className="w-5 h-5 bg-yellow-100 dark:bg-yellow-900/30 rounded-full flex items-center justify-center text-[10px] font-medium text-yellow-700 dark:text-yellow-400 flex-shrink-0">
                          {idx + 1}
                        </span>
                        <div className="truncate">
                          <span className="text-sm font-medium text-gray-900 dark:text-white">
                            {entry.asset_display_name || entry.asset_name || 'Unknown Asset'}
                          </span>
                          <span className="text-gray-400 dark:text-gray-500 mx-1">-</span>
                          <span className="text-xs text-gray-600 dark:text-gray-400">
                            {entry.name}
                          </span>
                        </div>
                      </div>
                      {entry.due_date && (
                        <div className="ml-7 text-xs text-gray-500 dark:text-gray-400 mt-0.5">
                          Due: {new Date(entry.due_date).toLocaleDateString()}
                        </div>
                      )}
                    </div>
                  </label>
                ))}
              </div>
              {/* Selection Summary */}
              <div className="mt-2 flex items-center justify-between text-xs">
                <span className="text-gray-500 dark:text-gray-400">
                  {selectedEntriesToApply.size} selected
                </span>
                {selectedEntriesToApply.size === 0 && (
                  <span className="text-red-500 dark:text-red-400">
                    Please select at least one entry
                  </span>
                )}
              </div>
            </div>

            {/* Completion Date */}
            <div className="mb-4">
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                Completion Date *
              </label>
              <input
                type="date"
                value={completionDate}
                onChange={(e) => setCompletionDate(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"
              />
            </div>

            {/* Next PM Date Info */}
            {formData.next_pm_date && (
              <div className="mb-4 p-3 bg-blue-50 dark:bg-blue-900/20 rounded-lg">
                <div className="flex items-center gap-2 text-sm">
                  <FaCalendarAlt className="text-blue-600 dark:text-blue-400" />
                  <span className="text-gray-700 dark:text-gray-300">
                    Next PM Date: <strong className="text-blue-600 dark:text-blue-400">{new Date(formData.next_pm_date).toLocaleDateString()}</strong>
                  </span>
                </div>
              </div>
            )}

            {/* Early Completion Warning & Reason */}
            {isEarlyCompletion && (
              <div className="mb-4">
                <div className="p-3 bg-amber-50 dark:bg-amber-900/20 rounded-lg border border-amber-200 dark:border-amber-800 mb-3">
                  <p className="text-sm text-amber-700 dark:text-amber-400 flex items-center gap-2">
                    <span className="text-lg">⚠️</span>
                    Completion date is before the Next PM Date. Please provide a reason.
                  </p>
                </div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                  Early Completion Reason *
                </label>
                <textarea
                  value={earlyCompletionReason}
                  onChange={(e) => setEarlyCompletionReason(e.target.value)}
                  rows={3}
                  placeholder="Enter reason for early completion..."
                  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-amber-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white resize-none"
                />
              </div>
            )}

            {/* Actions */}
            <div className="flex gap-3 justify-end">
              <button
                onClick={() => {
                  setShowApplyModal(false);
                  setCompletionDate('');
                  setEarlyCompletionReason('');
                  setSelectedEntriesToApply(new Set());
                }}
                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 transition-colors"
                disabled={applyingComplete}
              >
                Cancel
              </button>
              <button
                onClick={handleApply}
                disabled={applyingComplete || !completionDate || selectedEntriesToApply.size === 0 || (isEarlyCompletion && !earlyCompletionReason.trim())}
                className="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors flex items-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {applyingComplete ? (
                  <>
                    <FaSpinner className="animate-spin" />
                    Applying...
                  </>
                ) : (
                  <>
                    <FaClipboardCheck />
                    Complete ({selectedEntriesToApply.size})
                  </>
                )}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Approve Modal - Updated with Checkboxes and Asset Names */}
      {showApproveModal && (
        <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-lg w-full mx-4">
            <div className="flex items-center gap-3 mb-4">
              <div className="w-10 h-10 bg-green-100 dark:bg-green-900/30 rounded-full flex items-center justify-center">
                <FaThumbsUp className="text-green-600 dark:text-green-400" />
              </div>
              <div>
                <h3 className="text-lg font-semibold text-gray-800 dark:text-white">
                  Approve Entries
                </h3>
                <p className="text-sm text-gray-500 dark:text-gray-400">
                  {selectedEntriesToApprove.size} of {appliedEntries.length} {appliedEntries.length === 1 ? 'entry' : 'entries'} selected
                </p>
              </div>
            </div>

            {/* Applied Entries List with Checkboxes */}
            <div className="mb-4">
              <div className="flex items-center justify-between mb-2">
                <p className="text-xs font-medium text-gray-600 dark:text-gray-400">Select Entries to Approve:</p>
                <div className="flex gap-2">
                  <button
                    type="button"
                    onClick={selectAllApproveEntries}
                    className="text-xs text-green-600 dark:text-green-400 hover:underline"
                  >
                    Select All
                  </button>
                  <span className="text-gray-300 dark:text-gray-600">|</span>
                  <button
                    type="button"
                    onClick={deselectAllApproveEntries}
                    className="text-xs text-green-600 dark:text-green-400 hover:underline"
                  >
                    Deselect All
                  </button>
                </div>
              </div>
              <div className="max-h-48 overflow-y-auto bg-gray-50 dark:bg-gray-700 rounded-lg p-3 space-y-2">
                {appliedEntries.map((entry, idx) => (
                  <label
                    key={entry.name}
                    className={`flex items-center gap-3 p-2 rounded-lg cursor-pointer transition-all ${
                      selectedEntriesToApprove.has(entry.name)
                        ? 'bg-green-50 dark:bg-green-900/30 border border-green-200 dark:border-green-700'
                        : 'bg-white dark:bg-gray-600 border border-gray-200 dark:border-gray-500 hover:bg-gray-50 dark:hover:bg-gray-550'
                    }`}
                  >
                    <input
                      type="checkbox"
                      checked={selectedEntriesToApprove.has(entry.name)}
                      onChange={() => toggleApproveEntrySelection(entry.name)}
                      className="w-4 h-4 text-green-600 bg-gray-100 border-gray-300 rounded focus:ring-green-500 dark:focus:ring-green-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600"
                    />
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2">
                        <span className="w-5 h-5 bg-blue-100 dark:bg-blue-900/30 rounded-full flex items-center justify-center text-[10px] font-medium text-blue-700 dark:text-blue-400 flex-shrink-0">
                          {idx + 1}
                        </span>
                        <div className="truncate">
                          <span className="text-sm font-medium text-gray-900 dark:text-white">
                            {entry.asset_display_name || entry.asset_name || 'Unknown Asset'}
                          </span>
                          <span className="text-gray-400 dark:text-gray-500 mx-1">-</span>
                          <span className="text-xs text-gray-600 dark:text-gray-400">
                            {entry.name}
                          </span>
                        </div>
                      </div>
                      {entry.completion_date && (
                        <div className="ml-7 text-xs text-gray-500 dark:text-gray-400 mt-0.5">
                          Completed: {new Date(entry.completion_date).toLocaleDateString()}
                        </div>
                      )}
                    </div>
                  </label>
                ))}
              </div>
              {/* Selection Summary */}
              <div className="mt-2 flex items-center justify-between text-xs">
                <span className="text-gray-500 dark:text-gray-400">
                  {selectedEntriesToApprove.size} selected
                </span>
                {selectedEntriesToApprove.size === 0 && (
                  <span className="text-red-500 dark:text-red-400">
                    Please select at least one entry
                  </span>
                )}
              </div>
            </div>

            {/* Info Box */}
            <div className="mb-4 p-3 bg-green-50 dark:bg-green-900/20 rounded-lg border border-green-200 dark:border-green-800">
              <p className="text-sm text-green-700 dark:text-green-400">
                ✓ Approving will <strong>submit</strong> the documents (docstatus = 1) and trigger auto-creation of next planned entries.
              </p>
            </div>

            {/* Actions */}
            <div className="flex gap-3 justify-end">
              <button
                onClick={() => {
                  setShowApproveModal(false);
                  setSelectedEntriesToApprove(new Set());
                }}
                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 transition-colors"
                disabled={approving}
              >
                Cancel
              </button>
              <button
                onClick={handleApprove}
                disabled={approving || selectedEntriesToApprove.size === 0}
                className="px-4 py-2 bg-green-600 hover:bg-green-700 text-white rounded-lg transition-colors flex items-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {approving ? (
                  <>
                    <FaSpinner className="animate-spin" />
                    Approving...
                  </>
                ) : (
                  <>
                    <FaThumbsUp />
                    Approve ({selectedEntriesToApprove.size})
                  </>
                )}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* 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">
              Confirm Delete
            </h3>
            <p className="text-gray-600 dark:text-gray-400 mb-6">
              Are you sure you want to delete this PPM Planner? This action cannot be undone.
            </p>
            <div className="flex gap-3 justify-end">
              <button
                onClick={() => setDeleteConfirmOpen(false)}
                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={saving}
              >
                Cancel
              </button>
              <button
                onClick={handleDelete}
                className="px-4 py-2 bg-red-600 hover:bg-red-700 text-white rounded-lg transition-colors"
                disabled={saving}
              >
                {saving ? 'Deleting...' : 'Delete'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default PPMPlannerDetail;