import React, { useState, useEffect, useRef, useCallback, useMemo } from 'react';
import { createPortal } from 'react-dom';
import { useParams, useNavigate, useSearchParams } from 'react-router-dom';
import { useAssetDetails, useAssetMutations } from '../hooks/useAsset';
import { useDocTypeMeta } from '../hooks/useDocTypeMeta';
import { useFrappeFieldBehavior } from '../hooks/useFrappeFieldBehavior';
import { FaArrowLeft, FaSave, FaEdit, FaQrcode, FaCheck, FaCalendarAlt, FaHistory, FaFileAlt, FaTrashAlt, FaChevronDown} from 'react-icons/fa';
import type { CreateAssetData,AssetFinanceBookRow } from '../services/assetService';

import LinkField from '../components/LinkField';
import apiService from '../services/apiService';
import useDefaultHospital from '../hooks/useDefaultHospital';
import CommentSection from '../components/CommentSection';
import ActivityLog from '../components/ActivityLog';
import { isSiteEnabledHospital, buildMobileTeamSiteFilters } from '../utils/hospitalUtils';
import useUserPhccSiteFilter from '../hooks/useUserPhccSiteFilter';
import { openHtmlReport, showReportBlockedMessage, toAbsoluteSiteUrl } from '../utils/openHtmlReport';

