import React, { useState, useEffect, useCallback } from 'react';
import { useParams, useNavigate, useSearchParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { useInspectionDetails, useInspectionMutations } from '../hooks/useInspection';
import { useWorkflow } from '../hooks/useWorkflow';
import WorkflowActions from '../components/WorkflowActions';
import CommentSection from '../components/CommentSection';
import { 
  FaArrowLeft, 
  FaSave, 
  FaEdit, 
  FaTrash,
  FaCheckCircle,
  FaTimesCircle,
  FaExclamationTriangle,
  FaUser,
  FaClipboardCheck,
  FaExternalLinkAlt,
  FaCog,
  FaCheck,
  FaUpload,
  FaFile,
  FaTimes,
  FaSpinner,
  FaHistory,
  FaChevronDown,
  FaChevronUp,
  FaClock,
  FaSync,
  FaStickyNote,
  FaBan
} from 'react-icons/fa';
import { toast, ToastContainer, Bounce } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import LinkField from '../components/LinkField';
import inspectionService from '../services/inspectionService';
import apiService from '../services/apiService';
import API_CONFIG from '../config/api';
import type { CreateInspectionData } from '../services/inspectionService';

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

// Helper to get today's date in YYYY-MM-DD format
const getTodayDate = (): string => {
  return new Date().toISOString().split('T')[0];
};

// Status badge styles
const getStatusStyle = (status: string) => {
  switch (status?.toLowerCase()) {
    case 'open':
      return { bg: 'bg-blue-100 dark:bg-blue-900/30', text: 'text-blue-800 dark:text-blue-300', border: 'border-blue-200 dark:border-blue-800' };
    case 'in progress':
      return { bg: 'bg-yellow-100 dark:bg-yellow-900/30', text: 'text-yellow-800 dark:text-yellow-300', border: 'border-yellow-200 dark:border-yellow-800' };
    case 'closed':
      return { bg: 'bg-gray-100 dark:bg-gray-700', text: 'text-gray-800 dark:text-gray-300', border: 'border-gray-200 dark:border-gray-600' };
    default:
      return { bg: 'bg-gray-100 dark:bg-gray-700', text: 'text-gray-800 dark:text-gray-300', border: 'border-gray-200 dark:border-gray-600' };
  }
};

// Audit Log / Version interface
interface VersionChange {
  field: string;
  oldValue: any;
  newValue: any;
}

interface AuditLogEntry {
  name: string;
  owner: string;
  creation: string;
  changes: VersionChange[];
  added: any[];
  removed: any[];
  rowChanged: any[];
}

const InspectionDetail: React.FC = () => {
  const { t } = useTranslation();
  const { inspectionName } = useParams<{ inspectionName: string }>();
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();
  
  const isNewInspection = inspectionName === 'new';
  const startInEditMode = searchParams.get('edit') === 'true';

  // ✅ Roles allowed to delete inspections
  const DELETE_ALLOWED_ROLES = [
    'System Manager',
    'Contractor Supervisor', 
    'Contractor Manager'
  ];

  // ✅ State for role-based delete permission
  const [canDelete, setCanDelete] = useState(false);

// ✅ Check user permissions based on roles
  useEffect(() => {
    const checkPermissions = async () => {
      try {
        const response = await fetch('/api/method/asset_lite.api.user_roles.check_has_role', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            roles: DELETE_ALLOWED_ROLES.join(',')
          })
        });
        
        const data = await response.json();
        if (data.message) {
          setCanDelete(data.message.has_role);
        }
      } catch (error) {
        console.error('Error checking permissions:', error);
        setCanDelete(false);
      }
    };

    checkPermissions();
  }, []);

  // ✅ ADD HERE — fetch user roles for DeleteRequestButton
  const [userRoles, setUserRoles] = useState<string[]>([]);
  const [rolesLoaded, setRolesLoaded] = useState(false);

  useEffect(() => {
  const fetchRoles = async () => {
    try {
      const response = await apiService.apiCall<any>(
        '/api/method/asset_lite.api.user_roles.get_user_roles'
      );
      
      // API returns array directly, not wrapped in { message: [...] }
      if (Array.isArray(response)) {
        setUserRoles(response);
      } else if (response?.message) {
        setUserRoles(response.message);
      }
    } catch (err) {
      console.error('Error fetching roles:', err);
    } finally {
      setRolesLoaded(true);
    }
  };
  fetchRoles();
}, []);

  // ✅ State for cancel operation
  const [showCancelConfirm, setShowCancelConfirm] = useState(false);
  const [cancelling, setCancelling] = useState(false);

  // ✅ Check user permissions based on roles
  useEffect(() => {
    const checkPermissions = async () => {
      try {
        const response = await fetch('/api/method/asset_lite.api.user_roles.check_has_role', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            roles: DELETE_ALLOWED_ROLES.join(',')
          })
        });
        
        const data = await response.json();
        if (data.message) {
          setCanDelete(data.message.has_role);
        }
      } catch (error) {
        console.error('Error checking permissions:', error);
        setCanDelete(false);
      }
    };

    checkPermissions();
  }, []);
  
  // Form data state - Added new fields
  const [formData, setFormData] = useState<CreateInspectionData & {
    workflow_state?: string;
    work_order_type?: string;
    department?: string;
    location?: string;
    assigned_technician?: string;
    attachment?: string;
    attachment_on_close?: string;
    extension_no?: string;
    docstatus?: number;
  }>({
    inspection_type: '',
    status: 'Open',
    inspection_date: isNewInspection ? getTodayDate() : '',
    target_closure_date: '',
    requested_by: '',
    technician_department: '',
    linked_corrective_wo_no: '',
    observation_note: '',
    technical_response: '',
    workflow_state: 'Draft',
    // New fields
    work_order_type: '',
    department: '',
    location: '',
    assigned_technician: '',
    attachment: '',
    attachment_on_close: '',
    extension_no: '',
    docstatus: 0,
  });

  const [currentUserLoading, setCurrentUserLoading] = useState(isNewInspection);
  
  // State for filtered technicians based on work_order_type
  const [filteredTechnicians, setFilteredTechnicians] = useState<string[]>([]);
  
  // State for file upload
  const [isUploading, setIsUploading] = useState(false);

  // State for audit logs
  const [auditLogs, setAuditLogs] = useState<AuditLogEntry[]>([]);
  const [auditLogsLoading, setAuditLogsLoading] = useState(false);
  // const [auditLogsExpanded, setAuditLogsExpanded] = useState(true);
  const [auditLogsExpanded, setAuditLogsExpanded] = useState(false);
  const [showAllLogs, setShowAllLogs] = useState(false);

  const { inspection, loading, error, refetch } = useInspectionDetails(isNewInspection ? null : inspectionName || null);
  const { createInspection, updateInspection, deleteInspection, loading: saving } = useInspectionMutations();
  
  // Use the existing workflow hook
  const {
    transitions,
    isSystemManager,
    canEdit,
    getStateStyle,
  } = useWorkflow({
    doctype: 'Inspection',
    docname: isNewInspection ? null : inspectionName || null,
    workflowState: formData.workflow_state,
    enabled: !isNewInspection,
    docData: formData as Record<string, any>,
  });

  // ✅ Work Control role check + technician validation
  const isWorkControl = userRoles.includes('Work Control');
  const workControlMissingTechnician = isWorkControl && !formData.assigned_technician;

  const [isEditing, setIsEditing] = useState(isNewInspection || startInEditMode);
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);

  // ✅ Derived state for docstatus logic (like ERPNext)
  // docstatus 0 = Draft (workflow_state !== 'Closed' && workflow_state !== 'Cancelled')
  // docstatus 1 = Submitted (workflow_state === 'Closed')
  // docstatus 2 = Cancelled (workflow_state === 'Cancelled')
  const getDocStatus = useCallback((): number => {
    const workflowState = formData.workflow_state || 'Draft';
    if (workflowState === 'Cancelled') return 2;
    if (workflowState === 'Closed') return 1;
    return formData.docstatus || 0;
  }, [formData.workflow_state, formData.docstatus]);

  const docStatus = getDocStatus();
  const isSubmitted = docStatus === 1; // Closed state
  const isCancelled = docStatus === 2; // Cancelled state
  const isDraft = docStatus === 0; // Draft/Open states

  // ✅ Check if form should be read-only (submitted or cancelled)
  const hasDeleteRequest = !!(inspection?.custom_delete_status);
  const isFormReadOnly = isSubmitted || isCancelled || hasDeleteRequest;

  // ============== AUDIT LOG FUNCTIONS ==============

  /**
   * Fetch audit logs from Version doctype
   */
  const fetchAuditLogs = useCallback(async () => {
    if (isNewInspection || !inspectionName) return;
    
    setAuditLogsLoading(true);
    try {
      const response = await apiService.apiCall<any>(
        `/api/resource/Version?filters=[["ref_doctype","=","Inspection"],["docname","=","${encodeURIComponent(inspectionName)}"]]&fields=["name","owner","creation","data"]&order_by=creation desc&limit=50`
      );
      
      if (response?.data && response.data.length > 0) {
        const parsedLogs: AuditLogEntry[] = response.data.map((version: any) => {
          let parsedData = { added: [], changed: [], removed: [], row_changed: [] };
          try {
            parsedData = JSON.parse(version.data || '{}');
          } catch (e) {
            console.error('Error parsing version data:', e);
          }
          
          const changes: VersionChange[] = (parsedData.changed || []).map((change: any[]) => ({
            field: change[0] || '',
            oldValue: change[1],
            newValue: change[2]
          }));
          
          return {
            name: version.name,
            owner: version.owner,
            creation: version.creation,
            changes,
            added: parsedData.added || [],
            removed: parsedData.removed || [],
            rowChanged: parsedData.row_changed || []
          };
        });
        
        setAuditLogs(parsedLogs);
        console.log('Audit logs fetched:', parsedLogs.length);
      } else {
        setAuditLogs([]);
      }
    } catch (err) {
      console.error('Error fetching audit logs:', err);
      setAuditLogs([]);
    } finally {
      setAuditLogsLoading(false);
    }
  }, [isNewInspection, inspectionName]);

  // Initial fetch of audit logs
  useEffect(() => {
    fetchAuditLogs();
  }, [fetchAuditLogs]);

  /**
   * Format field name for display
   */
  const formatFieldName = (fieldName: string): string => {
    if (!fieldName) return '';
    return fieldName
      .replace(/^custom_/, '')
      .replace(/_/g, ' ')
      .replace(/\b\w/g, (char) => char.toUpperCase());
  };

  /**
   * Format value for display
   */
  const formatValue = (value: any): string => {
    if (value === null || value === undefined) return '(empty)';
    if (value === '') return '(empty)';
    if (value === 0) return '0';
    if (value === 1) return '1';
    if (typeof value === 'boolean') return value ? 'Yes' : 'No';
    if (typeof value === 'object') return JSON.stringify(value);
    return String(value);
  };

  /**
   * Format date for audit log display
   */
  const formatAuditDate = (dateStr: string): string => {
    if (!dateStr) return '';
    const date = new Date(dateStr);
    const now = new Date();
    const diffMs = now.getTime() - date.getTime();
    const diffMins = Math.floor(diffMs / 60000);
    const diffHours = Math.floor(diffMs / 3600000);
    const diffDays = Math.floor(diffMs / 86400000);
    
    if (diffMins < 1) return 'Just now';
    if (diffMins < 60) return `${diffMins} min${diffMins > 1 ? 's' : ''} ago`;
    if (diffHours < 24) return `${diffHours} hour${diffHours > 1 ? 's' : ''} ago`;
    if (diffDays < 7) return `${diffDays} day${diffDays > 1 ? 's' : ''} ago`;
    
    return date.toLocaleDateString('en-US', {
      month: 'short',
      day: 'numeric',
      year: date.getFullYear() !== now.getFullYear() ? 'numeric' : undefined,
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  /**
   * Get username from email (extract part before @)
   */
  const formatUsername = (email: string): string => {
    if (!email) return 'Unknown';
    const atIndex = email.indexOf('@');
    if (atIndex === -1) return email;
    return email.substring(0, atIndex);
  };

  /**
   * Get color class for field change based on field name
   */
  const getChangeColor = (fieldName: string): string => {
    const lowercaseField = fieldName.toLowerCase();
    if (lowercaseField.includes('status') || lowercaseField.includes('state')) {
      return 'text-purple-600 dark:text-purple-400';
    }
    if (lowercaseField.includes('date')) {
      return 'text-blue-600 dark:text-blue-400';
    }
    if (lowercaseField.includes('technician') || lowercaseField.includes('supervisor') || lowercaseField.includes('assigned')) {
      return 'text-green-600 dark:text-green-400';
    }
    return 'text-gray-600 dark:text-gray-400';
  };

  // ============== TECHNICIAN FILTERING BASED ON WORK ORDER TYPE ==============
  
  /**
   * Filter Technicians based on Work Order Type (Expertise)
   * Fetches all Asset Maintenance Team records with same expertise and collects all team members
   */
  const filterTechniciansBasedOnExpertise = useCallback(async (workOrderType: string) => {
    if (!workOrderType) {
      setFilteredTechnicians([]);
      return;
    }
    
    try {
      console.log('Filtering technicians for work order type:', workOrderType);
      
      // Get all Asset Maintenance Team records with same expertise
      const response = await apiService.apiCall<any>(
        `/api/resource/Asset Maintenance Team?filters=[["custom_expertise","=","${encodeURIComponent(workOrderType)}"]]&fields=["name"]&limit=100`
      );
      
      if (response?.data && response.data.length > 0) {
        const memberSet = new Set<string>();
        
        // Fetch each team document and collect members
        const promises = response.data.map(async (record: any) => {
          try {
            const teamResponse = await apiService.apiCall<any>(
              `/api/resource/Asset Maintenance Team/${encodeURIComponent(record.name)}`
            );
            
            if (teamResponse?.data) {
              const teamMembers = teamResponse.data.maintenance_team_members || [];
              teamMembers.forEach((row: any) => {
                if (row.team_member) {
                  memberSet.add(row.team_member);
                }
              });
            }
          } catch (err) {
            console.error('Error fetching team:', record.name, err);
          }
        });
        
        // Wait for all team documents to be fetched
        await Promise.all(promises);
        
        const memberList = Array.from(memberSet);
        console.log('Filtered Technicians:', memberList);
        setFilteredTechnicians(memberList);
      } else {
        setFilteredTechnicians([]);
      }
    } catch (err) {
      console.error('Error fetching technicians:', err);
      setFilteredTechnicians([]);
    }
  }, []);

  // Effect to filter technicians when work_order_type changes
  useEffect(() => {
    if (formData.work_order_type) {
      filterTechniciansBasedOnExpertise(formData.work_order_type);
    } else {
      setFilteredTechnicians([]);
    }
  }, [formData.work_order_type, filterTechniciansBasedOnExpertise]);

  // ============== DATE VALIDATION ==============
  
  /**
   * Validate inspection date - cannot be in the past
   */
  const validateInspectionDate = (dateStr: string): boolean => {
    if (!dateStr) return true;
    const today = getTodayDate();
    if (dateStr < today) {
      toast.error(t('inspections.detail.inspectionDateInPast'), {
        position: "top-right",
        autoClose: 5000,
        icon: <FaExclamationTriangle />
      });
      return false;
    }
    return true;
  };

  /**
   * Validate target closure date - cannot be earlier than inspection date and cannot be in the past
   */
  const validateTargetClosureDate = (targetDate: string, inspectionDate: string): boolean => {
    if (!targetDate) return true;
    const today = getTodayDate();
    
    // Check if earlier than inspection date
    if (inspectionDate && targetDate < inspectionDate) {
      toast.error(t('inspections.detail.targetClosureEarlier'), {
        position: "top-right",
        autoClose: 5000,
        icon: <FaExclamationTriangle />
      });
      return false;
    }
    
    // Check if in the past
    if (targetDate < today) {
      toast.error(t('inspections.detail.targetClosureInPast'), {
        position: "top-right",
        autoClose: 5000,
        icon: <FaExclamationTriangle />
      });
      return false;
    }
    
    return true;
  };

  // Handler for inspection date change with validation
  const handleInspectionDateChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const newDate = e.target.value;
    if (validateInspectionDate(newDate)) {
      setFormData(prev => ({ ...prev, inspection_date: newDate }));
      // Re-validate target closure date if it exists
      if (formData.target_closure_date) {
        validateTargetClosureDate(formData.target_closure_date, newDate);
      }
    }
  };

  // Handler for target closure date change with validation
  const handleTargetClosureDateChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const newDate = e.target.value;
    if (validateTargetClosureDate(newDate, formData.inspection_date || '')) {
      setFormData(prev => ({ ...prev, target_closure_date: newDate }));
    }
  };

  // Handler for work order type change - clears technician when type changes
  const handleWorkOrderTypeChange = (val: string) => {
    setFormData(prev => ({
      ...prev,
      work_order_type: val,
      assigned_technician: '' // Clear technician when work order type changes
    }));
  };

  // ============== FILE UPLOAD HANDLER ==============
  
  /**
   * Handle file upload for attachment field
   */
  const handleFileUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    
    // Check file size (max 10MB)
    const maxSize = 10 * 1024 * 1024; // 10MB
    if (file.size > maxSize) {
      toast.error(t('inspections.detail.fileSizeExceeds'), {
        position: "top-right",
        autoClose: 4000,
        icon: <FaTimesCircle />
      });
      return;
    }
    
    setIsUploading(true);
    
    try {
      const formDataUpload = new FormData();
      formDataUpload.append('file', file);
      formDataUpload.append('is_private', '0');
      formDataUpload.append('folder', 'Home/Attachments');
      
      // If editing existing inspection, attach to it
      if (!isNewInspection && inspectionName) {
        formDataUpload.append('doctype', 'Inspection');
        formDataUpload.append('docname', inspectionName);
      }
      
      const baseUrl = API_CONFIG.BASE_URL || '';
      const response = await fetch(`${baseUrl}/api/method/upload_file`, {
        method: 'POST',
        credentials: 'include',
        body: formDataUpload
      });
      
      const result = await response.json();
      
      if (result.message?.file_url) {
        setFormData(prev => ({
          ...prev,
          attachment: result.message.file_url
        }));
        toast.success(t('inspections.detail.fileUploadedSuccess'), {
          position: "top-right",
          autoClose: 3000,
          icon: <FaCheckCircle />
        });
      } else {
        throw new Error('Upload failed');
      }
    } catch (err) {
      console.error('File upload error:', err);
      toast.error(t('inspections.detail.failedToUpload'), {
        position: "top-right",
        autoClose: 4000,
        icon: <FaTimesCircle />
      });
    } finally {
      setIsUploading(false);
      // Reset the input
      e.target.value = '';
    }
  };

  /**
   * Remove attachment
   */
  const handleRemoveAttachment = () => {
    setFormData(prev => ({
      ...prev,
      attachment: ''
    }));
    toast.info(t('inspections.detail.attachmentRemoved'), {
      position: "top-right",
      autoClose: 2000
    });
  };

  /**
   * Get filename from URL
   */
  const getFilenameFromUrl = (url: string): string => {
    if (!url) return '';
    const parts = url.split('/');
    return parts[parts.length - 1] || url;
  };

  // ============== END FILE UPLOAD HANDLER ==============

  // ============== CANCEL HANDLER (ERPNext style) ==============
  
  /**
   * Handle cancel - changes docstatus to 2 and workflow_state to 'Cancelled'
   */
  const handleCancel = async () => {
    setCancelling(true);
    try {
      // Update the document with cancelled state
      await updateInspection(inspectionName!, {
        ...formData,
        workflow_state: 'Cancelled',
        docstatus: 2,
        status: 'Cancelled'
      });
      
      toast.success(t('inspections.detail.cancelledSuccessfully'), {
        position: "top-right",
        autoClose: 3000,
        icon: <FaCheckCircle />
      });
      
      setShowCancelConfirm(false);
      refetch();
      
      // Refresh audit logs
      setTimeout(() => {
        fetchAuditLogs();
      }, 500);
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'Unknown error';
      toast.error(t('inspections.detail.failedToCancel', { error: errorMessage }), {
        position: "top-right",
        autoClose: 6000,
        icon: <FaTimesCircle />
      });
    } finally {
      setCancelling(false);
    }
  };

  // ============== END CANCEL HANDLER ==============

  // Get current user for new inspections
  useEffect(() => {
    const fetchCurrentUser = async () => {
      if (isNewInspection && !formData.requested_by) {
        try {
          const currentUser = await inspectionService.getCurrentUser();
          if (currentUser) {
            setFormData(prev => ({ ...prev, requested_by: currentUser }));
          }
        } catch (err) {
          console.error('Error fetching current user:', err);
        } finally {
          setCurrentUserLoading(false);
        }
      } else {
        setCurrentUserLoading(false);
      }
    };

    fetchCurrentUser();
  }, [isNewInspection]);

  // Load inspection data when fetched
  useEffect(() => {
    if (inspection && !isNewInspection) {
      setFormData({
        inspection_type: inspection.inspection_type || '',
        status: inspection.status || 'Open',
        inspection_date: inspection.inspection_date || '',
        target_closure_date: inspection.target_closure_date || '',
        requested_by: inspection.requested_by || '',
        technician_department: inspection.technician_department || '',
        linked_corrective_wo_no: inspection.linked_corrective_wo_no || '',
        observation_note: inspection.observation_note || '',
        technical_response: inspection.technical_response || '',
        workflow_state: inspection.workflow_state || 'Draft',
        // New fields
        work_order_type: inspection.work_order_type || '',
        department: inspection.department || '',
        location: inspection.location || '',
        assigned_technician: inspection.assigned_technician || '',
        attachment: inspection.attachment || '',
        attachment_on_close: inspection.attachment_on_close || '',
        extension_no: inspection.extension_no || '',
        docstatus: inspection.docstatus || 0,
      });
      // ✅ Don't allow editing if submitted or cancelled
      if (inspection.workflow_state === 'Closed' || inspection.workflow_state === 'Cancelled' || inspection.docstatus >= 1) {
        setIsEditing(false);
      } else if (!startInEditMode) {
        setIsEditing(false);
      }
    }
  }, [inspection, isNewInspection, startInEditMode]);

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

  const handleSave = async () => {
    // Validation: target_closure_date is mandatory
    if (!formData.target_closure_date) {
      toast.error(t('inspections.detail.targetClosureMandatory'), {
        position: "top-right",
        autoClose: 5000,
        icon: <FaTimesCircle />
      });
      return;
    }

    // Validation: attachment is mandatory
    if (!formData.attachment) {
      toast.error(t('inspections.detail.attachmentMandatory'), {
        position: "top-right",
        autoClose: 5000,
        icon: <FaTimesCircle />
      });
      return;
    }

    // Validation: extension_no is mandatory
    if (!formData.extension_no) {
      toast.error(t('inspections.detail.extensionMandatory'), {
        position: "top-right",
        autoClose: 5000,
        icon: <FaTimesCircle />
      });
      return;
    }

    // Run date validations before save
    if (!validateInspectionDate(formData.inspection_date || '')) {
      return;
    }
    if (!validateTargetClosureDate(formData.target_closure_date || '', formData.inspection_date || '')) {
      return;
    }

    try {
      if (isNewInspection) {
        const newInspection = await createInspection(formData);
        toast.success(t('inspections.detail.createdSuccessfully'), {
          position: "top-right",
          autoClose: 3000,
          icon: <FaCheckCircle />
        });
        navigate(`/inspections/${newInspection.name}`);
      } else {
        await updateInspection(inspectionName!, formData);
        toast.success(t('inspections.detail.updatedSuccessfully'), {
          position: "top-right",
          autoClose: 3000,
          icon: <FaCheckCircle />
        });
        setIsEditing(false);
        refetch();
        // Refresh audit logs
        setTimeout(() => {
          fetchAuditLogs();
        }, 500);
      }
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'Unknown error';
      toast.error(t('inspections.detail.failedToSave', { error: errorMessage }), {
        position: "top-right",
        autoClose: 6000,
        icon: <FaTimesCircle />
      });
    }
  };

  const handleDelete = async () => {
    try {
      await deleteInspection(inspectionName!);
      toast.success(t('inspections.detail.deletedSuccessfully'), {
        position: "top-right",
        autoClose: 3000,
        icon: <FaCheckCircle />
      });
      navigate(-1);
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'Unknown error';
      toast.error(t('inspections.detail.failedToDelete', { error: errorMessage }), {
        position: "top-right",
        autoClose: 6000,
        icon: <FaTimesCircle />
      });
    }
  };

  const handleWorkflowActionComplete = (action: string, success: boolean) => {
    if (success) {
      toast.success(`Action "${action}" applied successfully!`, {
        position: "top-right",
        autoClose: 3000,
        icon: <FaCheckCircle />
      });
      // Refresh audit logs after workflow action
      setTimeout(() => {
        fetchAuditLogs();
      }, 500);
    }
  };

  const handleWorkflowStateChange = () => {
    refetch();
  };

  const isFieldDisabled = useCallback((fieldname: string): boolean => {
    // ✅ Always disable if form is read-only (submitted or cancelled)
    if (isFormReadOnly) return true;
    if (!isEditing) return true;
    // linked_corrective_wo_no is always read-only
    if (fieldname === 'linked_corrective_wo_no') return true;
    // Check workflow edit permission (System Manager can always edit)
    if (!isNewInspection && !canEdit && !isSystemManager) return true;
    return false;
  }, [isEditing, isNewInspection, canEdit, isSystemManager, isFormReadOnly]);

  if (loading || currentUserLoading) {
    return (
      <div className="flex items-center justify-center h-screen bg-gray-50 dark:bg-gray-900">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-teal-500 mx-auto"></div>
          <p className="mt-4 text-gray-600 dark:text-gray-400">{t('inspections.detail.loadingDetails')}</p>
        </div>
      </div>
    );
  }

  if (error && !isNewInspection) {
    return (
      <div className="p-6 bg-gray-50 dark:bg-gray-900 min-h-screen">
        <div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-6">
          <h2 className="text-xl font-bold text-red-800 dark:text-red-300 mb-4">{t('inspections.detail.errorLoading')}</h2>
          <p className="text-red-700 dark:text-red-400 mb-4">{error}</p>
          <button
            onClick={() => navigate(-1)}
            className="bg-teal-600 hover:bg-teal-700 text-white px-4 py-2 rounded"
          >
            {t('inspections.detail.backToList')}
          </button>
        </div>
      </div>
    );
  }

  const currentWorkflowState = inspection?.workflow_state || formData.workflow_state || 'Draft';
  const workflowStateStyle = getStateStyle(currentWorkflowState);
  const statusStyle = getStatusStyle(formData.status || 'Open');

  return (
    <div className="min-h-screen bg-gray-50 dark:bg-gray-900 p-6">
      {/* Toast Container */}
      <ToastContainer
        position="top-right"
        autoClose={4000}
        hideProgressBar={false}
        newestOnTop
        closeOnClick
        rtl={false}
        pauseOnFocusLoss
        draggable
        pauseOnHover
        theme="colored"
        transition={Bounce}
      />

      {/* Header */}
      <div className="mb-6 flex justify-between items-center">
        <div className="flex items-center gap-4">
          <button
            onClick={() => navigate(-1)}
            className="text-gray-600 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200"
          >
            <FaArrowLeft size={20} />
          </button>
          <div>
            <h1 className="text-2xl font-bold text-gray-800 dark:text-white flex items-center gap-3">
              {isNewInspection ? t('inspections.detail.newInspection') : inspection?.name || t('inspections.detail.inspectionDetails')}
              {/*!isNewInspection && (
                <span className={`px-3 py-1 rounded-full text-sm font-medium ${workflowStateStyle.bg} ${workflowStateStyle.text} ${workflowStateStyle.border} border`}>
                  {currentWorkflowState}
                </span>
              )} */}
              {!isNewInspection && (
                <span className={`px-3 py-1 rounded-full text-sm font-medium ${statusStyle.bg} ${statusStyle.text} ${statusStyle.border} border`}>
                  {formData.status || 'Open'}
                </span>
              )}
              {/* ✅ Show Cancelled badge */}
              {isCancelled && (
                <span className="px-3 py-1 rounded-full text-sm font-medium bg-red-100 dark:bg-red-900/30 text-red-700 dark:text-red-300 border border-red-200 dark:border-red-800">
                  {t('inspections.detail.cancelled')}
                </span>
              )}
              {isSystemManager && !isNewInspection && (
                <span className="px-2 py-0.5 bg-purple-100 dark:bg-purple-900/30 text-purple-700 dark:text-purple-300 text-xs rounded-full">
                  System Manager
                </span>
              )}
            </h1>
            <p className="text-gray-600 dark:text-gray-400 mt-1">
              {isNewInspection ? t('inspections.detail.createNewRecord') : `${formData.inspection_type || t('inspections.typeMap.inspection')}`}
              {/* ✅ Show read-only message */}
              {/* {isFormReadOnly && !isNewInspection && (
                <span className="ml-2 text-orange-600 dark:text-orange-400 text-sm">
                  (Read-only - {isSubmitted ? 'Closed' : 'Cancelled'})
                </span>
              )} */}
            </p>
          </div>
        </div>

        <div className="flex gap-3">
          {!isNewInspection && !isEditing && (
            <>
              {/* ✅ Show Edit button only if not submitted and not cancelled */}
              {!isFormReadOnly && (
                <button
                  onClick={() => setIsEditing(true)}
                  className="bg-teal-600 hover:bg-teal-700 text-white px-4 py-2 rounded-lg flex items-center gap-2"
                >
                  <FaEdit />
                  {t('common.edit')}
                </button>
              )}
              
              {/* ✅ Show Cancel button only if submitted (docstatus = 1) and user has delete permission */}
              {isSubmitted && canDelete && (
                <button
                  onClick={() => setShowCancelConfirm(true)}
                  className="bg-orange-600 hover:bg-orange-700 text-white px-4 py-2 rounded-lg flex items-center gap-2"
                >
                  <FaBan />
                  {t('common.cancel')}
                </button>
              )}
              
              {/* ✅ Show Delete button only if:
                  - Draft (docstatus = 0) AND user has delete permission
                  - OR Cancelled (docstatus = 2) AND user has delete permission
              */}

              {/* {((isDraft && canDelete) || (isCancelled && canDelete)) && (
                <button
                  onClick={() => setShowDeleteConfirm(true)}
                  className="bg-red-600 hover:bg-red-700 text-white px-4 py-2 rounded-lg flex items-center gap-2"
                >
                  <FaTrash />
                  {t('common.delete')}
                </button>
              )} */}
              {/* {!isNewInspection && rolesLoaded && (  // ← ADD rolesLoaded
              <>
    {console.log('Roles debug:', JSON.stringify(userRoles)) as any}
  
                <DeleteRequestButton
                  doctype="Inspection"
                  docname={inspectionName}
                  currentDeleteStatus={(inspection?.custom_delete_status ?? null) as DeleteStatus}
                  userRoles={userRoles}
                  isSystemManager={isSystemManager}
                  inline
                  redirectOnDelete="/inspections"
                  onStatusChange={() => refetch()}
                />
                </>
              )} */}
            </>
          )}
          {isEditing && (
            <>
              <button
                onClick={() => {
                  if (isNewInspection) {
                    navigate(-1);
                  } else {
                    setIsEditing(false);
                    refetch();
                  }
                }}
                className="bg-gray-600 hover:bg-gray-700 text-white px-4 py-2 rounded-lg"
              >
                {t('common.cancel')}
              </button>
              <button
                onClick={handleSave}
                disabled={saving}
                className="bg-green-600 hover:bg-green-700 text-white px-4 py-2 rounded-lg flex items-center gap-2 disabled:opacity-50"
              >
                <FaSave />
                {saving ? t('common.saving') : t('common.save')}
              </button>
            </>
          )}
        </div>
      </div>

      {/* ✅ Cancel Confirmation Modal */}
      {showCancelConfirm && (
        <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 p-6 max-w-md w-full mx-4 shadow-xl">
            <div className="flex items-start gap-3 mb-4">
              <FaBan className="text-orange-500 text-xl mt-0.5" />
              <div>
                <h3 className="text-lg font-semibold text-gray-800 dark:text-white">{t('inspections.detail.cancelInspection')}</h3>
                <p className="text-gray-600 dark:text-gray-400 mt-1">
                  {t('inspections.detail.cancelConfirmMessage')}
                </p>
              </div>
            </div>
            <div className="flex justify-end gap-3">
              <button
                onClick={() => setShowCancelConfirm(false)}
                className="px-4 py-2 bg-gray-300 hover:bg-gray-400 text-gray-700 rounded-lg"
                disabled={cancelling}
              >
                {t('inspections.detail.noGoBack')}
              </button>
              <button
                onClick={handleCancel}
                disabled={cancelling}
                className="px-4 py-2 bg-orange-600 hover:bg-orange-700 text-white rounded-lg disabled:opacity-50 flex items-center gap-2"
              >
                {cancelling ? (
                  <>
                    <FaSpinner className="animate-spin" />
                    {t('inspections.detail.cancelling')}
                  </>
                ) : (
                  <>
                    <FaBan />
                    {t('inspections.detail.yesCancel')}
                  </>
                )}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Delete Confirmation Modal */}
      {showDeleteConfirm && (
        <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 p-6 max-w-md w-full mx-4 shadow-xl">
            <div className="flex items-start gap-3 mb-4">
              <FaExclamationTriangle className="text-red-500 text-xl mt-0.5" />
              <div>
                <h3 className="text-lg font-semibold text-gray-800 dark:text-white">{t('inspections.deleteInspection')}</h3>
                <p className="text-gray-600 dark:text-gray-400 mt-1">
                  {t('inspections.deleteConfirmMessage')}
                </p>
              </div>
            </div>
            <div className="flex justify-end gap-3">
              <button
                onClick={() => setShowDeleteConfirm(false)}
                className="px-4 py-2 bg-gray-300 hover:bg-gray-400 text-gray-700 rounded-lg"
              >
                {t('common.cancel')}
              </button>
              <button
                onClick={handleDelete}
                disabled={saving}
                className="px-4 py-2 bg-red-600 hover:bg-red-700 text-white rounded-lg disabled:opacity-50"
              >
                {saving ? t('common.deleting') : t('common.delete')}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Form */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Main Content - Left Column */}
        <div className="lg:col-span-2 space-y-6">
          {/* Inspection Details */}
          <div className="bg-white dark:bg-gray-800 rounded-xl shadow-md p-6 border border-gray-200 dark:border-gray-700">
            <h2 className="text-lg font-semibold text-gray-800 dark:text-white mb-4 pb-2 border-b border-gray-200 dark:border-gray-700 flex items-center gap-2">
              <FaClipboardCheck className="text-teal-500" />
              {t('inspections.detail.inspectionDetails')}
            </h2>
            
            <div className="space-y-4">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                {/* Inspection Type */}
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    {t('inspections.detail.inspectionType')}
                  </label>
                  <select
                    name="inspection_type"
                    value={formData.inspection_type}
                    onChange={handleChange}
                    disabled={isFieldDisabled('inspection_type')}
                    className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-white disabled:bg-gray-100 dark:disabled:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-teal-500"
                  >
                    <option value="">{t('inspections.detail.selectType')}</option>
                    <option value="Inspection">{t('inspections.typeMap.inspection')}</option>
                    <option value="Safety Inspection">{t('inspections.typeMap.safety_inspection')}</option>
                  </select>
                </div>

                {/* Status */}
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    {t('inspections.detail.status')}
                  </label>
                  <select
                    name="status"
                    value={formData.status}
                    onChange={handleChange}
                    disabled={isFieldDisabled('status')}
                    className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-white disabled:bg-gray-100 dark:disabled:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-teal-500"
                  >
                    <option value="Open">{t('inspections.status.open')}</option>
                    <option value="In Progress">{t('inspections.status.in_progress')}</option>
                    <option value="Pending Review">{t('inspections.status.pending_review')}</option>
                    <option value="Closed">{t('inspections.status.closed')}</option>
                    <option value="Cancelled">{t('inspections.detail.cancelled')}</option>
                  </select>
                </div>
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                {/* Work Order Type - NEW FIELD */}
                <div>
                  <LinkField
                    label={t('inspections.detail.workOrderType')}
                    doctype="Issue Type"
                    value={formData.work_order_type || ''}
                    onChange={handleWorkOrderTypeChange}
                    disabled={isFieldDisabled('work_order_type')}
                    placeholder={t('inspections.detail.selectWorkOrderType')}
                  />
                  {filteredTechnicians.length > 0 && (
                    <p className="mt-1 text-xs text-blue-600 dark:text-blue-400">
                      {t('inspections.detail.techniciansAvailable', { count: filteredTechnicians.length })}
                    </p>
                  )}
                </div>

                {/* Department - NEW FIELD */}
                <div>
                  <LinkField
                    label={t('inspections.detail.department')}
                    doctype="Department"
                    value={formData.department || ''}
                    onChange={(val) => setFormData({ ...formData, department: val })}
                    disabled={isFieldDisabled('department')}
                    placeholder={t('inspections.detail.selectDepartment')}
                    allowQuickCreate={true}
                  />
                </div>
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                {/* Location - NEW FIELD */}
                <div>
                  <LinkField
                    label={t('inspections.detail.location')}
                    doctype="Location"
                    value={formData.location || ''}
                    onChange={(val) => setFormData({ ...formData, location: val })}
                    disabled={isFieldDisabled('location')}
                    placeholder={t('inspections.detail.selectLocation')}
                    allowQuickCreate={true}
                  />
                </div>

                {/* Extension No - NEW FIELD - MANDATORY */}
                <div>
                  <LinkField
                    label={t('inspections.detail.extensionNo')}
                    doctype="Extension Directory"
                    value={formData.extension_no || ''}
                    onChange={(val) => setFormData({ ...formData, extension_no: val })}
                    disabled={isFieldDisabled('extension_no')}
                    placeholder={t('inspections.detail.selectExtension')}
                    allowQuickCreate={true}
                  />
                </div>
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                {/* Inspection Date */}
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    {t('inspections.detail.inspectionDate')}
                  </label>
                  <input
                    type="date"
                    name="inspection_date"
                    value={formData.inspection_date || ''}
                    onChange={handleInspectionDateChange}
                    min={getTodayDate()}
                    disabled={isFieldDisabled('inspection_date')}
                    className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-white disabled:bg-gray-100 dark:disabled:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-teal-500"
                  />
                  <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
                    {t('inspections.detail.cannotBeInPast')}
                  </p>
                </div>

                {/* Target Closure Date */}
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    {t('inspections.detail.targetClosureDate')} <span className="text-red-500">*</span>
                  </label>
                  <input
                    type="date"
                    name="target_closure_date"
                    value={formData.target_closure_date || ''}
                    onChange={handleTargetClosureDateChange}
                    min={formData.inspection_date || getTodayDate()}
                    disabled={isFieldDisabled('target_closure_date')}
                    className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-white disabled:bg-gray-100 dark:disabled:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-teal-500"
                  />
                  <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
                    {t('inspections.detail.cannotBeEarlier')}
                  </p>
                </div>
              </div>

              {/* Attachments Row - Opening and Closing */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                {/* Opening Attachment - MANDATORY */}
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    {t('inspections.detail.openingAttachment')}
                  </label>
                  
                  {/* Show existing attachment */}
                  {formData.attachment ? (
                    <div className="flex items-center gap-3 p-3 bg-gray-50 dark:bg-gray-700 rounded-lg border border-gray-200 dark:border-gray-600">
                      <FaFile className="text-blue-500 flex-shrink-0" size={18} />
                      <div className="flex-1 min-w-0">
                        <a 
                          href={`${API_CONFIG.BASE_URL || ''}${formData.attachment}`}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="text-sm text-blue-600 dark:text-blue-400 hover:underline truncate block"
                        >
                          {getFilenameFromUrl(formData.attachment)}
                        </a>
                      </div>
                      {isEditing && !isFormReadOnly && (
                        <button
                          type="button"
                          onClick={handleRemoveAttachment}
                          className="p-1.5 text-red-500 hover:text-red-700 hover:bg-red-50 dark:hover:bg-red-900/20 rounded transition-colors flex-shrink-0"
                          title={t('inspections.detail.removeAttachment')}
                        >
                          <FaTimes size={14} />
                        </button>
                      )}
                    </div>
                  ) : (
                    /* Upload button when no attachment */
                    isEditing && !isFormReadOnly ? (
                      <label className="flex items-center gap-2 px-4 py-2.5 bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400 rounded-lg cursor-pointer hover:bg-blue-100 dark:hover:bg-blue-900/30 transition-colors border border-blue-200 dark:border-blue-800 w-fit">
                        {isUploading ? (
                          <>
                            <FaSpinner className="animate-spin" size={14} />
                            <span className="text-sm">{t('inspections.detail.uploading')}</span>
                          </>
                        ) : (
                          <>
                            <FaUpload size={14} />
                            <span className="text-sm">{t('inspections.detail.uploadFile')}</span>
                          </>
                        )}
                        <input
                          type="file"
                          onChange={handleFileUpload}
                          disabled={isUploading || isFieldDisabled('attachment')}
                          className="hidden"
                          accept="image/*,.pdf,.doc,.docx,.xls,.xlsx,.txt"
                        />
                      </label>
                    ) : (
                      <p className="text-sm text-gray-400 dark:text-gray-500 italic p-3 bg-gray-50 dark:bg-gray-700 rounded-lg">
                        {t('inspections.detail.noAttachment')}
                      </p>
                    )
                  )}
                </div>

                {/* Closing Attachment */}
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    {t('inspections.detail.closingAttachment')}
                  </label>
                  
                  {/* Show existing closing attachment */}
                  {formData.attachment_on_close ? (
                    <div className="flex items-center gap-3 p-3 bg-gray-50 dark:bg-gray-700 rounded-lg border border-gray-200 dark:border-gray-600">
                      <FaFile className="text-green-500 flex-shrink-0" size={18} />
                      <div className="flex-1 min-w-0">
                        <a 
                          href={`${API_CONFIG.BASE_URL || ''}${formData.attachment_on_close}`}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="text-sm text-blue-600 dark:text-blue-400 hover:underline truncate block"
                        >
                          {getFilenameFromUrl(formData.attachment_on_close)}
                        </a>
                      </div>
                      {isEditing && !isFormReadOnly && (
                        <button
                          type="button"
                          onClick={() => {
                            setFormData(prev => ({
                              ...prev,
                              attachment_on_close: ''
                            }));
                            toast.info(t('inspections.detail.closingAttachmentRemoved'), {
                              position: "top-right",
                              autoClose: 2000
                            });
                          }}
                          className="p-1.5 text-red-500 hover:text-red-700 hover:bg-red-50 dark:hover:bg-red-900/20 rounded transition-colors flex-shrink-0"
                          title={t('inspections.detail.removeClosingAttachment')}
                        >
                          <FaTimes size={14} />
                        </button>
                      )}
                    </div>
                  ) : (
                    /* Upload button when no closing attachment */
                    isEditing && !isFormReadOnly ? (
                      <label className="flex items-center gap-2 px-4 py-2.5 bg-green-50 dark:bg-green-900/20 text-green-600 dark:text-green-400 rounded-lg cursor-pointer hover:bg-green-100 dark:hover:bg-green-900/30 transition-colors border border-green-200 dark:border-green-800 w-fit">
                        {isUploading ? (
                          <>
                            <FaSpinner className="animate-spin" size={14} />
                            <span className="text-sm">{t('inspections.detail.uploading')}</span>
                          </>
                        ) : (
                          <>
                            <FaUpload size={14} />
                            <span className="text-sm">{t('inspections.detail.uploadClosingFile')}</span>
                          </>
                        )}
                        <input
                          type="file"
                          onChange={async (e) => {
                            const file = e.target.files?.[0];
                            if (!file) return;
                            
                            // Check file size (max 10MB)
                            const maxSize = 10 * 1024 * 1024;
                            if (file.size > maxSize) {
                              toast.error(t('inspections.detail.fileSizeExceeds'), {
                                position: "top-right",
                                autoClose: 4000,
                                icon: <FaTimesCircle />
                              });
                              return;
                            }
                            
                            setIsUploading(true);
                            
                            try {
                              const formDataUpload = new FormData();
                              formDataUpload.append('file', file);
                              formDataUpload.append('is_private', '0');
                              formDataUpload.append('folder', 'Home/Attachments');
                              
                              if (!isNewInspection && inspectionName) {
                                formDataUpload.append('doctype', 'Inspection');
                                formDataUpload.append('docname', inspectionName);
                              }
                              
                              const baseUrl = API_CONFIG.BASE_URL || '';
                              const response = await fetch(`${baseUrl}/api/method/upload_file`, {
                                method: 'POST',
                                credentials: 'include',
                                body: formDataUpload
                              });
                              
                              const result = await response.json();
                              
                              if (result.message?.file_url) {
                                setFormData(prev => ({
                                  ...prev,
                                  attachment_on_close: result.message.file_url
                                }));
                                toast.success(t('inspections.detail.closingAttachmentUploadedSuccess'), {
                                  position: "top-right",
                                  autoClose: 3000,
                                  icon: <FaCheckCircle />
                                });
                              } else {
                                throw new Error('Upload failed');
                              }
                            } catch (err) {
                              console.error('File upload error:', err);
                              toast.error(t('inspections.detail.failedToUploadClosing'), {
                                position: "top-right",
                                autoClose: 4000,
                                icon: <FaTimesCircle />
                              });
                            } finally {
                              setIsUploading(false);
                              e.target.value = '';
                            }
                          }}
                          disabled={isUploading || isFieldDisabled('attachment_on_close')}
                          className="hidden"
                          accept="image/*,.pdf,.doc,.docx,.xls,.xlsx,.txt"
                        />
                      </label>
                    ) : (
                      <p className="text-sm text-gray-400 dark:text-gray-500 italic p-3 bg-gray-50 dark:bg-gray-700 rounded-lg">
                        {t('inspections.detail.noClosingAttachment')}
                      </p>
                    )
                  )}
                </div>
              </div>
            </div>
          </div>

          {/* Assignment Information */}
          <div className="bg-white dark:bg-gray-800 rounded-xl shadow-md p-6 border border-gray-200 dark:border-gray-700">
            <h2 className="text-lg font-semibold text-gray-800 dark:text-white mb-4 pb-2 border-b border-gray-200 dark:border-gray-700 flex items-center gap-2">
              <FaUser className="text-blue-500" />
              {t('inspections.detail.assignmentInformation')}
            </h2>
            
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              {/* Requested By */}
              <div>
                <LinkField
                  label={t('inspections.detail.requestedBy')}
                  doctype="User"
                  value={formData.requested_by || ''}
                  onChange={(val) => setFormData({ ...formData, requested_by: val })}
                  disabled={isFieldDisabled('requested_by')}
                  placeholder={t('inspections.detail.selectUser')}
                />
              </div>

              {/* Technical Department */}
              <div>
                <LinkField
                  label={t('inspections.detail.technicalDepartment')}
                  doctype="Technical Department"
                  value={formData.technician_department || ''}
                  onChange={(val) => setFormData({ ...formData, technician_department: val })}
                  disabled={isFieldDisabled('technician_department')}
                  placeholder={t('inspections.detail.selectDepartment')}
                  allowQuickCreate={true}
                />
              </div>

              {/* Assigned Technician */}
              <div>
                <LinkField
                  label={t('inspections.detail.assignedTechnician')}
                  doctype="User"
                  value={formData.assigned_technician || ''}
                  onChange={(val) => setFormData({ ...formData, assigned_technician: val })}
                  disabled={isFieldDisabled('assigned_technician')}
                  placeholder={t('inspections.detail.selectTechnician')}
                  filters={filteredTechnicians.length > 0 ? { name: ['in', filteredTechnicians] } : {}}
                />
                {!formData.work_order_type && isEditing && !isFormReadOnly && (
                  <p className="mt-1 text-xs text-orange-500 dark:text-orange-400">
                    {t('inspections.detail.selectWOTypeFirst')}
                  </p>
                )}
                {formData.work_order_type && filteredTechnicians.length === 0 && isEditing && !isFormReadOnly && (
                  <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
                    {t('inspections.detail.noTechniciansForType')}
                  </p>
                )}
              </div>
            </div>
          </div>

          {/* Notes & Response */}
          <div className="bg-white dark:bg-gray-800 rounded-xl shadow-md p-6 border border-gray-200 dark:border-gray-700">
            <h2 className="text-lg font-semibold text-gray-800 dark:text-white mb-4 pb-2 border-b border-gray-200 dark:border-gray-700 flex items-center gap-2">
              <FaStickyNote className="text-green-500" />
              {t('inspections.detail.notesAndResponse')}
            </h2>
            
            <div className="space-y-4">
              {/* Observation Note */}
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  {t('inspections.detail.observationNote')}
                </label>
                <textarea
                  name="observation_note"
                  value={formData.observation_note}
                  onChange={handleChange}
                  disabled={isFieldDisabled('observation_note')}
                  placeholder={t('inspections.detail.placeholderObservation')}
                  rows={4}
                  className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-white disabled:bg-gray-100 dark:disabled:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-teal-500 resize-none"
                />
              </div>

              {/* Technical Response */}
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  {t('inspections.detail.technicalResponse')}
                </label>
                <textarea
                  name="technical_response"
                  value={formData.technical_response}
                  onChange={handleChange}
                  disabled={isFieldDisabled('technical_response')}
                  placeholder={t('inspections.detail.placeholderTechnicalResponse')}
                  rows={4}
                  className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-white disabled:bg-gray-100 dark:disabled:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-teal-500 resize-none"
                />
              </div>
            </div>
          </div>

          {/* Linked Work Order */}
          <div className="bg-white dark:bg-gray-800 rounded-xl shadow-md p-6 border border-gray-200 dark:border-gray-700">
            <h2 className="text-lg font-semibold text-gray-800 dark:text-white mb-4 pb-2 border-b border-gray-200 dark:border-gray-700 flex items-center gap-2">
              <FaCog className="text-orange-500" />
              {t('inspections.detail.linkedWorkOrder')}
            </h2>
            
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                {t('inspections.detail.linkedCorrectiveWO')} <span className="text-xs text-gray-500">({t('inspections.detail.readOnly')})</span>
              </label>
              {formData.linked_corrective_wo_no ? (
                <div className="flex items-center gap-3 p-3 bg-gray-50 dark:bg-gray-700 rounded-lg border border-gray-200 dark:border-gray-600">
                  <span className="text-gray-900 dark:text-white font-medium">{formData.linked_corrective_wo_no}</span>
                  <button
                    onClick={() => navigate(`/work-orders/${formData.linked_corrective_wo_no}`)}
                    className="text-blue-600 dark:text-blue-400 hover:text-blue-800 dark:hover:text-blue-300 flex items-center gap-1 text-sm"
                  >
                    {t('inspections.detail.viewWorkOrder')} <FaExternalLinkAlt size={12} />
                  </button>
                </div>
              ) : (
                <div className="p-3 bg-gray-50 dark:bg-gray-700 rounded-lg border border-gray-200 dark:border-gray-600">
                  <span className="text-gray-500 dark:text-gray-400 italic">{t('inspections.detail.noLinkedWorkOrder')}</span>
                </div>
              )}
            </div>
          </div>

          {/* ✅ ADD THIS — Comments Section */}
          {!isNewInspection && (
            <CommentSection
              referenceDoctype="Inspection"
              referenceName={inspectionName || null}
              title="Comments & Discussion"     // optional, default shown
              pollInterval={30000}               // optional, auto-refresh every 30s (0 = off)
              initialLimit={5}                   // optional, comments shown before "show more"
              collapsible={true}                 // optional, allow collapse/expand
              startCollapsed={false}             // optional, start collapsed
            />
          )}
          
        </div>

        {/* Sidebar - Right Column */}
        <div className="space-y-4">
          {/* Workflow Actions - Using the existing WorkflowActions component */}
          {/* Workflow Actions - Using the existing WorkflowActions component */}
          {!isNewInspection && !isEditing && !isFormReadOnly && (
            <div className="bg-white dark:bg-gray-800 rounded-xl shadow-md p-4 border border-gray-200 dark:border-gray-700">
              <h2 className="text-sm font-semibold text-gray-800 dark:text-white mb-3 pb-2 border-b border-gray-200 dark:border-gray-700 flex items-center gap-2">
                <FaCog className="text-purple-500" size={14} />
                {t('inspections.detail.workflowActions')}
              </h2>

              {/* ⚠️ Work Control warning — shown only when technician is missing */}
              {workControlMissingTechnician && (
                <div className="mb-3 flex items-start gap-2 p-3 bg-amber-50 dark:bg-amber-900/20 border border-amber-300 dark:border-amber-700 rounded-lg">
                  <FaExclamationTriangle
                    className="text-amber-500 flex-shrink-0 mt-0.5"
                    size={14}
                  />
                  <div>
                    <p className="text-xs font-semibold text-amber-800 dark:text-amber-300">
                      Technician Required
                    </p>
                    <p className="text-[11px] text-amber-700 dark:text-amber-400 mt-0.5">
                      Please assign a technician to this inspection before proceeding with workflow actions.
                    </p>
                  </div>
                </div>
              )}

              {/* Workflow buttons — hidden for Work Control when technician is missing */}
              {!workControlMissingTechnician && (
                <WorkflowActions
                  doctype="Inspection"
                  docname={inspectionName || null}
                  workflowState={currentWorkflowState}
                  onActionComplete={handleWorkflowActionComplete}
                  onStateChange={handleWorkflowStateChange}
                  showStateInfo={false}
                />
              )}

              {/* Workflow Progress Visual - Compact */}
              <div className="mt-3 p-3 bg-gray-50 dark:bg-gray-700 rounded-lg">
                <p className="text-[10px] text-gray-500 dark:text-gray-400 mb-2">{t('inspections.detail.workflowProgress')}</p>
                <div className="flex items-center justify-between">
                  {/* Draft */}
                  <div className={`flex flex-col items-center ${currentWorkflowState === 'Draft' ? 'text-orange-600' : 'text-green-600'}`}>
                    <div className={`w-5 h-5 rounded-full flex items-center justify-center text-[10px] ${currentWorkflowState === 'Draft' ? 'bg-orange-100 dark:bg-orange-900/30' : 'bg-green-100 dark:bg-green-900/30'}`}>
                      {currentWorkflowState === 'Draft' ? '1' : <FaCheck size={8} />}
                    </div>
                    <span className="text-[8px] mt-0.5">{t('inspections.detail.draftStep')}</span>
                  </div>
                  <div className={`flex-1 h-0.5 mx-0.5 ${currentWorkflowState !== 'Draft' ? 'bg-green-500' : 'bg-gray-300 dark:bg-gray-600'}`}></div>
                  
                  {/* Work Control */}
                  <div className={`flex flex-col items-center ${currentWorkflowState === 'Sent to Work Control' ? 'text-blue-600' : ['Sent to technician', 'Sent to Supervisor', 'Closed'].includes(currentWorkflowState) ? 'text-green-600' : 'text-gray-400'}`}>
                    <div className={`w-5 h-5 rounded-full flex items-center justify-center text-[10px] ${currentWorkflowState === 'Sent to Work Control' ? 'bg-blue-100 dark:bg-blue-900/30' : ['Sent to technician', 'Sent to Supervisor', 'Closed'].includes(currentWorkflowState) ? 'bg-green-100 dark:bg-green-900/30' : 'bg-gray-100 dark:bg-gray-700'}`}>
                      {['Sent to technician', 'Sent to Supervisor', 'Closed'].includes(currentWorkflowState) ? <FaCheck size={8} /> : '2'}
                    </div>
                    <span className="text-[8px] mt-0.5 text-center leading-tight">{(() => { const parts = t('inspections.detail.workControl').split(' '); return parts.length >= 2 ? <>{parts[0]}<br />{parts[1]}</> : t('inspections.detail.workControl'); })()}</span>
                  </div>
                  <div className={`flex-1 h-0.5 mx-0.5 ${['Sent to technician', 'Sent to Supervisor', 'Closed'].includes(currentWorkflowState) ? 'bg-green-500' : 'bg-gray-300 dark:bg-gray-600'}`}></div>
                  
                  {/* Technician */}
                  <div className={`flex flex-col items-center ${currentWorkflowState === 'Sent to technician' ? 'text-purple-600' : ['Sent to Supervisor', 'Closed'].includes(currentWorkflowState) ? 'text-green-600' : 'text-gray-400'}`}>
                    <div className={`w-5 h-5 rounded-full flex items-center justify-center text-[10px] ${currentWorkflowState === 'Sent to technician' ? 'bg-purple-100 dark:bg-purple-900/30' : ['Sent to Supervisor', 'Closed'].includes(currentWorkflowState) ? 'bg-green-100 dark:bg-green-900/30' : 'bg-gray-100 dark:bg-gray-700'}`}>
                      {['Sent to Supervisor', 'Closed'].includes(currentWorkflowState) ? <FaCheck size={8} /> : '3'}
                    </div>
                    <span className="text-[8px] mt-0.5">{t('inspections.detail.technicianStep')}</span>
                  </div>
                  <div className={`flex-1 h-0.5 mx-0.5 ${['Sent to Supervisor', 'Closed'].includes(currentWorkflowState) ? 'bg-green-500' : 'bg-gray-300 dark:bg-gray-600'}`}></div>
                  
                  {/* Supervisor */}
                  <div className={`flex flex-col items-center ${currentWorkflowState === 'Sent to Supervisor' ? 'text-indigo-600' : currentWorkflowState === 'Closed' ? 'text-green-600' : 'text-gray-400'}`}>
                    <div className={`w-5 h-5 rounded-full flex items-center justify-center text-[10px] ${currentWorkflowState === 'Sent to Supervisor' ? 'bg-indigo-100 dark:bg-indigo-900/30' : currentWorkflowState === 'Closed' ? 'bg-green-100 dark:bg-green-900/30' : 'bg-gray-100 dark:bg-gray-700'}`}>
                      {currentWorkflowState === 'Closed' ? <FaCheck size={8} /> : '4'}
                    </div>
                    <span className="text-[8px] mt-0.5">{t('inspections.detail.supervisorStep')}</span>
                  </div>
                  <div className={`flex-1 h-0.5 mx-0.5 ${currentWorkflowState === 'Closed' ? 'bg-green-500' : 'bg-gray-300 dark:bg-gray-600'}`}></div>
                  
                  {/* Closed */}
                  <div className={`flex flex-col items-center ${currentWorkflowState === 'Closed' ? 'text-green-600' : 'text-gray-400'}`}>
                    <div className={`w-5 h-5 rounded-full flex items-center justify-center text-[10px] ${currentWorkflowState === 'Closed' ? 'bg-green-100 dark:bg-green-900/30' : 'bg-gray-100 dark:bg-gray-700'}`}>
                      {currentWorkflowState === 'Closed' ? <FaCheck size={8} /> : '5'}
                    </div>
                    <span className="text-[8px] mt-0.5">{t('inspections.detail.closedStep')}</span>
                  </div>
                </div>
              </div>
            </div>
          )}

          {/* Status Information - Minimized */}
          <div className="bg-white dark:bg-gray-800 rounded-xl shadow-md p-4 border border-gray-200 dark:border-gray-700">
            <h2 className="text-sm font-semibold text-gray-800 dark:text-white mb-3 pb-2 border-b border-gray-200 dark:border-gray-700 flex items-center gap-2">
              <FaClipboardCheck className="text-teal-500" size={14} />
              {t('inspections.detail.statusInfo')}
            </h2>
            
            <div className="space-y-2">
              {/* Workflow State */}
              <div className={`p-2 rounded-lg border ${workflowStateStyle.bg} ${workflowStateStyle.border}`}>
                <p className="text-[10px] text-gray-500 dark:text-gray-400">{t('inspections.detail.workflow')}</p>
                <p className={`text-sm font-semibold ${workflowStateStyle.text}`}>
                  {currentWorkflowState}
                </p>
              </div>

              {/* Status */}
              <div className={`p-2 rounded-lg border ${statusStyle.bg} ${statusStyle.border}`}>
                <p className="text-[10px] text-gray-500 dark:text-gray-400">{t('inspections.detail.status')}</p>
                <p className={`text-sm font-semibold ${statusStyle.text}`}>
                  {formData.status || 'Open'}
                </p>
              </div>

              {/* ✅ DocStatus indicator */}
              {/* <div className={`p-2 rounded-lg border ${
                isCancelled 
                  ? 'bg-red-100 dark:bg-red-900/30 border-red-200 dark:border-red-800' 
                  : isSubmitted 
                    ? 'bg-green-100 dark:bg-green-900/30 border-green-200 dark:border-green-800'
                    : 'bg-blue-100 dark:bg-blue-900/30 border-blue-200 dark:border-blue-800'
              }`}>
                <p className="text-[10px] text-gray-500 dark:text-gray-400">{t('inspections.detail.documentStatus')}</p>
                <p className={`text-sm font-semibold ${
                  isCancelled 
                    ? 'text-red-700 dark:text-red-300' 
                    : isSubmitted 
                      ? 'text-green-700 dark:text-green-300'
                      : 'text-blue-700 dark:text-blue-300'
                }`}>
                  {isCancelled ? t('inspections.detail.cancelled') : isSubmitted ? t('inspections.detail.submitted') : t('inspections.workflowState.draft')}
                </p>
              </div> */}

              {/* Quick Info Row */}
              <div className="grid grid-cols-2 gap-2">
                {formData.inspection_type && (
                  <div className="p-2 bg-gray-50 dark:bg-gray-700 rounded-lg">
                    <p className="text-[10px] text-gray-500 dark:text-gray-400">{t('inspections.detail.inspectionType')}</p>
                    <p className="text-xs font-medium text-gray-900 dark:text-white truncate">
                      {formData.inspection_type}
                    </p>
                  </div>
                )}

                {formData.work_order_type && (
                  <div className="p-2 bg-gray-50 dark:bg-gray-700 rounded-lg">
                    <p className="text-[10px] text-gray-500 dark:text-gray-400">{t('inspections.detail.woType')}</p>
                    <p className="text-xs font-medium text-gray-900 dark:text-white truncate">
                      {formData.work_order_type}
                    </p>
                  </div>
                )}
              </div>

              {formData.assigned_technician && (
                <div className="p-2 bg-gray-50 dark:bg-gray-700 rounded-lg">
                  <p className="text-[10px] text-gray-500 dark:text-gray-400">{t('inspections.detail.assignedTo')}</p>
                  <p className="text-xs font-medium text-gray-900 dark:text-white truncate">
                    {formData.assigned_technician}
                  </p>
                </div>
              )}
            </div>
          </div>

          {/* Activity Log / Audit Log */}
          {!isNewInspection && (
            <div className="bg-white dark:bg-gray-800 rounded-xl shadow-md border border-gray-200 dark:border-gray-700 overflow-hidden">
              {/* Header */}
              <div className="flex items-center justify-between p-3 border-b border-gray-200 dark:border-gray-700">
                <div 
                  className="flex items-center gap-2 cursor-pointer flex-1"
                  onClick={() => setAuditLogsExpanded(!auditLogsExpanded)}
                >
                  <FaHistory className="text-blue-500" size={14} />
                  <h2 className="text-sm font-semibold text-gray-800 dark:text-white">
                    {t('inspections.detail.activityLog')}
                  </h2>
                  {auditLogs.length > 0 && (
                    <span className="px-1.5 py-0.5 bg-blue-100 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400 rounded-full text-[10px] font-medium">
                      {auditLogs.length}
                    </span>
                  )}
                </div>
                <div className="flex items-center gap-1">
                  {/* Refresh button */}
                  <button 
                    type="button"
                    onClick={(e) => {
                      e.stopPropagation();
                      fetchAuditLogs();
                      toast.info(t('inspections.detail.activityLogRefreshed'), {
                        position: "top-right",
                        autoClose: 1500,
                        icon: <FaSync />
                      });
                    }}
                    disabled={auditLogsLoading}
                    className="p-1 text-gray-400 hover:text-blue-500 hover:bg-blue-50 dark:hover:bg-blue-900/20 rounded transition-colors disabled:opacity-50"
                    title={t('inspections.detail.refreshActivityLog')}
                  >
                    <FaSync className={`${auditLogsLoading ? 'animate-spin' : ''}`} size={10} />
                  </button>
                  {/* Expand/Collapse button */}
                  <button 
                    type="button"
                    onClick={() => setAuditLogsExpanded(!auditLogsExpanded)}
                    className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors p-1"
                  >
                    {auditLogsExpanded ? <FaChevronUp size={12} /> : <FaChevronDown size={12} />}
                  </button>
                </div>
              </div>

              {/* Content */}
              {auditLogsExpanded && (
                <div className="p-3">
                  {/* Loading State */}
                  {auditLogsLoading && (
                    <div className="flex items-center justify-center py-6">
                      <FaSpinner className="animate-spin text-blue-500 mr-2" size={14} />
                      <span className="text-xs text-gray-500 dark:text-gray-400">{t('common.loading')}</span>
                    </div>
                  )}

                  {/* Empty State */}
                  {!auditLogsLoading && auditLogs.length === 0 && (
                    <div className="relative">
                      {/* Timeline line */}
                      <div className="absolute left-2 top-0 bottom-0 w-0.5 bg-gray-200 dark:bg-gray-700"></div>

                      {/* No changes message */}
                      <div className="relative pl-6 mb-3">
                        <div className="absolute left-1 top-1 w-2.5 h-2.5 rounded-full border-2 border-white dark:border-gray-800 bg-gray-300 dark:bg-gray-600"></div>
                        <div className="p-2 rounded-lg bg-gray-50 dark:bg-gray-700/50">
                          <p className="text-[10px] text-gray-500 dark:text-gray-400 italic">
                            {t('inspections.detail.noChangesRecorded')}
                          </p>
                        </div>
                      </div>

                      {/* Created By Entry */}
                      {inspection?.creation && inspection?.owner && (
                        <div className="relative pl-6">
                          <div className="absolute left-1 top-1 w-2.5 h-2.5 rounded-full border-2 border-white dark:border-gray-800 bg-green-500"></div>
                          <div className="p-2 rounded-lg bg-green-50 dark:bg-green-900/20 border border-green-100 dark:border-green-800/50">
                            <div className="flex items-center justify-between mb-1">
                              <div className="flex items-center gap-1.5">
                                <div className="w-5 h-5 rounded-full bg-green-200 dark:bg-green-800 flex items-center justify-center">
                                  <FaUser className="text-green-600 dark:text-green-400" size={8} />
                                </div>
                                <span className="text-[10px] font-medium text-gray-700 dark:text-gray-300">
                                  {formatUsername(inspection.owner)}
                                </span>
                              </div>
                              <div className="flex items-center gap-1 text-[10px] text-gray-500 dark:text-gray-400">
                                <FaClock size={8} />
                                <span title={new Date(inspection.creation).toLocaleString()}>
                                  {formatAuditDate(inspection.creation)}
                                </span>
                              </div>
                            </div>
                            <div className="text-[10px]">
                              <span className="inline-flex items-center gap-1 px-1.5 py-0.5 bg-green-100 dark:bg-green-800/50 text-green-700 dark:text-green-300 rounded font-medium">
                                <FaCheckCircle size={8} />
                                {t('inspections.detail.createdThisInspection')}
                              </span>
                            </div>
                          </div>
                        </div>
                      )}
                    </div>
                  )}

                  {/* Activity Timeline */}
                  {!auditLogsLoading && auditLogs.length > 0 && (
                    <div className="relative">
                      {/* Timeline line */}
                      <div className="absolute left-2 top-0 bottom-0 w-0.5 bg-gray-200 dark:bg-gray-700"></div>

                      {/* Activity entries */}
                      <div className="space-y-3">
                        {(showAllLogs ? auditLogs : auditLogs.slice(0, 5)).map((log, index) => (
                          <div key={log.name} className="relative pl-6">
                            {/* Timeline dot */}
                            <div className={`absolute left-1 top-1 w-2.5 h-2.5 rounded-full border-2 border-white dark:border-gray-800 ${
                              index === 0 ? 'bg-blue-500' : 'bg-gray-300 dark:bg-gray-600'
                            }`}></div>

                            {/* Entry content */}
                            <div className={`p-2 rounded-lg ${
                              index === 0 
                                ? 'bg-blue-50 dark:bg-blue-900/20 border border-blue-100 dark:border-blue-800/50' 
                                : 'bg-gray-50 dark:bg-gray-700/50'
                            }`}>
                              {/* Header: User and Time */}
                              <div className="flex items-center justify-between mb-1.5">
                                <div className="flex items-center gap-1.5">
                                  <div className="w-5 h-5 rounded-full bg-gray-200 dark:bg-gray-600 flex items-center justify-center">
                                    <FaUser className="text-gray-500 dark:text-gray-400" size={8} />
                                  </div>
                                  <span className="text-[10px] font-medium text-gray-700 dark:text-gray-300">
                                    {formatUsername(log.owner)}
                                  </span>
                                </div>
                                <div className="flex items-center gap-1 text-[10px] text-gray-500 dark:text-gray-400">
                                  <FaClock size={8} />
                                  <span title={new Date(log.creation).toLocaleString()}>
                                    {formatAuditDate(log.creation)}
                                  </span>
                                </div>
                              </div>

                              {/* Changes */}
                              <div className="space-y-1">
                                {log.changes.length > 0 ? (
                                  log.changes.map((change, changeIndex) => (
                                    <div key={changeIndex} className="text-[10px]">
                                      <span className={`font-medium ${getChangeColor(change.field)}`}>
                                        {formatFieldName(change.field)}
                                      </span>
                                      <span className="text-gray-500 dark:text-gray-400"> {t('inspections.detail.changedFrom')} </span>
                                      <span className="px-1 py-0.5 bg-red-100 dark:bg-red-900/30 text-red-600 dark:text-red-400 rounded text-[9px] font-mono">
                                        {formatValue(change.oldValue)}
                                      </span>
                                      <span className="text-gray-500 dark:text-gray-400"> → </span>
                                      <span className="px-1 py-0.5 bg-green-100 dark:bg-green-900/30 text-green-600 dark:text-green-400 rounded text-[9px] font-mono">
                                        {formatValue(change.newValue)}
                                      </span>
                                    </div>
                                  ))
                                ) : (
                                  <p className="text-[10px] text-gray-500 dark:text-gray-400 italic">
                                    {t('inspections.detail.documentUpdated')}
                                  </p>
                                )}

                                {/* Show added items */}
                                {log.added && log.added.length > 0 && (
                                  <div className="text-[10px] text-green-600 dark:text-green-400">
                                    <span className="font-medium">{t('inspections.detail.added')}</span> {log.added.length} {t('inspections.detail.items')}
                                  </div>
                                )}

                                {/* Show removed items */}
                                {log.removed && log.removed.length > 0 && (
                                  <div className="text-[10px] text-red-600 dark:text-red-400">
                                    <span className="font-medium">{t('inspections.detail.removed')}</span> {log.removed.length} {t('inspections.detail.items')}
                                  </div>
                                )}

                                {/* Show row changes */}
                                {log.rowChanged && log.rowChanged.length > 0 && (
                                  <div className="text-[10px] text-orange-600 dark:text-orange-400">
                                    <span className="font-medium">{t('inspections.detail.modified')}</span> {log.rowChanged.length} {t('inspections.detail.rows')}
                                  </div>
                                )}
                              </div>
                            </div>
                          </div>
                        ))}
                      </div>

                      {/* Show More/Less Button */}
                      {auditLogs.length > 5 && (
                        <div className="mt-3 text-center">
                          <button
                            type="button"
                            onClick={() => setShowAllLogs(!showAllLogs)}
                            className="inline-flex items-center gap-1 px-2 py-1 text-[10px] font-medium text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300 hover:bg-blue-50 dark:hover:bg-blue-900/20 rounded-md transition-colors"
                          >
                            {showAllLogs ? (
                              <>
                                <FaChevronUp size={8} />
                                {t('inspections.detail.showLess')}
                              </>
                            ) : (
                              <>
                                <FaChevronDown size={8} />
                                {t('inspections.detail.showAll')} ({auditLogs.length})
                              </>
                            )}
                          </button>
                        </div>
                      )}

                      {/* Created By Entry - Always at bottom */}
                      {inspection?.creation && inspection?.owner && (
                        <div className="relative pl-6 mt-3">
                          <div className="absolute left-1 top-1 w-2.5 h-2.5 rounded-full border-2 border-white dark:border-gray-800 bg-green-500"></div>
                          <div className="p-2 rounded-lg bg-green-50 dark:bg-green-900/20 border border-green-100 dark:border-green-800/50">
                            <div className="flex items-center justify-between mb-1">
                              <div className="flex items-center gap-1.5">
                                <div className="w-5 h-5 rounded-full bg-green-200 dark:bg-green-800 flex items-center justify-center">
                                  <FaUser className="text-green-600 dark:text-green-400" size={8} />
                                </div>
                                <span className="text-[10px] font-medium text-gray-700 dark:text-gray-300">
                                  {formatUsername(inspection.owner)}
                                </span>
                              </div>
                              <div className="flex items-center gap-1 text-[10px] text-gray-500 dark:text-gray-400">
                                <FaClock size={8} />
                                <span title={new Date(inspection.creation).toLocaleString()}>
                                  {formatAuditDate(inspection.creation)}
                                </span>
                              </div>
                            </div>
                            <div className="text-[10px]">
                              <span className="inline-flex items-center gap-1 px-1.5 py-0.5 bg-green-100 dark:bg-green-800/50 text-green-700 dark:text-green-300 rounded font-medium">
                                <FaCheckCircle size={8} />
                                {t('inspections.detail.createdThisInspection')}
                              </span>
                            </div>
                          </div>
                        </div>
                      )}
                    </div>
                  )}
                </div>
              )}
            </div>
          )}

          {/* Delete Request */}
          {!isNewInspection && rolesLoaded && (
            <div className="bg-white dark:bg-gray-800 rounded-xl shadow-md p-4 border border-gray-200 dark:border-gray-700">
              <h2 className="text-sm font-semibold text-gray-800 dark:text-white mb-3 pb-2 border-b border-gray-200 dark:border-gray-700">
                Delete Request
              </h2>
              <DeleteRequestButton
                doctype="Inspection"
                docname={inspectionName}
                currentDeleteStatus={(inspection?.custom_delete_status ?? null) as DeleteStatus}
                userRoles={userRoles}
                isSystemManager={isSystemManager}
                redirectOnDelete="/inspections"
                onStatusChange={() => refetch()}
              />
            </div>
          )}
          
        </div>
      </div>
    </div>
  );
};

export default InspectionDetail;