const AssetDetail: React.FC = () => {
  const { assetName } = useParams<{ assetName: string }>();
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const duplicateFromAsset = searchParams.get('duplicate');
  
  const isNewAsset = assetName === 'new';
  const isDuplicating = isNewAsset && !!duplicateFromAsset;
  
  // Fetch DocType metadata to check allow_on_submit fields
  const { isAllowedOnSubmit } = useDocTypeMeta('Asset');
  
  // Form data state (declared early for useFrappeFieldBehavior)
  const [formData, setFormData] = useState<CreateAssetData>({
    asset_name: '',
    company: '',
    custom_serial_number: '',
    custom_local_id: '',
    location: '',
    custom_manufacturer: '',
    department: '',
    custom_asset_type: '',
    asset_category: '',
    custom_moh_id: '',
    custom_floor: '',
    custom_moh_engg: '',
    custom_smeh_engg: '',
    custom_manufacturing_year: '',
    custom_model: '',
    custom_class: '',
    custom_device_status: '',
    custom_down_time: 0,
    asset_owner_company: '',
    custom_up_time: 0,
    custom_total_hours: 0,
    custom_modality: '',
    custom_attach_image: '',
    custom_site_contractor: '',
    custom_site: '',
    custom_total_amount: 0,
    calculate_depreciation: false,
    available_for_use_date: undefined,
    finance_books:[],
    custom_service_agreement: '',
    custom_service_coverage: '',
    custom_start_date: '',
    custom_end_date: '',
    custom_warranty: false,
    custom_extended_warranty: false,
    custom__service_contract: false,
    custom_covering_spare_parts: false,
    custom_spare_parts_labour: false,
    custom_covering_labour: false,
    custom_ppm_only: false,
    custom_support_plan: '',
    custom_spare_parts: [],
    custom_total_spare_parts_amount: 0,
    custom_moh_supervisor:'',
    custom_team_leader: '',
    is_existing_asset: true,
    __islocal: false,
  });

  // Frappe dynamic field behavior - evaluates depends_on, mandatory_depends_on, read_only_depends_on
  const { 
    shouldShowField: frappeShowField, 
    isMandatory: frappeMandatory, 
    isReadOnly: frappeReadOnly,
    getFieldLabel,
    validateMandatory: frappeValidate,
    loading: fieldConfigLoading 
  } = useFrappeFieldBehavior('Asset', formData as Record<string, any>);
  
  const { asset, loading, error, refetch: refetchAsset } = useAssetDetails(
    isDuplicating ? duplicateFromAsset : (isNewAsset ? null : assetName || null)
  );
  const { createAsset, updateAsset, submitAsset, loading: saving } = useAssetMutations();

  const [isEditing, setIsEditing] = useState(isNewAsset);

  // Check document status (matching Frappe behavior)
  const docstatus = asset?.docstatus ?? 0; // Default to 0 (Draft) if not set
  const isSubmitted = docstatus === 1;
  const isCancelled = docstatus === 2;
  const isDraft = docstatus === 0;

  // Add dropdown state
  const [isActionDropdownOpen, setIsActionDropdownOpen] = useState(false);
  const actionDropdownRef = useRef<HTMLDivElement>(null);

  // Close dropdown when clicking outside (desktop only)
  useEffect(() => {
    if (!isActionDropdownOpen) return;

    const mq = window.matchMedia('(min-width: 1024px)');
    if (!mq.matches) return;

    const handleClickOutside = (event: MouseEvent) => {
      if (actionDropdownRef.current && !actionDropdownRef.current.contains(event.target as Node)) {
        setIsActionDropdownOpen(false);
      }
    };

    document.addEventListener('click', handleClickOutside);
    return () => document.removeEventListener('click', handleClickOutside);
  }, [isActionDropdownOpen]);

  useEffect(() => {
    if (!isActionDropdownOpen) return;

    const mq = window.matchMedia('(min-width: 1024px)');
    if (mq.matches) return;

    const previousOverflow = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => {
      document.body.style.overflow = previousOverflow;
    };
  }, [isActionDropdownOpen]);

  // Debug logging (development only)
  useEffect(() => {
    if (import.meta.env.DEV && asset) {
      console.log(`[AssetDetail] Document Status:`, {
        docstatus,
        isDraft,
        isSubmitted,
        isCancelled,
        isEditing
      });
    }
  }, [asset, docstatus, isDraft, isSubmitted, isCancelled, isEditing]);

  // Helper function to determine if a field should be disabled
  // This matches Frappe's behavior:
  // - Draft (0): All fields editable when in edit mode
  // - Submitted (1): Only fields with allow_on_submit can be edited
  // - Cancelled (2): No fields can be edited
  // - Also checks Frappe's read_only_depends_on expressions
  const isFieldDisabled = useCallback((fieldname: string): boolean => {
    // Always disabled when not in edit mode
    if (!isEditing) return true;
    
    // Cancelled documents cannot be edited at all
    if (isCancelled) return true;
    
    // Check Frappe's read_only_depends_on
    if (frappeReadOnly(fieldname)) return true;
    
    // Submitted documents: only allow editing fields marked as allow_on_submit
    if (isSubmitted) {
      return !isAllowedOnSubmit(fieldname);
    }
    
    // Draft documents: all fields are editable when in edit mode
    if (isDraft) {
      return false;
    }
    
    // Default: disable if status is unknown
    return true;
  }, [isEditing, isCancelled, isSubmitted, isDraft, isAllowedOnSubmit, frappeReadOnly]);
  
  // Helper function to check if field should be visible based on Frappe's depends_on
  const shouldShowField = useCallback((fieldname: string): boolean => {
    return frappeShowField(fieldname);
  }, [frappeShowField]);
  
  // Helper function to check if field is mandatory based on Frappe's mandatory_depends_on
  const isFieldMandatory = useCallback((fieldname: string): boolean => {
    return frappeMandatory(fieldname);
  }, [frappeMandatory]);

  const [userSiteName, setUserSiteName] = useState('');
  const [departmentFilters, setDepartmentFilters] = useState<Record<string, any>>({});
  const { userPhccSiteName, siteLocked } = useUserPhccSiteFilter();

  const shouldShowSiteNameField = useMemo(
    () => isSiteEnabledHospital(formData.company),
    [formData.company]
  );

  const mobileTeamSiteFilters = useMemo(
    () => buildMobileTeamSiteFilters(formData.company, userPhccSiteName),
    [formData.company, userPhccSiteName]
  );

  const mohSupervisorFilters = useMemo(() => {
    if (!formData.company) {
      return {};
    }
    return {
      custom_site_name: formData.company,
      role_profile_name: 'MOH Supervisor',
    };
  }, [formData.company]);

  const smehEnggFilters = useMemo(() => {
    if (!formData.company) {
      return {};
    }
    return {
      custom_site_name: formData.company,
      role_profile_name: 'Technician',
    };
  }, [formData.company]);

  // Set default available_for_use_date for new assets
  useEffect(() => {
    if (isNewAsset && !formData.available_for_use_date) {
      setFormData(prev => ({
        ...prev,
        available_for_use_date: new Date().toISOString().split('T')[0],
        __islocal: true
      }));
    }
  }, [isNewAsset]);

  // Load user details on mount (hospital for department filters)
  useEffect(() => {
    async function loadUserDetails() {
      try {
        const user = await apiService.getUserDetails();
        setUserSiteName(user.custom_site_name || '');
      } catch (err) {
        console.error('Error loading user details', err);
      }
    }

    loadUserDetails();
  }, []);

  // Auto-set site name from user profile when available
  useEffect(() => {
    if (!userPhccSiteName) return;

    setFormData((prev) => {
      if (prev.custom_site) return prev;
      return { ...prev, custom_site: userPhccSiteName };
    });
  }, [userPhccSiteName]);

  useDefaultHospital(setFormData, {
    fields: ['company', 'asset_owner_company'],
  });

  const addFinanceRow = () => {
    // Get today's date in YYYY-MM-DD format for date input
    const today = new Date().toISOString().split('T')[0];
    
    const newRow: AssetFinanceBookRow = {
      finance_book: 'Depreciation Entries',
      depreciation_method: 'Straight Line',
      total_number_of_depreciations: 10,
      frequency_of_depreciation: 12,
      depreciation_start_date: today
    };
    
    setFormData(prev => ({
      ...prev,
      finance_books: [
        ...(prev.finance_books || []),
        newRow
      ]
    }));
  };

  const removeFinanceRow = (index: number) => {
    setFormData(prev => {
      const rows = [...(prev.finance_books || [])];
      rows.splice(index, 1);
      return { ...prev, finance_books: rows };
    });
  };

  const updateFinanceRow = (index: number, patch: Partial<AssetFinanceBookRow>) => {
    setFormData(prev => {
      const rows = [...(prev.finance_books || [])];
      rows[index] = { ...(rows[index] || {}), ...patch };
      return { ...prev, finance_books: rows };
    });
  };

  // Auto-add finance_books row when calculate_depreciation is checked and finance_books is empty
  // Based on Frappe client script logic
  useEffect(() => {
    if (formData.calculate_depreciation && (!formData.finance_books || formData.finance_books.length === 0)) {
      const today = new Date().toISOString().split('T')[0];
      const newRow: AssetFinanceBookRow = {
        finance_book: 'Depreciation Entries',
        depreciation_method: 'Straight Line',
        total_number_of_depreciations: 10,
        frequency_of_depreciation: 12,
        depreciation_start_date: today
      };
      setFormData(prev => ({
        ...prev,
        finance_books: [newRow]
      }));
    }
  }, [formData.calculate_depreciation]);

  // Spare Parts calculation functions
  interface SparePartRow {
    item_code?: string;
    item_name?: string;
    qty?: number;
    rate?: number;
    amount?: number;
    uom?: string;
    work_order?: string;
  }

  const updateSparePartRow = (index: number, field: keyof SparePartRow, value: any) => {
    setFormData(prev => {
      const rows = [...(prev.custom_spare_parts || [])];
      const updatedRow = { ...rows[index] };
      
      if (field === 'qty' || field === 'rate') {
        updatedRow[field] = value;
        // Calculate amount = qty * rate
        updatedRow.amount = (updatedRow.qty || 0) * (updatedRow.rate || 0);
      } else {
        updatedRow[field] = value;
      }
      
      rows[index] = updatedRow;
      
      // Calculate total
      const total = rows.reduce((sum, row) => sum + (row.amount || 0), 0);
      
      return {
        ...prev,
        custom_spare_parts: rows,
        custom_total_spare_parts_amount: total
      };
    });
  };

  const addSparePartRow = () => {
    setFormData(prev => ({
      ...prev,
      custom_spare_parts: [
        ...(prev.custom_spare_parts || []),
        { qty: 0, rate: 0, amount: 0 }
      ]
    }));
  };

  const removeSparePartRow = (index: number) => {
    setFormData(prev => {
      const rows = [...(prev.custom_spare_parts || [])];
      rows.splice(index, 1);
      const total = rows.reduce((sum, row) => sum + (row.amount || 0), 0);
      return {
        ...prev,
        custom_spare_parts: rows,
        custom_total_spare_parts_amount: total
      };
    });
  };

  // Calculate total hours and up time based on available_for_use_date
  // Based on Frappe client script logic
  useEffect(() => {
    if (formData.available_for_use_date) {
      // Parse the available date
      const availableDate = new Date(formData.available_for_use_date);
      const currentDate = new Date();
      
      // Get the time difference in milliseconds and convert it to days
      const timeDiff = currentDate.getTime() - availableDate.getTime();
      const dayDiff = Math.floor(timeDiff / (1000 * 60 * 60 * 24));
      
      // Convert days to hours
      const totalHours = dayDiff * 24;
      
      // Calculate up time = total hours - down time
      const upTime = totalHours - (formData.custom_down_time || 0);
      
      setFormData(prev => ({
        ...prev,
        custom_total_hours: totalHours,
        custom_up_time: upTime
      }));
    }
  }, [formData.available_for_use_date, formData.custom_down_time]);

  // Handle custom_asset_type changes - auto-set custom_site_contractor
  // Based on Frappe client script: when asset type is "biomedical", set contractor to "SAMAMA"
  const prevAssetTypeRef = useRef<string>('');
  
  useEffect(() => {
    if (!isEditing) {
      // Reset ref when not editing
      prevAssetTypeRef.current = formData.custom_asset_type || '';
      return;
    }
    
    const currentAssetType = (formData.custom_asset_type || '').toString().trim().toLowerCase();
    const prevAssetType = (prevAssetTypeRef.current || '').toString().trim().toLowerCase();
    
    // Only process if asset type actually changed
    if (currentAssetType === prevAssetType) {
      return;
    }
    
    // Update the ref for next comparison
    prevAssetTypeRef.current = formData.custom_asset_type || '';
    
    if (currentAssetType === 'biomedical') {
      // If type changed to biomedical, set contractor to SAMAMA (only if not already set)
      if (formData.custom_site_contractor !== 'SAMAMA') {
        setFormData(prev => ({
          ...prev,
          custom_site_contractor: 'SAMAMA'
        }));
      }
    } else if (prevAssetType === 'biomedical') {
      // If type changed FROM biomedical to something else, only clear if it was auto-set to SAMAMA
      // This avoids overwriting manual values
      if (formData.custom_site_contractor === 'SAMAMA') {
        setFormData(prev => ({
          ...prev,
          custom_site_contractor: ''
        }));
      }
    }
  }, [formData.custom_asset_type, isEditing]);

  // Update department filters when company or userSiteName changes
  // Based on Frappe client script logic
  useEffect(() => {
    const filters: Record<string, any> = {};

    if (formData.company) {
      filters['company'] = formData.company;
    }

    // Logic from Frappe script:
    // If site_name starts with "Mobile", exclude Bio department (but script has it commented out)
    // Otherwise, exclude Non Bio department
    // Also check if company starts with "Mobile"
    const isMobileSite =
      isSiteEnabledHospital(userSiteName) || isSiteEnabledHospital(formData.company);

    if (userSiteName || formData.company) {
      if (isMobileSite) {
        // Mobile sites: exclude Non Bio departments (as per script logic)
        filters['department_name'] = ['not like', 'Non Bio%'];
      } else {
        // Non-Mobile sites: exclude Non Bio departments
        filters['department_name'] = ['not like', 'Non Bio%'];
      }
    }

    setDepartmentFilters(filters);
  }, [formData.company, userSiteName]);

  // Load asset data for editing or duplicating
  useEffect(() => {
    if (asset) {
      // Initialize the asset type ref when asset loads
      prevAssetTypeRef.current = asset.custom_asset_type || '';
      
      setFormData({
        asset_name: isDuplicating ? `${asset.asset_name} (Copy)` : (asset.asset_name || ''),
        company: asset.company || '',
        custom_serial_number: isDuplicating ? '' : (asset.custom_serial_number || ''),
        custom_local_id: isDuplicating ? '' : ((asset as any).custom_local_id || ''),
        location: asset.location || '',
        custom_manufacturer: asset.custom_manufacturer || '',
        department: asset.department || '',
        custom_moh_supervisor: asset.custom_moh_supervisor || '',
        custom_team_leader: asset.custom_team_leader || '',
        custom_asset_type: asset.custom_asset_type || '',
        asset_category: asset.asset_category || '',
        custom_moh_id: (asset as any).custom_moh_id || '',
        custom_floor: (asset as any).custom_floor || '',
        custom_moh_engg: (asset as any).custom_moh_engg || '',
        custom_smeh_engg: (asset as any).custom_smeh_engg || '',
        custom_manufacturing_year: asset.custom_manufacturing_year || '',
        custom_model: asset.custom_model || '',
        custom_class: asset.custom_class || '',
        custom_device_status: asset.custom_device_status || '',
        custom_down_time: asset.custom_down_time || 0,
        asset_owner_company: asset.asset_owner_company || '',
        custom_up_time: asset.custom_up_time || 0,
        custom_total_hours: (asset as any).custom_total_hours || 0,
        custom_modality: asset.custom_modality || '',
        custom_attach_image: asset.custom_attach_image || '',
        custom_site_contractor: asset.custom_site_contractor || '',
        custom_site: (asset as any).custom_site || '',
        custom_total_amount: asset.custom_total_amount || 0,
        gross_purchase_amount: asset.gross_purchase_amount || 0,
        available_for_use_date: asset.available_for_use_date || '',
        calculate_depreciation: asset.calculate_depreciation || false,
        finance_books: asset.finance_books || [],
        custom_service_agreement: (asset as any).custom_service_agreement || '',
        custom_service_coverage: (asset as any).custom_service_coverage || '',
        custom_start_date: (asset as any).custom_start_date ? (asset as any).custom_start_date.split(' ')[0] : '',
        custom_end_date: (asset as any).custom_end_date ? (asset as any).custom_end_date.split(' ')[0] : '',
        // Checkbox fields
        custom_warranty: (asset as any).custom_warranty || false,
        custom_extended_warranty: (asset as any).custom_extended_warranty || false,
        custom__service_contract: (asset as any).custom__service_contract || false,
        custom_covering_spare_parts: (asset as any).custom_covering_spare_parts || false,
        custom_spare_parts_labour: (asset as any).custom_spare_parts_labour || false,
        custom_covering_labour: (asset as any).custom_covering_labour || false,
        custom_ppm_only: (asset as any).custom_ppm_only || false,
        custom_support_plan: (asset as any).custom_support_plan || '',
        // Spare parts
        custom_spare_parts: asset.custom_spare_parts || [],
        custom_total_spare_parts_amount: (asset as any).custom_total_spare_parts_amount || 0,
      });
    }
  }, [asset, isDuplicating]);

  const [qrCodeUrl, setQrCodeUrl] = useState<string | null>(null);

  useEffect(() => {
    if (!assetName || assetName === "new") return;

    const fetchQRCode = async () => {
      try {
        const directUrl = `/files/${assetName}-qr.png`;

        const response = await fetch(directUrl, { method: "HEAD" });

        if (response.ok) {
          setQrCodeUrl(directUrl);
          return;
        }

        const fileRes = await apiService.apiCall<any>(
          `/api/resource/File?filters=[["File","attached_to_name","=","${assetName}"]]`
        );

        if (fileRes?.data?.length > 0) {
          setQrCodeUrl(fileRes.data[0].file_url);
        }
      } catch (error) {
        console.error("Error loading QR code:", error);
      }
    };

    fetchQRCode();
  }, [assetName, asset]);

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

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!formData.asset_name) {
      alert('Please enter an Asset Name');
      return;
    }
    
    if (!formData.custom_asset_type) {
      alert('Please select an Asset Type');
      return;
    }
    
    console.log('Submitting asset data:', formData);
    
    try {
      if (isNewAsset || isDuplicating) {
        const newAsset = await createAsset(formData);
        if (newAsset.name) {
          const qrUrl = `/files/${newAsset.name}-qr.png`;
          setQrCodeUrl(qrUrl);
        }
        const successMessage = isDuplicating 
          ? 'Asset duplicated successfully!' 
          : 'Asset created successfully!';
        alert(successMessage);
        navigate(`/assets/${newAsset.name}`);
      } else if (assetName) {
        await updateAsset(assetName, formData);
        alert('Asset updated successfully!');
        setIsEditing(false);
        // Refresh asset data to get updated docstatus
        refetchAsset();
      }
    } catch (err) {
      console.error('Asset save error:', err);
      const errorMessage = err instanceof Error ? err.message : 'Unknown error';
      
      if (errorMessage.includes('404') || errorMessage.includes('not found') || 
          errorMessage.includes('has no attribute') || errorMessage.includes('417')) {
        alert(
          '⚠️ Asset API Not Deployed\n\n' +
          'The Asset API endpoint (asset_api.py) is not deployed on your Frappe server yet.\n\n' +
          'To fix this:\n' +
          '1. SSH into your Frappe server\n' +
          '2. Navigate to: frappe-bench/apps/asset_lite/asset_lite/api/\n' +
          '3. Create the file: asset_api.py\n' +
          '4. Copy the content from frappe_asset_api.py in this project\n' +
          '5. Restart Frappe: bench restart\n\n' +
          'Error: ' + errorMessage
        );
      } else {
        alert('Failed to save asset:\n\n' + errorMessage);
      }
    }
  };

  const handleSubmitDocument = async () => {
    if (!assetName || isNewAsset) {
      alert('Cannot submit: Asset not saved yet');
      return;
    }

    if (!window.confirm('Are you sure you want to submit this asset? Once submitted, only fields marked as "Allow on Submit" can be edited.')) {
      return;
    }

    try {
      await submitAsset(assetName);
      alert('Asset submitted successfully!');
      // Refresh asset data to get updated docstatus
      refetchAsset();
      setIsEditing(false);
    } catch (err) {
      console.error('Asset submit error:', err);
      const errorMessage = err instanceof Error ? err.message : 'Unknown error';
      alert('Failed to submit asset:\n\n' + errorMessage);
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-screen bg-gray-50 dark:bg-gray-900">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500 mx-auto"></div>
          <p className="mt-4 text-gray-600 dark:text-gray-400">Loading asset details...</p>
        </div>
      </div>
    );
  }

  if (error && !isNewAsset && !isDuplicating) {
    return (
      <div className="p-4 sm:p-6 bg-gray-50 dark:bg-gray-900 min-h-screen min-w-0 overflow-x-hidden">
        <div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-4">
          <p className="text-red-600 dark:text-red-400">Error: {error}</p>
          <button 
            onClick={() => navigate('/assets')}
            className="mt-2 text-red-700 dark:text-red-400 underline hover:text-red-800 dark:hover:text-red-300"
          >
            Back to assets list
          </button>
        </div>
      </div>
    );
  }

  if (error && isDuplicating) {
    return (
      <div className="p-4 sm:p-6 bg-gray-50 dark:bg-gray-900 min-h-screen min-w-0 overflow-x-hidden">
        <div className="bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg p-4">
          <h3 className="text-lg font-semibold text-yellow-800 dark:text-yellow-300 mb-2">
            Source Asset Not Found
          </h3>
          <p className="text-yellow-700 dark:text-yellow-400">
            The asset you're trying to duplicate could not be found.
          </p>
          <div className="mt-4 flex gap-3">
            <button 
              onClick={() => navigate('/assets/new')}
              className="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors"
            >
              Create New Asset
            </button>
            <button 
              onClick={() => navigate('/assets')}
              className="px-4 py-2 bg-gray-600 hover:bg-gray-700 text-white rounded-lg transition-colors"
            >
              Back to Assets List
            </button>
          </div>
        </div>
      </div>
    );
  }

  const runAssetAction = (action: () => void) => {
    const isDesktop = window.matchMedia('(min-width: 1024px)').matches;
    if (isDesktop) {
      action();
      setIsActionDropdownOpen(false);
      return;
    }
    setIsActionDropdownOpen(false);
    window.setTimeout(() => action(), 0);
  };

  const handlePrintQR = () => {
    if (!qrCodeUrl || !asset) return;

    const reportHandle = openHtmlReport();
    if (!reportHandle) {
      showReportBlockedMessage();
      return;
    }

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

  const handlePrintStayPlugged = () => {
  const reportHandle = openHtmlReport();
  if (!reportHandle) {
    showReportBlockedMessage();
    return;
  }

  reportHandle.write(`
    <!DOCTYPE html>
    <html>
      <head>
        <title>Stay Plugged</title>
        <style>
          @page {
            margin: 0.5in;
            size: auto;
          }
          * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
          }
          body {
            font-family: Arial, sans-serif;
            display: flex;
            align-items: center;
            justify-content: center;
            min-height: 100vh;
            padding: 0;
          }
          .image-container {
            text-align: center;
            padding: 40px;
            max-width: 100%;
          }
          .stay-plugged-image {
            max-width: 100%;
            height: auto;
            display: block;
            margin: 0 auto;
          }
        </style>
      </head>
      <body>
        <div class="image-container">
          <img src="${toAbsoluteSiteUrl('/files/Stay Plugged.jpg')}" alt="Stay Plugged" class="stay-plugged-image" onload="window.print();" />
        </div>
      </body>
    </html>
  `);
};

const handlePPMPlan = async () => {
  if (!assetName || isNewAsset) {
    alert('Please save the asset first to view PPM Plan');
    return;
  }

  const reportHandle = openHtmlReport(`
    <!DOCTYPE html>
    <html><head><title>PPM Plan</title></head>
    <body style="font-family:Arial,sans-serif;padding:24px;">Loading PPM Plan...</body></html>
  `);
  if (!reportHandle) {
    showReportBlockedMessage();
    return;
  }

  try {
    // Fetch maintenance logs with "Planned" status for this asset
    const response = await apiService.apiCall<any>(
      `/api/resource/Asset Maintenance Log?filters=[["asset_name","=","${assetName}"],["maintenance_status","=","Planned"]]&fields=["name","due_date","periodicity","custom_asset_names","asset_name","maintenance_type","assign_to_name"]`
    );

    const maintenanceLogs = response?.data || [];

    // Helper function to add days/months/years
    const addDays = (date: Date, days: number): Date => {
      const result = new Date(date);
      result.setDate(result.getDate() + days);
      return result;
    };

    const addMonths = (date: Date, months: number): Date => {
      const result = new Date(date);
      result.setMonth(result.getMonth() + months);
      return result;
    };

    const addYears = (date: Date, years: number): Date => {
      const result = new Date(date);
      result.setFullYear(result.getFullYear() + years);
      return result;
    };

    const getNextDueDate = (currentDate: Date, periodicity: string): Date => {
      switch (periodicity) {
        case 'Daily':
          return addDays(currentDate, 1);
        case 'Weekly':
          return addDays(currentDate, 7);
        case 'Monthly':
          return addMonths(currentDate, 1);
        case 'Quarterly':
          return addMonths(currentDate, 3);
        case 'Half-yearly':
          return addMonths(currentDate, 6);
        case 'Yearly':
          return addYears(currentDate, 1);
        case '2 Yearly':
          return addYears(currentDate, 2);
        case '3 Yearly':
          return addYears(currentDate, 3);
        default:
          return addMonths(currentDate, 1);
      }
    };

    const formatDate = (date: Date): string => {
      return date.toISOString().split('T')[0];
    };

    // Generate PPM data for next 5 years
    const maxDate = addYears(new Date(), 5);
    const ppmData: Array<{
      asset_name: string;
      custom_asset_names: string;
      serial_number: string;
      due_date: string;
      periodicity: string;
      maintenance_type: string;
      assign_to_name: string;
      status: string;
    }> = [];

    for (const log of maintenanceLogs) {
      let dueDate = new Date(log.due_date);
      const periodicity = log.periodicity || 'Monthly';

      // Generate due dates for the next 5 years (max 60 iterations)
      for (let i = 0; i < 60; i++) {
        ppmData.push({
          asset_name: log.asset_name || '',
          custom_asset_names: log.custom_asset_names || '',
          serial_number: formData.custom_serial_number || 'N/A',
          due_date: formatDate(dueDate),
          periodicity: periodicity,
          maintenance_type: log.maintenance_type || '',
          assign_to_name: log.assign_to_name || '',
          status: 'Planned'
        });

        dueDate = getNextDueDate(dueDate, periodicity);

        if (dueDate > maxDate) {
          break;
        }
      }
    }

    // Sort by due date
    ppmData.sort((a, b) => new Date(a.due_date).getTime() - new Date(b.due_date).getTime());

    const tableRows = ppmData.length > 0
      ? ppmData.map((row, index) => `
          <tr class="${index % 2 === 0 ? 'bg-white' : 'bg-gray-50'}">
            <td class="border px-3 py-2">${row.asset_name}</td>
            <td class="border px-3 py-2">${row.custom_asset_names}</td>
            <td class="border px-3 py-2">${row.serial_number}</td>
            <td class="border px-3 py-2">${row.due_date}</td>
            <td class="border px-3 py-2">${row.periodicity}</td>
            <td class="border px-3 py-2">${row.maintenance_type}</td>
            <td class="border px-3 py-2">${row.assign_to_name}</td>
            <td class="border px-3 py-2">
              <span class="px-2 py-1 bg-yellow-100 text-yellow-800 rounded text-xs">${row.status}</span>
            </td>
          </tr>
        `).join('')
      : `<tr><td colspan="8" class="border px-3 py-4 text-center text-gray-500">No planned maintenance found for this asset</td></tr>`;

    reportHandle.write(`
      <!DOCTYPE html>
      <html>
        <head>
          <title>PPM Plan - ${assetName}</title>
          <style>
            @page {
              margin: 0.5in;
              size: landscape;
            }
            * {
              margin: 0;
              padding: 0;
              box-sizing: border-box;
            }
            body {
              font-family: Arial, sans-serif;
              padding: 20px;
              background: #f5f5f5;
            }
            .container {
              max-width: 1400px;
              margin: 0 auto;
              background: white;
              padding: 20px;
              border-radius: 8px;
              box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            }
            .header {
              display: flex;
              justify-content: space-between;
              align-items: center;
              margin-bottom: 20px;
              padding-bottom: 15px;
              border-bottom: 2px solid #3b82f6;
            }
            h1 {
              font-size: 24px;
              color: #1f2937;
            }
            .asset-info {
              font-size: 14px;
              color: #6b7280;
            }
            .btn {
              padding: 10px 20px;
              font-size: 14px;
              border: none;
              border-radius: 5px;
              cursor: pointer;
              margin-left: 10px;
            }
            .btn-print {
              background: #3b82f6;
              color: white;
            }
            .btn-print:hover {
              background: #2563eb;
            }
            .btn-close {
              background: #6b7280;
              color: white;
            }
            .btn-close:hover {
              background: #4b5563;
            }
            .table-container {
              overflow-x: auto;
              margin-top: 20px;
            }
            table {
              width: 100%;
              border-collapse: collapse;
              font-size: 13px;
            }
            th {
              background: #3b82f6;
              color: white;
              padding: 12px 8px;
              text-align: left;
              border: 1px solid #2563eb;
              font-weight: 600;
            }
            td {
              border: 1px solid #e5e7eb;
              padding: 8px;
            }
            .bg-white { background: white; }
            .bg-gray-50 { background: #f9fafb; }
            .summary {
              margin-top: 20px;
              padding: 15px;
              background: #f0f9ff;
              border-radius: 5px;
              font-size: 14px;
              color: #1e40af;
            }
            @media print {
              .no-print { display: none; }
              body { background: white; padding: 0; }
              .container { box-shadow: none; padding: 0; }
            }
          </style>
        </head>
        <body>
          <div class="container">
            <div class="header">
              <div>
                <h1>PPM Planner Report</h1>
                <div class="asset-info">
                  <strong>Asset ID:</strong> ${assetName} | 
                  <strong>Asset Name:</strong> ${formData.asset_name || 'N/A'} |
                  <strong>Generated:</strong> ${new Date().toLocaleDateString()}
                </div>
              </div>
              <div class="no-print">
                <button class="btn btn-print" onclick="window.print()">Print / Save PDF</button>
                <button class="btn btn-close" onclick="window.close()">Close</button>
              </div>
            </div>
            
            <div class="table-container">
              <table>
                <thead>
                  <tr>
                    <th>Asset ID</th>
                    <th>Asset Name</th>
                    <th>Serial Number</th>
                    <th>Due Date</th>
                    <th>Periodicity</th>
                    <th>Maintenance Type</th>
                    <th>Assigned To</th>
                    <th>Status</th>
                  </tr>
                </thead>
                <tbody>
                  ${tableRows}
                </tbody>
              </table>
            </div>
            
            <div class="summary">
              <strong>Summary:</strong> ${ppmData.length} planned maintenance entries for the next 5 years
            </div>
          </div>
        </body>
      </html>
    `);

  } catch (err) {
    console.error('Error fetching PPM Plan:', err);
    alert('Failed to load PPM Plan. Please try again.');
  }
  };

  const handleAssetHistory = async () => {
  if (!assetName || isNewAsset) {
    alert('Please save the asset first to view Asset History');
    return;
  }

  try {
    const reportHandle = openHtmlReport(`
      <!DOCTYPE html>
      <html><head><title>Asset History</title></head>
      <body style="font-family:Arial,sans-serif;padding:24px;">Loading Asset History...</body></html>
    `);
    if (!reportHandle) {
      showReportBlockedMessage();
      return;
    }

    // Fetch Asset Details
    const assetResponse = await apiService.apiCall<any>(
      `/api/resource/Asset/${assetName}`
    );
    const assetData = assetResponse?.data || {};

    // Fetch Work Orders
    const workOrdersResponse = await apiService.apiCall<any>(
      `/api/resource/Work_Order?filters=[["asset","=","${assetName}"]]&fields=["name","work_order_type","repair_status","creation","total_repair_cost"]`
    );
    const workOrders = workOrdersResponse?.data || [];

    // Fetch Asset Maintenance Records
    const maintenanceResponse = await apiService.apiCall<any>(
      `/api/resource/Asset Maintenance?filters=[["asset_name","=","${assetName}"]]&fields=["name","maintenance_team","custom_type_of_maintenance"]`
    );
    const maintenanceRecords = maintenanceResponse?.data || [];

    // Fetch Maintenance Logs
    let maintenanceLogs: any[] = [];
    let maintenanceTasks: any[] = [];
    
    for (const maintenance of maintenanceRecords) {
      // Fetch full maintenance record with tasks
      const fullMaintenanceResponse = await apiService.apiCall<any>(
        `/api/resource/Asset Maintenance/${maintenance.name}`
      );
      const fullMaintenance = fullMaintenanceResponse?.data || {};
      
      if (fullMaintenance.asset_maintenance_tasks) {
        maintenanceTasks = [...maintenanceTasks, ...fullMaintenance.asset_maintenance_tasks.map((t: any) => ({
          ...t,
          maintenance_id: maintenance.name
        }))];
      }

      // Fetch maintenance logs
      const logsResponse = await apiService.apiCall<any>(
        `/api/resource/Asset Maintenance Log?filters=[["asset_maintenance","=","${maintenance.name}"]]&fields=["name","maintenance_status","assign_to_name","maintenance_type","due_date","completion_date","periodicity","actions_performed"]&order_by=completion_date desc`
      );
      maintenanceLogs = [...maintenanceLogs, ...(logsResponse?.data || [])];
    }

    // Separate completed and pending logs
    const completedLogs = maintenanceLogs.filter(log => log.maintenance_status === 'Completed');
    const pendingLogs = maintenanceLogs.filter(log => log.maintenance_status !== 'Completed');

    // Count maintenance status
    const statusCounts: Record<string, number> = {};
    maintenanceLogs.forEach(log => {
      statusCounts[log.maintenance_status] = (statusCounts[log.maintenance_status] || 0) + 1;
    });

    // Get spare parts from asset
    const spareParts = assetData.custom_spare_parts || [];
    
    // Group spare parts by work order
    const groupedSpareParts: Record<string, any[]> = {};
    spareParts.forEach((sp: any) => {
      const wo = sp.work_order || 'Unassigned';
      if (!groupedSpareParts[wo]) {
        groupedSpareParts[wo] = [];
      }
      groupedSpareParts[wo].push(sp);
    });

    // Generate Work Orders HTML
    const workOrdersHTML = workOrders.length > 0
      ? workOrders.map((wo: any, index: number) => {
          const statusClass = wo.repair_status === 'Completed' 
            ? 'bg-green-100 text-green-800' 
            : wo.repair_status === 'Work In Progress'
            ? 'bg-yellow-100 text-yellow-800'
            : 'bg-gray-100 text-gray-800';
          return `
            <tr class="${index % 2 === 0 ? 'bg-white' : 'bg-gray-50'}">
              <td class="px-4 py-3 font-medium text-blue-600">${wo.name}</td>
              <td class="px-4 py-3">${wo.work_order_type || '-'}</td>
              <td class="px-4 py-3"><span class="px-2 py-1 rounded-full text-xs font-medium ${statusClass}">${wo.repair_status || '-'}</span></td>
              <td class="px-4 py-3 font-semibold">${parseFloat(wo.total_repair_cost || 0).toFixed(2)} ر.س</td>
              <td class="px-4 py-3 text-gray-500">${wo.creation ? new Date(wo.creation).toLocaleDateString() : '-'}</td>
            </tr>
          `;
        }).join('')
      : `<tr><td colspan="5" class="px-4 py-8 text-center text-gray-500">No Work Orders Found</td></tr>`;

    // Generate Spare Parts HTML
    let sparePartsHTML = '';
    if (Object.keys(groupedSpareParts).length > 0) {
      Object.keys(groupedSpareParts).forEach(workOrder => {
        sparePartsHTML += `
          <div class="mb-4">
            <div class="bg-amber-50 border-l-4 border-amber-400 px-4 py-2 mb-2">
              <span class="font-medium">Work Order: </span>
              <span class="text-blue-600 font-medium">${workOrder}</span>
            </div>
            <table class="w-full">
              <thead>
                <tr class="bg-gray-100">
                  <th class="px-4 py-2 text-left text-xs font-semibold text-gray-600">Item Name</th>
                  <th class="px-4 py-2 text-left text-xs font-semibold text-gray-600">Quantity</th>
                  <th class="px-4 py-2 text-left text-xs font-semibold text-gray-600">Cost</th>
                  <th class="px-4 py-2 text-left text-xs font-semibold text-gray-600">Amount</th>
                </tr>
              </thead>
              <tbody>
                ${groupedSpareParts[workOrder].map((sp: any, idx: number) => `
                  <tr class="${idx % 2 === 0 ? 'bg-white' : 'bg-gray-50'}">
                    <td class="px-4 py-2">${sp.item_code || '-'}</td>
                    <td class="px-4 py-2">${sp.qty || 0}</td>
                    <td class="px-4 py-2">${sp.rate || 0} ر.س</td>
                    <td class="px-4 py-2 font-medium">${sp.amount || 0} ر.س</td>
                  </tr>
                `).join('')}
              </tbody>
            </table>
          </div>
        `;
      });
    } else {
      sparePartsHTML = `<p class="text-gray-500 text-center py-8">No Spare Parts Used</p>`;
    }

    // Generate Maintenance Records HTML
    const maintenanceRecordsHTML = maintenanceRecords.length > 0
      ? maintenanceRecords.map((m: any) => `
          <div class="bg-white border rounded-lg p-4 mb-3 shadow-sm">
            <div class="flex justify-between items-start">
              <div>
                <p class="text-sm text-gray-500">Maintenance ID</p>
                <p class="font-medium text-blue-600">${m.name}</p>
              </div>
              <div class="text-right">
                <p class="text-sm text-gray-500">Type</p>
                <p class="font-medium">${m.custom_type_of_maintenance || '-'}</p>
              </div>
            </div>
            <div class="mt-2">
              <p class="text-sm text-gray-500">Maintenance Team</p>
              <p class="font-medium">${m.maintenance_team || '-'}</p>
            </div>
          </div>
        `).join('')
      : `<p class="text-gray-500 text-center py-8">No Maintenance Records Found</p>`;

    // Generate Maintenance Tasks HTML
    const maintenanceTasksHTML = maintenanceTasks.length > 0
      ? maintenanceTasks.map((task: any, index: number) => `
          <tr class="${index % 2 === 0 ? 'bg-white' : 'bg-gray-50'}">
            <td class="px-4 py-3">${task.assign_to_name || '-'}</td>
            <td class="px-4 py-3">${task.periodicity || '-'}</td>
            <td class="px-4 py-3">${task.next_due_date || '-'}</td>
            <td class="px-4 py-3 text-blue-600 text-sm">${task.maintenance_id || '-'}</td>
          </tr>
        `).join('')
      : `<tr><td colspan="4" class="px-4 py-8 text-center text-gray-500">No Maintenance Tasks Found</td></tr>`;

    // Generate Status Summary HTML
    const statusSummaryHTML = Object.keys(statusCounts).length > 0
      ? Object.entries(statusCounts).map(([status, count]) => {
          const statusClass = status === 'Completed' 
            ? 'bg-green-100 text-green-800 border-green-200' 
            : status === 'Planned'
            ? 'bg-blue-100 text-blue-800 border-blue-200'
            : 'bg-yellow-100 text-yellow-800 border-yellow-200';
          return `
            <div class="flex items-center justify-between p-3 rounded-lg border ${statusClass}">
              <span class="font-medium">${status}</span>
              <span class="text-2xl font-bold">${count}</span>
            </div>
          `;
        }).join('')
      : `<p class="text-gray-500 text-center">No Data</p>`;

    // Generate Completed Logs HTML
    const completedLogsHTML = completedLogs.length > 0
      ? completedLogs.map((log: any, index: number) => `
          <tr class="${index % 2 === 0 ? 'bg-white' : 'bg-gray-50'}">
            <td class="px-3 py-2 text-blue-600 font-medium">${log.name}</td>
            <td class="px-3 py-2">${log.assign_to_name || '-'}</td>
            <td class="px-3 py-2">${log.maintenance_type || '-'}</td>
            <td class="px-3 py-2">${log.due_date || '-'}</td>
            <td class="px-3 py-2 text-green-600 font-medium">${log.completion_date || '-'}</td>
            <td class="px-3 py-2">${log.periodicity || '-'}</td>
            <td class="px-3 py-2 text-sm text-gray-600">${log.actions_performed || '-'}</td>
          </tr>
        `).join('')
      : `<tr><td colspan="7" class="px-4 py-8 text-center text-gray-500">No Completed Maintenance Logs</td></tr>`;

    // Generate Pending Logs HTML
    const pendingLogsHTML = pendingLogs.length > 0
      ? pendingLogs.map((log: any, index: number) => {
          const statusClass = log.maintenance_status === 'Planned' 
            ? 'bg-blue-100 text-blue-800' 
            : 'bg-yellow-100 text-yellow-800';
          return `
            <tr class="${index % 2 === 0 ? 'bg-white' : 'bg-gray-50'}">
              <td class="px-3 py-2 text-blue-600 font-medium">${log.name}</td>
              <td class="px-3 py-2">${log.assign_to_name || '-'}</td>
              <td class="px-3 py-2">${log.maintenance_type || '-'}</td>
              <td class="px-3 py-2">${log.due_date || '-'}</td>
              <td class="px-3 py-2">${log.periodicity || '-'}</td>
              <td class="px-3 py-2"><span class="px-2 py-1 rounded-full text-xs font-medium ${statusClass}">${log.maintenance_status || '-'}</span></td>
              <td class="px-3 py-2 text-sm text-gray-600">${log.actions_performed || '-'}</td>
            </tr>
          `;
        }).join('')
      : `<tr><td colspan="7" class="px-4 py-8 text-center text-gray-500">No Pending/Planned Maintenance Logs</td></tr>`;

    reportHandle.write(`
      <!DOCTYPE html>
      <html>
        <head>
          <title>Asset History - ${assetName}</title>
          <script src="https://cdn.tailwindcss.com"></script>
          <style>
            @page { margin: 0.5in; size: landscape; }
            @media print {
              .no-print { display: none !important; }
              .page-break { page-break-before: always; }
            }
            body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; }
            .section-card {
              background: white;
              border-radius: 12px;
              box-shadow: 0 1px 3px rgba(0,0,0,0.1);
              margin-bottom: 24px;
              overflow: hidden;
            }
            .section-header {
              padding: 16px 20px;
              font-weight: 600;
              font-size: 16px;
              display: flex;
              align-items: center;
              gap: 10px;
            }
            .section-content {
              padding: 16px 20px;
            }
            table {
              width: 100%;
              border-collapse: collapse;
            }
            th {
              text-align: left;
              padding: 12px 16px;
              font-size: 12px;
              font-weight: 600;
              text-transform: uppercase;
              letter-spacing: 0.5px;
            }
            td {
              border-top: 1px solid #e5e7eb;
            }
          </style>
        </head>
        <body class="bg-gray-100 min-h-screen">
          <!-- Header -->
          <div class="bg-gradient-to-r from-blue-600 to-blue-800 text-white py-6 px-8 no-print">
            <div class="max-w-7xl mx-auto flex justify-between items-center">
              <div>
                <h1 class="text-2xl font-bold">Asset History</h1>
                <p class="text-blue-200 mt-1">Complete history and maintenance records</p>
              </div>
              <div class="flex gap-3">
                <button onclick="window.print()" class="bg-white text-blue-600 px-4 py-2 rounded-lg font-medium hover:bg-blue-50 transition">
                  🖨️ Print / Save PDF
                </button>
                <button onclick="window.close()" class="bg-blue-700 text-white px-4 py-2 rounded-lg font-medium hover:bg-blue-600 transition">
                  ✕ Close
                </button>
              </div>
            </div>
          </div>

          <div class="max-w-7xl mx-auto py-6 px-8">
            <!-- Asset Details Card -->
            <div class="section-card">
              <div class="section-header bg-gradient-to-r from-blue-500 to-blue-600 text-white">
                <span>🔍</span> Asset Details
              </div>
              <div class="section-content">
                <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4">
                  <div class="bg-gray-50 rounded-lg p-4">
                    <p class="text-xs text-gray-500 uppercase tracking-wide">Asset ID</p>
                    <p class="font-semibold text-blue-600 mt-1">${assetName}</p>
                  </div>
                  <div class="bg-gray-50 rounded-lg p-4">
                    <p class="text-xs text-gray-500 uppercase tracking-wide">Asset Name</p>
                    <p class="font-semibold mt-1">${assetData.asset_name || '-'}</p>
                  </div>
                  <div class="bg-gray-50 rounded-lg p-4">
                    <p class="text-xs text-gray-500 uppercase tracking-wide">🏥 Hospital</p>
                    <p class="font-semibold mt-1">${assetData.company || '-'}</p>
                  </div>
                  <div class="bg-gray-50 rounded-lg p-4">
                    <p class="text-xs text-gray-500 uppercase tracking-wide">📍 Location</p>
                    <p class="font-semibold mt-1">${assetData.location || '-'}</p>
                  </div>
                  <div class="bg-gray-50 rounded-lg p-4">
                    <p class="text-xs text-gray-500 uppercase tracking-wide">🚛 Supplier</p>
                    <p class="font-semibold mt-1">${assetData.supplier || '-'}</p>
                  </div>
                  <div class="bg-amber-50 rounded-lg p-4 border border-amber-200">
                    <p class="text-xs text-amber-600 uppercase tracking-wide">💰 Total Repair Cost</p>
                    <p class="font-bold text-amber-700 mt-1 text-lg">${assetData.custom_total_spare_parts_amount || 0} ر.س</p>
                  </div>
                </div>
              </div>
            </div>

            <!-- Two Column Layout -->
            <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
              <!-- Work Orders -->
              <div class="section-card">
                <div class="section-header bg-gradient-to-r from-indigo-500 to-indigo-600 text-white">
                  <span>🔗</span> Linked Work Orders
                </div>
                <div class="overflow-x-auto">
                  <table>
                    <thead class="bg-gray-50">
                      <tr>
                        <th class="text-gray-600">Work Order No</th>
                        <th class="text-gray-600">Type</th>
                        <th class="text-gray-600">Status</th>
                        <th class="text-gray-600">Repair Cost</th>
                        <th class="text-gray-600">Created</th>
                      </tr>
                    </thead>
                    <tbody>
                      ${workOrdersHTML}
                    </tbody>
                  </table>
                </div>
              </div>

              <!-- Spare Parts -->
              <div class="section-card">
                <div class="section-header bg-gradient-to-r from-orange-500 to-orange-600 text-white">
                  <span>🛠️</span> Items Used for Repair
                </div>
                <div class="section-content max-h-96 overflow-y-auto">
                  ${sparePartsHTML}
                </div>
              </div>
            </div>

            <!-- Maintenance Section -->
            <div class="grid grid-cols-1 lg:grid-cols-3 gap-6 mt-6">
              <!-- Maintenance Records -->
              <div class="section-card">
                <div class="section-header bg-gradient-to-r from-teal-500 to-teal-600 text-white">
                  <span>🛠️</span> Maintenance Records
                </div>
                <div class="section-content max-h-80 overflow-y-auto">
                  ${maintenanceRecordsHTML}
                </div>
              </div>

              <!-- Maintenance Tasks -->
              <div class="section-card lg:col-span-2">
                <div class="section-header bg-gradient-to-r from-purple-500 to-purple-600 text-white">
                  <span>📋</span> Maintenance Tasks
                </div>
                <div class="overflow-x-auto">
                  <table>
                    <thead class="bg-gray-50">
                      <tr>
                        <th class="text-gray-600">Assigned To</th>
                        <th class="text-gray-600">Periodicity</th>
                        <th class="text-gray-600">Next Due Date</th>
                        <th class="text-gray-600">Maintenance ID</th>
                      </tr>
                    </thead>
                    <tbody>
                      ${maintenanceTasksHTML}
                    </tbody>
                  </table>
                </div>
              </div>
            </div>

            <!-- Periodic Maintenance Summary -->
            <div class="section-card mt-6">
              <div class="section-header bg-gradient-to-r from-cyan-500 to-cyan-600 text-white">
                <span>📜</span> Periodic Maintenance Summary
              </div>
              <div class="section-content">
                <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
                  ${statusSummaryHTML}
                </div>
              </div>
            </div>

            <!-- Completed Maintenance Logs -->
            <div class="section-card mt-6">
              <div class="section-header bg-gradient-to-r from-green-500 to-green-600 text-white">
                <span>✅</span> Completed Maintenance Logs
              </div>
              <div class="overflow-x-auto">
                <table>
                  <thead class="bg-gray-50">
                    <tr>
                      <th class="text-gray-600">Log ID</th>
                      <th class="text-gray-600">Assigned To</th>
                      <th class="text-gray-600">Type</th>
                      <th class="text-gray-600">Due Date</th>
                      <th class="text-gray-600">Completed</th>
                      <th class="text-gray-600">Periodicity</th>
                      <th class="text-gray-600">Actions</th>
                    </tr>
                  </thead>
                  <tbody>
                    ${completedLogsHTML}
                  </tbody>
                </table>
              </div>
            </div>

            <!-- Pending/Planned Maintenance Logs -->
            <div class="section-card mt-6">
              <div class="section-header bg-gradient-to-r from-amber-500 to-amber-600 text-white">
                <span>⏳</span> Pending/Planned Maintenance Logs
              </div>
              <div class="overflow-x-auto">
                <table>
                  <thead class="bg-gray-50">
                    <tr>
                      <th class="text-gray-600">Log ID</th>
                      <th class="text-gray-600">Assigned To</th>
                      <th class="text-gray-600">Type</th>
                      <th class="text-gray-600">Due Date</th>
                      <th class="text-gray-600">Periodicity</th>
                      <th class="text-gray-600">Status</th>
                      <th class="text-gray-600">Actions</th>
                    </tr>
                  </thead>
                  <tbody>
                    ${pendingLogsHTML}
                  </tbody>
                </table>
              </div>
            </div>

            <!-- Footer -->
            <div class="text-center text-gray-500 text-sm mt-8 pb-8">
              Generated on ${new Date().toLocaleString()} | Asset: ${assetName}
            </div>
          </div>
        </body>
      </html>
    `);

  } catch (err) {
    console.error('Error fetching Asset History:', err);
    alert('Failed to load Asset History. Please try again.');
  }
  };

  const handleInstallationReport = () => {
    if (!assetName || isNewAsset) {
      alert('Please save the asset first to view Installation Report');
      return;
    }

    const reportHandle = openHtmlReport();
    if (!reportHandle) {
      showReportBlockedMessage();
      return;
    }

    // Get current date formatted
    const today = new Date();
    const formatDate = (date: Date) => {
      const day = String(date.getDate()).padStart(2, '0');
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const year = date.getFullYear();
      return `${day}/${month}/${year}`;
    };

    // Get spare parts from asset data
    const spareParts = (asset as any)?.custom_spare_parts || [];
    
    // Generate table rows for spare parts
    let sparePartsRows = '';
    const minRows = 3;
    
    if (spareParts.length > 0) {
      spareParts.forEach((item: any, index: number) => {
        sparePartsRows += `
          <tr>
            <td>${index + 1}</td>
            <td>${item.item_name || ''}</td>
            <td>${item.item_code || ''}</td>
            <td>${item.uom || ''}</td>
            <td>${item.qty || ''}</td>
          </tr>
        `;
      });
      // Add empty rows to fill up to minimum
      for (let i = spareParts.length; i < minRows; i++) {
        sparePartsRows += `
          <tr>
            <td>${i + 1}</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
          </tr>
        `;
      }
    } else {
      // All empty rows
      for (let i = 0; i < minRows; i++) {
        sparePartsRows += `
          <tr>
            <td>${i + 1}</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
          </tr>
        `;
      }
    }

    reportHandle.write(`
      <!DOCTYPE html>
      <html lang="ar" dir="rtl">
      <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Installation Report - ${assetName}</title>
        <style>
          @page {
            margin: 0.5in;
            size: A4;
          }
          body {
            font-family: 'Times New Roman', serif;
            margin: 0;
            padding: 20px;
            font-size: 12px;
            line-height: 1.3;
            direction: rtl;
            text-align: right;
          }
          
          .header-line {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 5px;
          }
          
          .header-right {
            font-weight: bold;
          }
          
          .header-center {
            font-weight: bold;
            text-align: center;
            flex-grow: 1;
          }
          
          .header-left {
            font-weight: bold;
          }
          
          .dotted-line {
            border-bottom: 1px dotted #000;
            display: inline-block;
            min-width: 100px;
          }
          
          .main-content {
            margin: 15px 0;
            text-align: justify;
          }
          
          .equipment-section {
            margin: 15px 0;
          }
          
          .equipment-line {
            display: flex;
            justify-content: space-between;
            margin: 8px 0;
            font-weight: bold;
          }
          
          .equipment-item {
            display: flex;
            align-items: center;
            direction: ltr;
            text-align: left;
            width: 48%;
          }
          
          .arabic-label {
            direction: rtl;
            text-align: right;
            margin-left: 10px;
          }
          
          .colon {
            margin: 0 5px;
          }
          
          .field-value {
            border-bottom: 1px solid #000;
            min-width: 120px;
            display: inline-block;
            height: 18px;
          }
          
          .location-line {
            margin: 10px 0;
            font-weight: bold;
            display: flex;
            justify-content: space-between;
            align-items: center;
            width: 100%;
          }
          
          .location-arabic {
            direction: rtl;
            text-align: right;
          }
          
          .location-english {
            direction: ltr;
            text-align: left;
          }
          
          .parts-table {
            width: 100%;
            border-collapse: collapse;
            margin: 15px 0;
            border: 2px solid #000;
          }
          
          .parts-table th,
          .parts-table td {
            border: 1px solid #000;
            padding: 6px;
            text-align: center;
            font-weight: bold;
            vertical-align: middle;
          }
          
          .parts-table th {
            background-color: #f8f8f8;
            font-size: 11px;
          }
          
          .parts-table .row-number {
            width: 8%;
          }
          
          .parts-table .description {
            width: 35%;
          }
          
          .parts-table .part-number {
            width: 25%;
          }
          
          .parts-table .unit {
            width: 16%;
          }
          
          .parts-table .quantity {
            width: 16%;
          }
          
          .footer-text {
            margin: 20px 0;
            text-align: justify;
          }
          
          .signatures-section {
            margin-top: 40px;
          }
          
          .signature-row {
            display: flex;
            justify-content: space-between;
            margin: 30px 0;
          }
          
          .signature-block-right {
            text-align: left;
            width: 45%;
            float: right;
          }
          
          .signature-block-left {
            text-align: left;
            width: 45%;
            float: left;
          }
          
          .signature-title {
            font-weight: bold;
            margin-bottom: 3px;
            font-size: 11px;
          }
          
          .signature-line {
            border-bottom: 1px solid #000;
            height: 25px;
            margin: 8px 0;
            display: inline-block;
            width: 120px;
            margin-left: 10px;
          }
          
          .signature-label {
            font-size: 10px;
            font-weight: bold;
          }
          
          .seal-section {
            text-align: center;
            margin-top: 30px;
            font-weight: bold;
            font-size: 12px;
          }
        </style>
      </head>
      <body>
        <!-- Header Section -->
        <div class="header-line">
          <div class="header-right">المملكة العربية السعودية</div>
          <div class="header-center"></div>
          <div class="header-left">الرقم: <span class="dotted-line">${assetName || ''}</span></div>
        </div>
        
        <div class="header-line">
          <div class="header-right">تجمع الجوف الصحي</div>
          <div class="header-center">محضر تركيب</div>
          <div class="header-left">التاريخ: <span class="dotted-line">${formatDate(today)}</span> هـ</div>
        </div>
        
        <div class="header-line">
          <div class="header-right">الصيانة الطبية</div>
          <div class="header-center">INSTALLATION REPORT</div>
          <div class="header-left">الموافق: <span class="dotted-line">${formatDate(today)}</span> م</div>
        </div>
        
        <div style="margin: 15px 0; font-weight: bold;">
          مستشفى <span class="dotted-line" style="min-width: 200px;">${formData.company || ''}</span>
        </div>

        <!-- Main Content -->
        <div class="main-content">
          تشهد مستشفى <span class="dotted-line" style="min-width: 180px;">${formData.company || ''}</span> بأن <span class="dotted-line" style="min-width: 180px;">${formData.supplier || ''}</span> قامت بتركيب و توريد قطع الغيار الخاصة التالية والتابعة:
        </div>

        <!-- Equipment Information -->
        <div class="equipment-section">
          <div class="equipment-line">
            <div class="equipment-item">
              <span>EQUIPMENT NAME</span>
              <span class="colon">:</span>
              <span class="field-value">${formData.asset_name || ''}</span>
              <span class="arabic-label">اسم الجهاز:</span>
            </div>
            <div class="equipment-item">
              <span>MFR</span>
              <span class="colon">:</span>
              <span class="field-value">${formData.custom_manufacturer || ''}</span>
              <span class="arabic-label">صناعة:</span>
            </div>
          </div>
          
          <div class="equipment-line">
            <div class="equipment-item">
              <span>SERIAL NO</span>
              <span class="colon">:</span>
              <span class="field-value">${formData.custom_serial_number || ''}</span>
              <span class="arabic-label">مسلسل:</span>
            </div>
            <div class="equipment-item">
              <span>MODEL</span>
              <span class="colon">:</span>
              <span class="field-value">${formData.custom_model || ''}</span>
              <span class="arabic-label">موديل:</span>
            </div>
          </div>
        </div>
        
        <div class="location-line">
          <span class="location-arabic">
            التابع لقسم:
          </span>
          <span class="field-value" style="min-width: 300px; flex-grow: 1; margin: 0 10px; text-align: left;">${formData.location || ''}</span>
          <span class="location-english">
            LOCATION:
          </span>
        </div>

        <!-- Parts Table -->
        <table class="parts-table">
          <thead>
            <tr>
              <th class="row-number">م</th>
              <th class="description">وصف القطعة<br>DESCRIPTION</th>
              <th class="part-number">رقم القطعة<br>PART NO.</th>
              <th class="unit">الوحدة<br>UNIT</th>
              <th class="quantity">الكمية<br>QTY.</th>
            </tr>
          </thead>
          <tbody>
            ${sparePartsRows}
          </tbody>
        </table>

        <!-- Footer Text -->
        <div class="footer-text">
          وذلك طبقا لعقد صيانة وإصلاح الأجهزة الطبية بمستشفى <span class="dotted-line" style="min-width: 150px;">${formData.company || ''}</span> والجهاز يعمل بحالة جيدة.
          <br><br>
          وﷲ الموفق .....
        </div>

        <!-- Signatures Section -->
        <div class="signatures-section">
          <!-- First Row -->
          <div class="signature-row">
            <div class="signature-block-right">
              <div class="signature-title">المسئول في القسم &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Dept. Responsible</div>
              <div><span class="signature-line"></span><span class="signature-label">Name</span></div>
              <div><span class="signature-line"></span><span class="signature-label">Sign</span></div>
            </div>
            
            <div class="signature-block-left">
              <div class="signature-title">مدير شركة سمامة &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Site Manager</div>
              <div><span class="signature-line"></span><span class="signature-label">Name</span></div>
              <div><span class="signature-line"></span><span class="signature-label">Sign</span></div>
            </div>
          </div>
          
          <!-- Installation Engineer - Right aligned -->
          <div style="text-align: left; margin: 25px 0; width: 45%; float: right; clear: both;">
            <div class="signature-title">مهندس/ فني التركيب &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Installation Eng</div>
            <div><span class="signature-line"></span><span class="signature-label">Name</span></div>
            <div><span class="signature-line"></span><span class="signature-label">Sign</span></div>
          </div>
          <div style="clear: both;"></div>
          
          <!-- Second Row -->
          <div class="signature-row">
            <div class="signature-block-right">
              <div class="signature-title">مشرف الوزارة بالمستشفى &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Hospital Supervisor</div>
              <div><span class="signature-line"></span><span class="signature-label">Name</span></div>
              <div><span class="signature-line"></span><span class="signature-label">Sign</span></div>
            </div>
            
            <div class="signature-block-left">
              <div class="signature-title">مدير المستشفى/ المركز &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Hospital Manager</div>
              <div><span class="signature-line"></span><span class="signature-label">Name</span></div>
              <div><span class="signature-line"></span><span class="signature-label">Sign</span></div>
            </div>
          </div>
        </div>

        <!-- Official Seal -->
        <div class="seal-section">
          الختم الرسمي
        </div>

        <script>
          window.onload = function() {
            window.print();
          };
        </script>
      </body>
      </html>
    `);
  };

  const handleDismantlingReport = () => {
    if (!assetName || isNewAsset) {
      alert('Please save the asset first to view Dismantling Report');
      return;
    }

    const reportHandle = openHtmlReport();
    if (!reportHandle) {
      showReportBlockedMessage();
      return;
    }

    // Get current date formatted
    const today = new Date();
    const formatDate = (date: Date) => {
      const day = String(date.getDate()).padStart(2, '0');
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const year = date.getFullYear();
      return `${day}/${month}/${year}`;
    };

    // Calculate usage period if available
    const creationDate = asset?.creation ? new Date(asset.creation) : null;
    let usagePeriod = '';
    if (creationDate) {
      const years = Math.floor((today.getTime() - creationDate.getTime()) / (1000 * 60 * 60 * 24 * 365));
      const months = Math.floor(((today.getTime() - creationDate.getTime()) % (1000 * 60 * 60 * 24 * 365)) / (1000 * 60 * 60 * 24 * 30));
      usagePeriod = `${years} سنة و ${months} شهر`;
    }

    reportHandle.write(`
      <!DOCTYPE html>
      <html lang="ar" dir="rtl">
      <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Dismantling Report - ${assetName}</title>
        <style>
          @page {
            margin: 0.5in;
            size: A4;
          }
          body {
            font-family: 'Times New Roman', serif;
            margin: 0;
            padding: 20px;
            font-size: 12px;
            line-height: 1.4;
            direction: rtl;
            text-align: right;
          }
          
          .header {
            text-align: left;
            margin-bottom: 30px;
          }
          
          .title {
            text-align: center;
            font-size: 14px;
            font-weight: bold;
            margin: 20px 0;
          }
          
          .department-line {
            margin: 15px 0;
            font-weight: bold;
          }
          
          .section-title {
            font-weight: bold;
            margin: 20px 0 10px 0;
          }
          
          .reasons-section {
            margin: 20px 0;
          }
          
          .reasons-table {
            width: 60%;
            border-collapse: collapse;
            margin: 10px 0;
          }
          
          .reasons-table td {
            border: 2px solid #000;
            padding: 8px;
            text-align: center;
            font-weight: bold;
            width: 16.66%;
            height: 30px;
          }
          
          .reason-text {
            margin: 8px 0;
            text-align: right;
            font-size: 11px;
            direction: rtl;
            word-wrap: break-word;
            overflow-wrap: break-word;
          }
          
          .committee-opinion {
            margin: 20px 0;
            padding: 10px;
            border: 1px solid #ccc;
            text-align: justify;
          }
          
          .signatures-table {
            width: 100%;
            border-collapse: collapse;
            margin: 20px 0;
          }
          
          .signatures-table td {
            padding: 8px;
            text-align: right;
            vertical-align: top;
            font-weight: bold;
            direction: rtl;
            word-wrap: break-word;
            overflow-wrap: break-word;
          }
          
          .signature-title {
            font-size: 11px;
            height: 30px;
            font-weight: bold;
          }
          
          .signature-field {
            height: 25px;
            font-size: 10px;
          }
          
          .hospital-manager {
            text-align: right;
            margin: 20px 0;
          }
          
          .hospital-manager-table {
            width: 100%;
            margin: 0;
            border-collapse: collapse;
            float: right;
          }
          
          .hospital-manager-table td {
            padding: 8px;
            text-align: right;
            font-weight: bold;
            direction: rtl;
            word-wrap: break-word;
            overflow-wrap: break-word;
          }
          
          .seal-section {
            text-align: center;
            margin: 30px 0;
            font-weight: bold;
          }
          
          .footer {
            margin-top: 40px;
            text-align: right;
          }
          
          .footer-title {
            font-weight: bold;
            margin-bottom: 5px;
            color: #0066cc;
          }
          
          .footer-name {
            font-size: 11px;
            color: #0066cc;
          }
          
          .logo {
            width: 100px;
            height: 60px;
            margin: 0;
            display: inline-flex;
            align-items: center;
            justify-content: center;
          }

          .logo img {
            max-width: 100%;
            max-height: 100%;
            object-fit: contain;
          }
          
          .equipment-table {
            width: 100%;
            border: 1px solid black;
            border-collapse: collapse;
          }
          
          .equipment-table td {
            width: 25%;
            border: 1px solid black;
            padding: 8px;
          }
        </style>
      </head>
      <body>
        <!-- Header Section -->
        <div class="header">
          <div class="logo"><img src='/files/SEMH!.png' onerror="this.style.display='none'"></div>
        </div>

        <!-- Title -->
        <div class="title">
          محضر تكهين / إبعاد عن الخدمة
        </div>

        <!-- Department -->
        <div class="department-line">
          القسم : <span style="border-bottom: 1px solid #000; min-width: 200px; display: inline-block;">${formData.department || ''}</span>
        </div>

        <!-- Equipment Data Section -->
        <div class="section-title">0-1 بيانات الجهاز المطلوب تكهينه :</div>
        
        <table class="equipment-table">
          <tr>
            <td>اسم الجهاز</td>
            <td>${formData.asset_name || ''}</td>
            <td>الرقم التسلسلي</td>
            <td>${formData.custom_serial_number || ''}</td>
          </tr>
          <tr>
            <td>الشركة الصانعة</td>
            <td>${formData.custom_manufacturer || ''}</td>
            <td>تاريخ التوريد</td>
            <td>${creationDate ? formatDate(creationDate) : ''}</td>
          </tr>
          <tr>
            <td>الطراز/الموديل</td>
            <td>${formData.custom_model || ''}</td>
            <td>مدة استخدام الجهاز</td>
            <td>${usagePeriod}</td>
          </tr>
        </table>

        <!-- Reasons Section -->
        <div class="section-title">2- أسباب طلب التكهين / إبعاد عن الخدمة :</div>
        
        <table class="reasons-table">
          <tr>
            <td>أ</td>
            <td>ب</td>
            <td>ج</td>
            <td>د</td>
            <td>هـ</td>
            <td>و</td>
          </tr>
          <tr>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
          </tr>
        </table>

        <div class="reason-text">
          أ) تكاليف قطع الغيار المطلوبة للإصلاح أكثر من نصف قيمة الجهاز (مرفق عرض أسعار قطع الغيار اللازمة للإصلاح).
        </div>
        <div class="reason-text">
          ب) توقف انتاج الجهاز وقطع الغيار من الشركة الصانعة حسب تقرير المورد.
        </div>
        <div class="reason-text">
          ج) جهاز قديم وتم استخدامه أكثر من عشر سنوات.
        </div>
        <div class="reason-text">
          د) ليس للجهاز وكيل معروف بالمملكة في الوقت الحالي ولا يمكن توفير قطع غيار للجهاز.
        </div>
        <div class="reason-text">
          ه) تكرار أعطال الجهاز وإصلاحه على فترات متقاربة.
        </div>
        <div class="reason-text">
          و) أخرى : <span style="border-bottom: 1px solid #000; min-width: 300px; display: inline-block;"></span>
        </div>

        <!-- Committee Opinion -->
        <div class="section-title">3- مرئيات اللجنة:</div>
        <div class="reason-text">
          بناءاً على الفقرة أ. ج. و. يتم تكهين الجهاز وادراجه ضمن بنود الإحلال المطلوبة للمستشفى.
        </div>

        <!-- Signatures Section -->
        <div class="section-title">توقيع اللجنة :</div>
        
        <table class="signatures-table">
          <tr>
            <td class="signature-title">المقاول</td>
            <td class="signature-title">رئيس القسم</td>
            <td class="signature-title">مدير الصيانة الطبية</td>
            <td class="signature-title">مدير مراقبة المخزون</td>
          </tr>
          <tr>
            <td class="signature-field">الإسم :</td>
            <td class="signature-field">الإسم :</td>
            <td class="signature-field">الإسم :</td>
            <td class="signature-field">الإسم :</td>
          </tr>
          <tr>
            <td class="signature-field">التوقيع :</td>
            <td class="signature-field">التوقيع :</td>
            <td class="signature-field">التوقيع :</td>
            <td class="signature-field">التوقيع :</td>
          </tr>
          <tr>
            <td class="signature-field">التاريخ :</td>
            <td class="signature-field">التاريخ :</td>
            <td class="signature-field">التاريخ :</td>
            <td class="signature-field">التاريخ :</td>
          </tr>
        </table>

        <!-- Hospital Manager Section -->
        <div class="hospital-manager">
          <table class="hospital-manager-table">
            <tr>
              <td class="signature-title">مدير مستشفى</td>
            </tr>
            <tr>
              <td class="signature-field">الإسم :</td>
            </tr>
            <tr>
              <td class="signature-field">التوقيع :</td>
            </tr>
            <tr>
              <td class="signature-field">التاريخ :</td>
            </tr>
            <tr>
              <td class="signature-field">الختم :</td>
            </tr>
          </table>
        </div>

        <!-- Arabic text after last table -->
        <div style="clear: both; text-align: left; margin: 20px 0;">
          <div style="font-weight: bold; margin-bottom: 5px;">الصيانة الطبية بتجمع الجوف الصحي</div>
          <div>المهندس/عبد العزيز زايد الخمعلي</div>
        </div>

        <!-- Footer -->
        <div class="footer">
          <div style="color: #0066cc; font-weight: bold;">تجمع الجوف الصحي</div>
          <div style="color: #0066cc;">Aljouf Health Cluster</div>
        </div>

        <script>
          window.onload = function() {
            window.print();
          };
        </script>
      </body>
      </html>
    `);
  };

  const renderActionMenuItems = () => (
    <>
      {qrCodeUrl && (
        <button
          type="button"
          onClick={() => runAssetAction(handlePrintQR)}
          className="w-full text-left px-4 py-3 min-h-[48px] text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 flex items-center gap-2"
        >
          <FaQrcode size={14} />
          Print QR
        </button>
      )}

      <button
        type="button"
        onClick={() => runAssetAction(handlePrintStayPlugged)}
        className="w-full text-left px-4 py-3 min-h-[48px] text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 flex items-center gap-2"
      >
        <FaQrcode size={14} />
        Stay Plugged
      </button>

      <button
        type="button"
        onClick={() => runAssetAction(handlePPMPlan)}
        className="w-full text-left px-4 py-3 min-h-[48px] text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 flex items-center gap-2"
      >
        <FaCalendarAlt size={14} />
        PPM Plan
      </button>

      <button
        type="button"
        onClick={() => runAssetAction(handleAssetHistory)}
        className="w-full text-left px-4 py-3 min-h-[48px] text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 flex items-center gap-2"
      >
        <FaHistory size={14} />
        Asset History
      </button>

      <button
        type="button"
        onClick={() => runAssetAction(handleInstallationReport)}
        className="w-full text-left px-4 py-3 min-h-[48px] text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 flex items-center gap-2"
      >
        <FaFileAlt size={14} />
        Installation Report
      </button>

      {asset?.status === 'Scrapped' && (
        <button
          type="button"
          onClick={() => runAssetAction(handleDismantlingReport)}
          className="w-full text-left px-4 py-3 min-h-[48px] text-sm hover:bg-red-50 dark:hover:bg-red-900/20 flex items-center gap-2 text-red-600 dark:text-red-400 border-t border-gray-200 dark:border-gray-700"
        >
          <FaTrashAlt size={14} />
          Dismantling Report
        </button>
      )}
    </>
  );

  return (
    <div className="min-h-screen bg-gray-50 dark:bg-gray-900 p-4 sm:p-6 min-w-0 overflow-x-hidden">
      {/* Header */}
      <div className="mb-6 flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between lg:items-center flex-wrap">
        <div className="flex items-center gap-4">
          <button
            onClick={() => navigate('/assets')}
            className="text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300 flex items-center gap-2"
          >
            <FaArrowLeft />
            <span className="text-gray-900 dark:text-white font-medium">
              {isDuplicating ? 'Duplicate Asset' : (isNewAsset ? 'New Asset Details' : 'Asset Details')}
            </span>
          </button>
          
          {/* Document Status Badge */}
          {asset && (
            <span className={`px-3 py-1 rounded-full text-xs font-medium ${
              docstatus === 0 ? 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-300' :
              docstatus === 1 ? 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-300' :
              'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-300'
            }`}>
              {docstatus === 0 ? 'Draft' : docstatus === 1 ? 'Submitted' : 'Cancelled'}
            </span>
          )}
        </div>
        <div className="flex flex-wrap items-center gap-2 sm:gap-3">
          {!isNewAsset && !isEditing && !isCancelled && (
          <>
            <div className="relative" ref={actionDropdownRef}>
              <button
                type="button"
                onClick={() => setIsActionDropdownOpen(!isActionDropdownOpen)}
                className="bg-blue-600 hover:bg-blue-700 text-white px-3 py-2 min-h-[44px] rounded-lg flex items-center gap-2"
              >
                Actions
                <FaChevronDown size={12} className={`transition-transform ${isActionDropdownOpen ? 'rotate-180' : ''}`} />
              </button>

              {isActionDropdownOpen && (
                <div className="absolute right-0 mt-2 w-56 bg-white dark:bg-gray-800 rounded-md shadow-lg z-50 border border-gray-200 dark:border-gray-700 hidden lg:block">
                  <div className="py-1">{renderActionMenuItems()}</div>
                </div>
              )}
            </div>

            {isActionDropdownOpen &&
              createPortal(
                <>
                  <button
                    type="button"
                    className="fixed inset-0 z-[10000] bg-black/50 lg:hidden"
                    onClick={() => setIsActionDropdownOpen(false)}
                    aria-label="Close actions"
                  />
                  <div className="fixed inset-x-0 bottom-0 z-[10001] max-h-[85vh] overflow-y-auto rounded-t-2xl bg-white dark:bg-gray-800 border-t border-gray-200 dark:border-gray-700 lg:hidden">
                    <div className="px-4 py-3 border-b border-gray-200 dark:border-gray-700">
                      <h3 className="text-sm font-semibold text-gray-900 dark:text-white">Actions</h3>
                    </div>
                    <div className="py-1">{renderActionMenuItems()}</div>
                  </div>
                </>,
                document.body
              )}

            <button
              onClick={() => setIsEditing(true)}
              className="bg-blue-600 hover:bg-blue-700 text-white px-3 py-2 min-h-[44px] rounded-lg flex items-center gap-2"
            >
              <FaEdit />
              Edit
            </button>
            {isDraft && (
              <button
                onClick={handleSubmitDocument}
                disabled={saving}
                className="bg-purple-600 hover:bg-purple-700 text-white px-3 py-2 min-h-[44px] rounded-lg flex items-center gap-2 disabled:opacity-50"
              >
                <FaCheck />
                {saving ? 'Submitting...' : 'Submit'}
              </button>
            )}
          </>
        )}
          {isCancelled && (
            <span className="text-sm text-gray-500 dark:text-gray-400 italic">
              Cancelled documents cannot be edited
            </span>
          )}
          {isEditing && (
            <>
              <button
                onClick={() => {
                  if (isNewAsset) {
                    navigate('/assets');
                  } else {
                    setIsEditing(false);
                  }
                }}
                className="bg-gray-300 hover:bg-gray-400 text-gray-700 dark:text-gray-800 px-2 py-1 rounded-lg"
                disabled={saving}
              >
                Cancel
              </button>
              <button
                onClick={handleSubmit}
                disabled={saving}
                className="bg-green-600 hover:bg-green-700 text-white px-2 py-1 rounded-lg flex items-center gap-2 disabled:opacity-50"
              >
                <FaSave />
                {saving ? 'Saving...' : 'Save Changes'}
              </button>
            </>
          )}
        </div>
      </div>

      <form onSubmit={handleSubmit}>
        {/* 4-Column Grid Layout */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
          
          {/* COLUMN 1: Asset Information */}
          <div className="bg-white dark:bg-gray-800 rounded-lg shadow-md p-6">
            <h2 className="text-base font-semibold text-gray-800 dark:text-white mb-4 pb-2 border-b border-gray-200 dark:border-gray-700">
              Asset Information
            </h2>
            <div className="space-y-4">
              <div>
                <label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Asset Name <span className="text-red-500">*</span>
                </label>
                <input
                  type="text"
                  name="asset_name"
                  value={formData.asset_name}
                  onChange={handleChange}
                  placeholder="e.g. Laptop Model X"
                  required
                  disabled={isFieldDisabled('asset_name')}
                  className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100 dark:disabled:bg-gray-700 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                />
              </div>

              <LinkField
                label="Asset Type"
                doctype="Asset Type"
                value={formData.custom_asset_type || ''}
                onChange={(val) => setFormData({ ...formData, custom_asset_type: val })}
                disabled={isFieldDisabled('custom_asset_type')}
              />

              <LinkField
                label="Asset Category"
                doctype="Asset Category"
                value={formData.asset_category || ''}
                onChange={(val) => setFormData({ ...formData, asset_category: val })}
                disabled={isFieldDisabled('asset_category')}
              />

              <LinkField
                label="Modality"
                doctype="Modality"
                value={formData.custom_modality || ''}
                onChange={(val) => setFormData({ ...formData, custom_modality: val })}
                disabled={isFieldDisabled('custom_modality')}
              />

              <div>
                <label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Class
                </label>
                <select
                  name="custom_class"
                  value={formData.custom_class}
                  onChange={handleChange}
                  disabled={isFieldDisabled('custom_class')}
                  className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100 dark:disabled:bg-gray-700 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                >
                  <option value="">Select class</option>
                  <option value="Class A">Class A</option>
                  <option value="Class B">Class B</option>
                  <option value="Class C">Class C</option>
                </select>
              </div>

              <div>
                <label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Asset ID
                </label>
                <input
                  type="text"
                  value={isNewAsset || isDuplicating ? 'Auto-generated' : asset?.name}
                  disabled
                  className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-md bg-gray-100 dark:bg-gray-700 text-gray-500 dark:text-gray-400"
                />
                {isDuplicating && (
                  <p className="mt-1 text-xs text-blue-600 dark:text-blue-400">
                    💡 Duplicating from: {duplicateFromAsset}
                  </p>
                )}
              </div>
              <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    Device Status <span className="text-red-500">*</span>
                  </label>
                  <select
                    name="custom_device_status"
                    value={formData.custom_device_status}
                    onChange={handleChange}
                    disabled={!isEditing}
                    className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100 dark:disabled:bg-gray-700 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                  >
                    {/* <option value="">Select class</option> */}
                    <option value="Up">Up</option>
                    <option value="Down">Down</option>
                  </select>
                </div>
            </div>
          </div>

          {/* COLUMN 2: Technical Specs */}
          <div className="bg-white dark:bg-gray-800 rounded-lg shadow-md p-6">
            <h2 className="text-base font-semibold text-gray-800 dark:text-white mb-4 pb-2 border-b border-gray-200 dark:border-gray-700">
              Technical Specs
            </h2>
            <div className="space-y-4">
              <div>
                <label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Serial Code
                </label>
                <input
                  type="text"
                  name="custom_serial_number"
                  value={formData.custom_serial_number}
                  onChange={handleChange}
                  placeholder="e.g. SN-12345"
                  disabled={isFieldDisabled('custom_serial_number')}
                  className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100 dark:disabled:bg-gray-700 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                />
              </div>

              <div>
                <label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Local ID
                </label>
                <input
                  type="text"
                  name="custom_local_id"
                  value={formData.custom_local_id || ''}
                  onChange={handleChange}
                  placeholder="Local ID"
                  disabled={isFieldDisabled('custom_local_id')}
                  className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100 dark:disabled:bg-gray-700 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                />
              </div>

              {/* <div>
                <label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                  System ID
                </label>
                <input
                  type="text"
                  placeholder="e.g. SYS-755"
                  disabled={!isEditing}
                  className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100 dark:disabled:bg-gray-700 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                />
              </div>

              <div>
                <label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Serial No.2
                </label>
                <input
                  type="text"
                  placeholder="e.g. SR-V021-A"
                  disabled={!isEditing}
                  className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100 dark:disabled:bg-gray-700 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                />
              </div> */}

              <LinkField
                label="Manufacturer"
                doctype="Manufacturer"
                value={formData.custom_manufacturer || ''}
                onChange={(val) => setFormData({ ...formData, custom_manufacturer: val })}
                disabled={isFieldDisabled('custom_manufacturer')}
              />

              <div>
                <label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Model
                </label>
                <input
                  type="text"
                  name="custom_model"
                  value={formData.custom_model}
                  onChange={handleChange}
                  placeholder="Model number"
                  disabled={isFieldDisabled('custom_model')}
                  className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100 dark:disabled:bg-gray-700 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                />
              </div>

              <div>
                <label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Total Hours
                </label>
                <input
                  type="number"
                  name="custom_total_hours"
                  value={formData.custom_total_hours || 0}
                  disabled
                  className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-md bg-gray-100 dark:bg-gray-700 text-gray-500 dark:text-gray-400"
                />
                <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
                  Calculated from Available For Use Date
                </p>
              </div>

              <div>
                <label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Down Time (Hours)
                </label>
                <input
                  type="number"
                  name="custom_down_time"
                  value={formData.custom_down_time || 0}
                  onChange={handleChange}
                  placeholder="0"
                  disabled={isFieldDisabled('custom_down_time')}
                  className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100 dark:disabled:bg-gray-700 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                />
              </div>

              <div>
                <label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Up Time (Hours)
                </label>
                <input
                  type="number"
                  name="custom_up_time"
                  value={formData.custom_up_time || 0}
                  disabled
                  className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-md bg-gray-100 dark:bg-gray-700 text-gray-500 dark:text-gray-400"
                />
                <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
                  Calculated: Total Hours - Down Time
                </p>
              </div>

              {/* <div>
                <label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Model Number
                </label>
                <input
                  type="text"
                  placeholder="Model number"
                  disabled={!isEditing}
                  className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100 dark:disabled:bg-gray-700 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                />
              </div> */}
            </div>
          </div>

          {/* COLUMN 3: Location */}
          <div className="bg-white dark:bg-gray-800 rounded-lg shadow-md p-6">
            <h2 className="text-base font-semibold text-gray-800 dark:text-white mb-4 pb-2 border-b border-gray-200 dark:border-gray-700">
              Location
            </h2>
            <div className="space-y-4">
              <LinkField
                label="Hospital"
                doctype="Company"
                value={formData.company || ''}
                onChange={(val) => {
                  setFormData({
                    ...formData,
                    company: val,
                    asset_owner_company: val,
                    department: '',
                    custom_site: '',
                    custom_moh_supervisor: '',
                    custom_smeh_engg: '',
                  });
                }}
                disabled={isFieldDisabled('company')}
                filters={{ domain: 'Healthcare' }}
              />

              {shouldShowSiteNameField && (
                <LinkField
                  key={formData.company || 'site-name'}
                  label="Site Name"
                  doctype="Mobile Team Site"
                  value={formData.custom_site || ''}
                  onChange={(val) => setFormData({ ...formData, custom_site: val })}
                  disabled={isFieldDisabled('custom_site') || !formData.company || siteLocked}
                  filters={mobileTeamSiteFilters}
                  placeholder="Select Site"
                />
              )}

              <LinkField
                label="Department"
                doctype="Department"
                value={formData.department || ''}
                onChange={(val) => setFormData({ ...formData, department: val })}
                disabled={isFieldDisabled('department')}
                filters={departmentFilters}
              />

              <LinkField
                label="Location"
                doctype="Location"
                value={formData.location || ''}
                onChange={(val) => setFormData({ ...formData, location: val })}
                disabled={isFieldDisabled('location')}
              />

              <div>
                <label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                  MOH ID
                </label>
                <input
                  type="text"
                  name="custom_moh_id"
                  value={formData.custom_moh_id || ''}
                  onChange={handleChange}
                  placeholder="MOH ID"
                  disabled={isFieldDisabled('custom_moh_id')}
                  className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100 dark:disabled:bg-gray-700 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                />
              </div>

              <div>
                <label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Floor
                </label>
                <input
                  type="text"
                  name="custom_floor"
                  value={formData.custom_floor || ''}
                  onChange={handleChange}
                  placeholder="Floor"
                  disabled={isFieldDisabled('custom_floor')}
                  className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100 dark:disabled:bg-gray-700 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                />
              </div>

              <div>
                <label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Building
                </label>
                <input
                  type="text"
                  placeholder="Building name"
                  disabled={!isEditing}
                  className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100 dark:disabled:bg-gray-700 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                />
              </div>

              {/* <div>
                <label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Area/Unit
                </label>
                <input
                  type="text"
                  placeholder="Area or unit"
                  disabled={!isEditing}
                  className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100 dark:disabled:bg-gray-700 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                />
              </div> */}

              <div>
                <label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Room Number
                </label>
                <input
                  type="text"
                  placeholder="e.g. Room 001-002"
                  disabled={!isEditing}
                  className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100 dark:disabled:bg-gray-700 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                />
              </div>

              {/* <div>
                <label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Assigned To
                </label>
                <input
                  type="text"
                  placeholder="Person or department"
                  disabled={!isEditing}
                  className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100 dark:disabled:bg-gray-700 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                />
              </div> */}
            </div>
          </div>

          {/* COLUMN 4: More Details */}
          <div className="bg-white dark:bg-gray-800 rounded-lg shadow-md p-6">
            <h2 className="text-base font-semibold text-gray-800 dark:text-white mb-4 pb-2 border-b border-gray-200 dark:border-gray-700">
              More Details
            </h2>
            <div className="space-y-4">
              {/* <div>
                <label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Condition
                </label>
                <select
                  name="custom_device_status"
                  value={formData.custom_device_status}
                  onChange={handleChange}
                  disabled={isFieldDisabled('custom_device_status')}
                  className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100 dark:disabled:bg-gray-700 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                >
                  <option value="">Select status</option>
                  <option value="Operational">Operational</option>
                  <option value="Under Maintenance">Under Maintenance</option>
                  <option value="Decommissioned">Decommissioned</option>
                </select>
              </div> */}

              {/* QR Code */}
              <div className="flex flex-col items-center my-4">
                <div className="border-2 border-gray-300 dark:border-gray-600 p-3 rounded-lg bg-white dark:bg-gray-700">
                  {qrCodeUrl ? (
                    <>
                      <img
                        src={qrCodeUrl}
                        alt={`QR Code for ${asset?.name || 'Asset'}`}
                        className="w-[120px] h-[120px] object-contain"
                        onError={(e) => {
                          const target = e.target as HTMLImageElement;
                          target.style.display = 'none';
                          const fallback = target.nextElementSibling as HTMLElement;
                          if (fallback) {
                            fallback.style.display = 'flex';
                          }
                        }}
                      />
                      <div className="w-[120px] h-[120px] hidden items-center justify-center bg-gray-100 dark:bg-gray-700 rounded">
                        <FaQrcode size={80} className="text-gray-400 dark:text-gray-500" />
                      </div>
                    </>
                  ) : (
                    <div className="w-[120px] h-[120px] flex items-center justify-center bg-gray-100 dark:bg-gray-700 rounded">
                      <FaQrcode size={80} className="text-gray-400 dark:text-gray-500" />
                    </div>
                  )}
                </div>
                {asset?.name && (
                  <p className="mt-2 text-xs text-gray-500 dark:text-gray-400 text-center">
                    Asset ID: {asset.name}
                  </p>
                )}
              </div>

              <div>
                <label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Description
                </label>
                <textarea
                  rows={4}
                  placeholder="Brief description of the asset"
                  disabled={!isEditing}
                  className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100 dark:disabled:bg-gray-700 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                />
              </div>
            </div>
          </div>
        </div>

        {/* Bottom Sections - 2 Columns */}
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 mt-6">
          {/* Coverage */}
          <div className="bg-white dark:bg-gray-800 rounded-lg shadow-md p-6">
            <h2 className="text-base font-semibold text-gray-800 dark:text-white mb-4 pb-2 border-b border-gray-200 dark:border-gray-700">
              Coverage
            </h2>
            <div className="space-y-4">
              <div>
                <label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Site Contractor
                </label>
                <input
                  type="text"
                  name="custom_site_contractor"
                  value={formData.custom_site_contractor}
                  onChange={handleChange}
                  disabled={isFieldDisabled('custom_site_contractor')}
                  className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100 dark:disabled:bg-gray-700 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                />
              </div>

              <div>
                <label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Contract Number
                </label>
                <input
                  type="text"
                  disabled={!isEditing}
                  className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100 dark:disabled:bg-gray-700 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                />
              </div>

              <div>
                <label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Service Agreement
                </label>
                <select
                  name="custom_service_agreement"
                  value={formData.custom_service_agreement || ''}
                  onChange={handleChange}
                  disabled={isFieldDisabled('custom_service_agreement')}
                  className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100 dark:disabled:bg-gray-700 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                >
                  <option value="">Select Service Agreement</option>
                  <option value="Warranty">Warranty</option>
                  <option value="Contract">Contract</option>
                  <option value="Frame Work">Frame Work</option>
		  <option value="Main Contractor">Main Contractor</option>	
                  <option value="Out of warranty">Out of warranty</option>
                  <option value="Under Dismantle">Under Dismantle</option>
                  <option value="Under Installation">Under Installation</option>
                </select>
              </div>

              <div>
                <label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Service Coverage
                </label>
                <select
                  name="custom_service_coverage"
                  value={formData.custom_service_coverage || ''}
                  onChange={handleChange}
                  disabled={isFieldDisabled('custom_service_coverage')}
                  className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100 dark:disabled:bg-gray-700 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                >
                  <option value="">Select Service Coverage</option>
                  <option value="PM Only">PM Only</option>
                  <option value="Labour">Labour</option>
                  <option value="Labour & Parts">Labour & Parts</option>
                  <option value="Comprehensive">Comprehensive</option>
                </select>
              </div>

              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                    Start Date
                  </label>
                  <input
                    type="date"
                    name="custom_start_date"
                    value={formData.custom_start_date || ''}
                    onChange={handleChange}
                    disabled={isFieldDisabled('custom_start_date')}
                    className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100 dark:disabled:bg-gray-700 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                  />
                </div>

                <div>
                  <label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                    End Date
                  </label>
                  <input
                    type="date"
                    name="custom_end_date"
                    value={formData.custom_end_date || ''}
                    onChange={handleChange}
                    disabled={isFieldDisabled('custom_end_date')}
                    className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100 dark:disabled:bg-gray-700 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                  />
                </div>
              </div>

              <div>
                <label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Total Amount
                </label>
                <input
                  type="number"
                  name="custom_total_amount"
                  value={formData.custom_total_amount}
                  onChange={handleChange}
                  disabled={isFieldDisabled('custom_total_amount')}
                  className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100 dark:disabled:bg-gray-700 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                />
              </div>

              <div>
                <label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Comments
                </label>
                <textarea
                  rows={2}
                  disabled={!isEditing}
                  className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100 dark:disabled:bg-gray-700 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                />
              </div>
            </div>
          </div>

          {/* Acquisition Details */}
          <div className="bg-white dark:bg-gray-800 rounded-lg shadow-md p-6">
            <h2 className="text-base font-semibold text-gray-800 dark:text-white mb-4 pb-2 border-b border-gray-200 dark:border-gray-700">
              Acquisition Details
            </h2>
            <div className="space-y-4">
              <div>
                <label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Purchase Order Number
                </label>
                <input
                  type="text"
                  placeholder="PO number"
                  disabled={!isEditing}
                  className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100 dark:disabled:bg-gray-700 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                />
              </div>
              <LinkField
                key={`moh-supervisor-${formData.company || 'none'}`}
                label="MOH Supervisor"
                doctype="User"
                query="frappe.core.doctype.user.user.user_query"
                value={formData.custom_moh_supervisor || ''}
                onChange={(val) => setFormData({ ...formData, custom_moh_supervisor: val })}
                disabled={isFieldDisabled('custom_moh_supervisor') || !formData.company}
                filters={mohSupervisorFilters}
                placeholder={formData.company ? 'Select MOH Supervisor' : 'Select Hospital first'}
              />

              <LinkField
                key={`smeh-engg-${formData.company || 'none'}`}
                label="SMEH Engg"
                doctype="User"
                query="frappe.core.doctype.user.user.user_query"
                value={formData.custom_smeh_engg || ''}
                onChange={(val) => setFormData({ ...formData, custom_smeh_engg: val })}
                disabled={isFieldDisabled('custom_smeh_engg') || !formData.company}
                filters={smehEnggFilters}
                placeholder={formData.company ? 'Select SMEH Engg' : 'Select Hospital first'}
              />

              <LinkField
                label="Team Leader"
                doctype="User"
                value={formData.custom_team_leader || ''}
                onChange={(val) => setFormData({ ...formData, custom_team_leader: val })}
                disabled={isFieldDisabled('custom_team_leader')}
              />

              <LinkField
                label="Supplier/Vendor"
                doctype="Supplier"
                value={formData.supplier || ''}
                onChange={(val) => setFormData({ ...formData, supplier: val })}
                disabled={isFieldDisabled('supplier')}
              />

              <div>
                <label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Gross Purchase Amount
                </label>
                <input
                  type="number"
                  name="gross_purchase_amount"
                  value={formData.gross_purchase_amount || 0}
                  onChange={handleChange}
                  disabled={isFieldDisabled('gross_purchase_amount')}
                  className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100 dark:disabled:bg-gray-700 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                />
              </div>

              <div>
                <label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Purchase Date
                </label>
                <input
                  type="date"
                  disabled={!isEditing}
                  className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100 dark:disabled:bg-gray-700 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                />
              </div>

              <div>
                <label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Installation Date
                </label>
                <input
                  type="date"
                  disabled={!isEditing}
                  className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100 dark:disabled:bg-gray-700 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                />
              </div>

              <div>
                <label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Available For Use Date
                </label>
                <input
                  type="date"
                  name="available_for_use_date"
                  value={formData.available_for_use_date || ''}
                  onChange={(e) =>
                    setFormData((prev) => ({ ...prev, available_for_use_date: e.target.value }))
                  }
                  disabled={isFieldDisabled('available_for_use_date')}
                  className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100 dark:disabled:bg-gray-700 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                />
              </div>
            </div>
          </div>
        </div>


      {/* Updated Financial Details */}
        <div className="mt-6">
            <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
              <h2 className="text-lg font-semibold text-gray-800 dark:text-white mb-4">Financial Details</h2>
              <p className="text-sm text-gray-600 dark:text-gray-400 mb-4">
                The depreciation method is an accounting method used to allocate the cost of a tangible asset over its useful life.
              </p>
              
              <div className="flex items-center mb-6">
                <input
                  id="calculate_depreciation"
                  type="checkbox"
                  checked={formData.calculate_depreciation}
                  onChange={(e) =>
                    setFormData({
                      ...formData,
                      calculate_depreciation: e.target.checked,
                    })
                  }
                  disabled={!isEditing}
                  className="h-4 w-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500 dark:border-gray-600 dark:bg-gray-700"
                />
                <label
                  htmlFor="calculate_depreciation"
                  className="ml-2 text-sm font-medium text-gray-700 dark:text-gray-300"
                >
                  Calculate Depreciation
                </label>
              </div>

              {/* Asset Finance Book child table — shown only when checkbox checked */}
              {formData.calculate_depreciation && (
                <div className="border-t pt-4">
                  {/* Header with Add Row button */}
                  <div className="flex justify-between items-center mb-4">
                    <h3 className="text-md font-semibold text-gray-800 dark:text-white">
                      Asset Finance Books
                    </h3>
                    {isEditing && (
                      <button
                        type="button"
                        onClick={addFinanceRow}
                        className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 flex items-center gap-2"
                      >
                        <span>+</span> Add Row
                      </button>
                    )}
                  </div>

                  {/* Show message if no rows */}
                  {(!formData.finance_books || formData.finance_books.length === 0) && (
                    <div className="text-center py-8 text-gray-500 dark:text-gray-400 bg-gray-50 dark:bg-gray-900 rounded-lg">
                      No finance books added yet. Click "Add Row" to add one.
                    </div>
                  )}

                  {/* TABLE - Full width desktop view with overflow fix */}
                  {formData.finance_books && formData.finance_books.length > 0 && (
                    <div className="overflow-visible">
                      <div className="overflow-x-auto">
                        <table className="w-full border-collapse">
                          <thead>
                            <tr className="bg-gray-100 dark:bg-gray-700 border-b border-gray-300 dark:border-gray-600">
                              <th className="text-left px-4 py-3 text-sm font-semibold text-gray-700 dark:text-gray-300 min-w-[200px]">
                                Finance Book
                              </th>
                              <th className="text-left px-4 py-3 text-sm font-semibold text-gray-700 dark:text-gray-300 min-w-[200px]">
                                Depreciation Method*
                              </th>
                              <th className="text-left px-4 py-3 text-sm font-semibold text-gray-700 dark:text-gray-300 min-w-[180px]">
                                Total Depreciations*
                              </th>
                              <th className="text-left px-4 py-3 text-sm font-semibold text-gray-700 dark:text-gray-300 min-w-[180px]">
                                Frequency (Months)*
                              </th>
                              <th className="text-left px-4 py-3 text-sm font-semibold text-gray-700 dark:text-gray-300 min-w-[200px]">
                                Depreciation Posting Date*
                              </th>
                              {isEditing && (
                                <th className="text-center px-4 py-3 text-sm font-semibold text-gray-700 dark:text-gray-300 min-w-[120px]">
                                  Action
                                </th>
                              )}
                            </tr>
                          </thead>
                          <tbody>
                            {formData.finance_books.map((row: AssetFinanceBookRow, idx: number) => (
                              <tr
                                key={idx}
                                className="border-b border-gray-200 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-750"
                              >
                                {/* Finance Book - with overflow visible */}
                                <td className="px-4 py-3 relative" style={{ overflow: 'visible' }}>
                                  <div className="relative z-20">
                                    <LinkField
                                      label=""
                                      doctype="Finance Book"
                                      value={row.finance_book || ''}
                                      onChange={(val) => updateFinanceRow(idx, { finance_book: val })}
                                      disabled={!isEditing}
                                    />
                                  </div>
                                </td>

                                {/* Depreciation Method */}
                                <td className="px-4 py-3">
                                  <select
                                    value={row.depreciation_method || ''}
                                    onChange={(e) => updateFinanceRow(idx, { depreciation_method: e.target.value })}
                                    disabled={!isEditing}
                                    className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100 dark:disabled:bg-gray-700 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                                  >
                                    <option value="">Select Method</option>
                                    <option value="Straight Line">Straight Line</option>
                                    <option value="Double Declining Balance">Double Declining Balance</option>
                                    <option value="Written Down Value">Written Down Value</option>
                                    <option value="Manual">Manual</option>
                                  </select>
                                </td>

                                {/* Total Depreciations */}
                                <td className="px-4 py-3">
                                  <input
                                    type="number"
                                    value={row.total_number_of_depreciations ?? ''}
                                    onChange={(e) =>
                                      updateFinanceRow(idx, {
                                        total_number_of_depreciations: Number(e.target.value),
                                      })
                                    }
                                    disabled={!isEditing}
                                    placeholder="0"
                                    className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100 dark:disabled:bg-gray-700 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                                  />
                                </td>

                                {/* Frequency */}
                                <td className="px-4 py-3">
                                  <input
                                    type="number"
                                    value={row.frequency_of_depreciation ?? ''}
                                    onChange={(e) =>
                                      updateFinanceRow(idx, {
                                        frequency_of_depreciation: Number(e.target.value),
                                      })
                                    }
                                    disabled={!isEditing}
                                    placeholder="0"
                                    className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100 dark:disabled:bg-gray-700 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                                  />
                                </td>

                                {/* Start Date */}
                                <td className="px-4 py-3">
                                  <input
                                    type="date"
                                    value={row.depreciation_start_date || ''}
                                    onChange={(e) =>
                                      updateFinanceRow(idx, { depreciation_start_date: e.target.value })
                                    }
                                    disabled={!isEditing}
                                    className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100 dark:disabled:bg-gray-700 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                                  />
                                </td>

                                {/* REMOVE BUTTON */}
                                {isEditing && (
                                  <td className="px-4 py-3 text-center">
                                    <button
                                      type="button"
                                      onClick={() => removeFinanceRow(idx)}
                                      className="px-3 py-2 bg-red-600 text-white rounded-md hover:bg-red-700 transition-colors"
                                    >
                                      Remove
                                    </button>
                                  </td>
                                )}
                              </tr>
                            ))}
                          </tbody>
                        </table>
                      </div>
                    </div>
                  )}
                </div>
              )}
            </div>
          </div>

          {/* End-of-Life Details */}
        <div className="grid grid-cols-1 lg:grid-cols-4 gap-6 mt-6">
          <div className="bg-white dark:bg-gray-800 rounded-lg shadow-md p-6">
            <h2 className="text-base font-semibold text-gray-800 dark:text-white mb-4 pb-2 border-b border-gray-200 dark:border-gray-700">
              End-of-Life Details
            </h2>
            <div className="space-y-4">
              <div>
                <label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Expected End-of-Life Date
                </label>
                <input
                  type="date"
                  disabled={!isEditing}
                  className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100 dark:disabled:bg-gray-700 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                />
              </div>

              <div>
                <label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Disposal Method
                </label>
                <select
                  disabled={!isEditing}
                  className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100 dark:disabled:bg-gray-700 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                >
                  <option value="">Recycling</option>
                  <option value="Donation">Donation</option>
                  <option value="Sale">Sale</option>
                </select>
              </div>
            </div>
          </div>
        </div>

        {/* Warranty & Service Contract Checkboxes */}
        <div className="mt-6 bg-white dark:bg-gray-800 rounded-lg shadow-md p-6">
          <h2 className="text-base font-semibold text-gray-800 dark:text-white mb-4 pb-2 border-b border-gray-200 dark:border-gray-700">
            Warranty & Service Contract
          </h2>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
            {/* Custom Warranty */}
            <div className="flex items-center">
              <input
                id="custom_warranty"
                type="checkbox"
                checked={formData.custom_warranty || false}
                onChange={(e) => {
                  setFormData({ ...formData, custom_warranty: e.target.checked });
                }}
                disabled={isFieldDisabled('custom_warranty')}
                className={`h-5 w-5 rounded border-2 border-black focus:ring-2 focus:ring-blue-500 ${
                  formData.custom_warranty 
                    ? 'bg-green-500 border-black' 
                    : 'bg-red-500 border-black'
                }`}
              />
              <label htmlFor="custom_warranty" className="ml-2 text-sm font-medium text-gray-700 dark:text-gray-300">
                Warranty
              </label>
            </div>

            {/* Extended Warranty */}
            <div className="flex items-center">
              <input
                id="custom_extended_warranty"
                type="checkbox"
                checked={formData.custom_extended_warranty || false}
                onChange={(e) => {
                  setFormData({ ...formData, custom_extended_warranty: e.target.checked });
                }}
                disabled={isFieldDisabled('custom_extended_warranty')}
                className={`h-5 w-5 rounded border-2 border-black focus:ring-2 focus:ring-blue-500 ${
                  formData.custom_extended_warranty 
                    ? 'bg-green-500 border-black' 
                    : 'bg-red-500 border-black'
                }`}
              />
              <label htmlFor="custom_extended_warranty" className="ml-2 text-sm font-medium text-gray-700 dark:text-gray-300">
                Extended Warranty
              </label>
            </div>

            {/* Service Contract */}
            <div className="flex items-center">
              <input
                id="custom__service_contract"
                type="checkbox"
                checked={formData.custom__service_contract || false}
                onChange={(e) => {
                  setFormData({ ...formData, custom__service_contract: e.target.checked });
                }}
                disabled={isFieldDisabled('custom__service_contract')}
                className={`h-5 w-5 rounded border-2 border-black focus:ring-2 focus:ring-blue-500 ${
                  formData.custom__service_contract 
                    ? 'bg-green-500 border-black' 
                    : 'bg-red-500 border-black'
                }`}
              />
              <label htmlFor="custom__service_contract" className="ml-2 text-sm font-medium text-gray-700 dark:text-gray-300">
                Service Contract
              </label>
            </div>

            {/* Covering Spare Parts */}
            <div className="flex items-center">
              <input
                id="custom_covering_spare_parts"
                type="checkbox"
                checked={formData.custom_covering_spare_parts || false}
                onChange={(e) => {
                  setFormData({ ...formData, custom_covering_spare_parts: e.target.checked });
                }}
                disabled={isFieldDisabled('custom_covering_spare_parts')}
                className={`h-5 w-5 rounded border-2 border-black focus:ring-2 focus:ring-blue-500 ${
                  formData.custom_covering_spare_parts 
                    ? 'bg-green-500 border-black' 
                    : 'bg-red-500 border-black'
                }`}
              />
              <label htmlFor="custom_covering_spare_parts" className="ml-2 text-sm font-medium text-gray-700 dark:text-gray-300">
                Covering Spare Parts
              </label>
            </div>

            {/* Spare Parts Labour */}
            <div className="flex items-center">
              <input
                id="custom_spare_parts_labour"
                type="checkbox"
                checked={formData.custom_spare_parts_labour || false}
                onChange={(e) => {
                  setFormData({ ...formData, custom_spare_parts_labour: e.target.checked });
                }}
                disabled={isFieldDisabled('custom_spare_parts_labour')}
                className={`h-5 w-5 rounded border-2 border-black focus:ring-2 focus:ring-blue-500 ${
                  formData.custom_spare_parts_labour 
                    ? 'bg-green-500 border-black' 
                    : 'bg-red-500 border-black'
                }`}
              />
              <label htmlFor="custom_spare_parts_labour" className="ml-2 text-sm font-medium text-gray-700 dark:text-gray-300">
                Spare Parts Labour
              </label>
            </div>

            {/* Covering Labour */}
            <div className="flex items-center">
              <input
                id="custom_covering_labour"
                type="checkbox"
                checked={formData.custom_covering_labour || false}
                onChange={(e) => {
                  setFormData({ ...formData, custom_covering_labour: e.target.checked });
                }}
                disabled={isFieldDisabled('custom_covering_labour')}
                className={`h-5 w-5 rounded border-2 border-black focus:ring-2 focus:ring-blue-500 ${
                  formData.custom_covering_labour 
                    ? 'bg-green-500 border-black' 
                    : 'bg-red-500 border-black'
                }`}
              />
              <label htmlFor="custom_covering_labour" className="ml-2 text-sm font-medium text-gray-700 dark:text-gray-300">
                Covering Labour
              </label>
            </div>

            {/* PPM Only */}
            <div className="flex items-center">
              <input
                id="custom_ppm_only"
                type="checkbox"
                checked={formData.custom_ppm_only || false}
                onChange={(e) => {
                  setFormData({ ...formData, custom_ppm_only: e.target.checked });
                }}
                disabled={isFieldDisabled('custom_ppm_only')}
                className={`h-5 w-5 rounded border-2 border-black focus:ring-2 focus:ring-blue-500 ${
                  formData.custom_ppm_only 
                    ? 'bg-green-500 border-black' 
                    : 'bg-red-500 border-black'
                }`}
              />
              <label htmlFor="custom_ppm_only" className="ml-2 text-sm font-medium text-gray-700 dark:text-gray-300">
                PPM Only
              </label>
            </div>
          </div>

          {/* Support Plan Field */}
          <div className="mt-4">
            <label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
              Support Plan
            </label>
            <input
              type="text"
              name="custom_support_plan"
              value={formData.custom_support_plan || ''}
              onChange={handleChange}
              disabled={isFieldDisabled('custom_support_plan')}
              className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100 dark:disabled:bg-gray-700 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
            />
          </div>
        </div>

        {/* Spare Parts Table */}
        <div className="mt-6 bg-white dark:bg-gray-800 rounded-lg shadow-md p-6">
          <div className="flex justify-between items-center mb-4">
            <h2 className="text-base font-semibold text-gray-800 dark:text-white">
              Spare Parts
            </h2>
            {isEditing && (
              <button
                type="button"
                onClick={addSparePartRow}
                className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 flex items-center gap-2 text-sm"
              >
                <span>+</span> Add Row
              </button>
            )}
          </div>

          {(!formData.custom_spare_parts || formData.custom_spare_parts.length === 0) && (
            <div className="text-center py-8 text-gray-500 dark:text-gray-400 bg-gray-50 dark:bg-gray-900 rounded-lg">
              No spare parts added yet. Click "Add Row" to add one.
            </div>
          )}

          {formData.custom_spare_parts && formData.custom_spare_parts.length > 0 && (
            <div className="overflow-x-auto">
              <table className="w-full border-collapse">
                <thead>
                  <tr className="bg-gray-100 dark:bg-gray-700 border-b border-gray-300 dark:border-gray-600">
                    <th className="text-left px-4 py-3 text-sm font-semibold text-gray-700 dark:text-gray-300">Item Code</th>
                    <th className="text-left px-4 py-3 text-sm font-semibold text-gray-700 dark:text-gray-300">Item Name</th>
                    <th className="text-left px-4 py-3 text-sm font-semibold text-gray-700 dark:text-gray-300">Qty</th>
                    <th className="text-left px-4 py-3 text-sm font-semibold text-gray-700 dark:text-gray-300">Rate</th>
                    <th className="text-left px-4 py-3 text-sm font-semibold text-gray-700 dark:text-gray-300">Amount</th>
                    <th className="text-left px-4 py-3 text-sm font-semibold text-gray-700 dark:text-gray-300">UOM</th>
                    {isEditing && (
                      <th className="text-center px-4 py-3 text-sm font-semibold text-gray-700 dark:text-gray-300">Action</th>
                    )}
                  </tr>
                </thead>
                <tbody>
                  {formData.custom_spare_parts.map((row: any, idx: number) => (
                    <tr
                      key={idx}
                      className="border-b border-gray-200 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-750"
                    >
                      <td className="px-4 py-3">
                        <input
                          type="text"
                          value={row.item_code || ''}
                          onChange={(e) => updateSparePartRow(idx, 'item_code', e.target.value)}
                          disabled={!isEditing}
                          className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100 dark:disabled:bg-gray-700 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                        />
                      </td>
                      <td className="px-4 py-3">
                        <input
                          type="text"
                          value={row.item_name || ''}
                          onChange={(e) => updateSparePartRow(idx, 'item_name', e.target.value)}
                          disabled={!isEditing}
                          className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100 dark:disabled:bg-gray-700 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                        />
                      </td>
                      <td className="px-4 py-3">
                        <input
                          type="number"
                          value={row.qty || 0}
                          onChange={(e) => updateSparePartRow(idx, 'qty', Number(e.target.value))}
                          disabled={!isEditing}
                          className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100 dark:disabled:bg-gray-700 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                        />
                      </td>
                      <td className="px-4 py-3">
                        <input
                          type="number"
                          value={row.rate || 0}
                          onChange={(e) => updateSparePartRow(idx, 'rate', Number(e.target.value))}
                          disabled={!isEditing}
                          className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100 dark:disabled:bg-gray-700 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                        />
                      </td>
                      <td className="px-4 py-3">
                        <input
                          type="number"
                          value={row.amount || 0}
                          disabled
                          className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-md bg-gray-100 dark:bg-gray-700 text-gray-500 dark:text-gray-400"
                        />
                      </td>
                      <td className="px-4 py-3">
                        <input
                          type="text"
                          value={row.uom || ''}
                          onChange={(e) => updateSparePartRow(idx, 'uom', e.target.value)}
                          disabled={!isEditing}
                          className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100 dark:disabled:bg-gray-700 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                        />
                      </td>
                      {isEditing && (
                        <td className="px-4 py-3 text-center">
                          <button
                            type="button"
                            onClick={() => removeSparePartRow(idx)}
                            className="px-3 py-2 bg-red-600 text-white rounded-md hover:bg-red-700 transition-colors text-sm"
                          >
                            Remove
                          </button>
                        </td>
                      )}
                    </tr>
                  ))}
                </tbody>
                <tfoot>
                  <tr className="bg-gray-100 dark:bg-gray-700 font-semibold">
                    <td colSpan={4} className="px-4 py-3 text-right text-sm text-gray-700 dark:text-gray-300">
                      Total Amount:
                    </td>
                    <td className="px-4 py-3 text-sm text-gray-900 dark:text-white">
                      {formData.custom_total_spare_parts_amount || 0}
                    </td>
                    <td colSpan={isEditing ? 2 : 1}></td>
                  </tr>
                </tfoot>
              </table>
            </div>
          )}
        </div>
      </form>

      {!isNewAsset && !isDuplicating && (
        <div className="mt-6 space-y-6 max-w-5xl">
          <CommentSection
            referenceDoctype="Asset"
            referenceName={assetName || null}
            pollInterval={30000}
            initialLimit={5}
          />
          <ActivityLog
            doctype="Asset"
            docname={assetName || null}
            creationDate={asset?.creation}
            createdBy={asset?.owner}
            initialVisible={5}
            collapsible={false}
            startCollapsed={false}
          />
        </div>
      )}
    </div>
  );
};

export default AssetDetail;
