import React, { useState, useEffect, useCallback } from 'react';
import { useParams, useNavigate, useSearchParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { useSupportPlanDetails, useSupportPlanMutations } from '../hooks/useSupportPlan';
import { 
  FaArrowLeft, FaSave, FaEdit, FaTrash, FaCheckCircle, FaTimesCircle,
  FaExclamationTriangle, FaFileContract, FaShieldAlt, FaCog, FaCalendarAlt,
  FaWrench, FaHistory, FaClock, FaChevronDown, FaChevronUp
} from 'react-icons/fa';
import { toast, ToastContainer, Bounce } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import LinkField from '../components/LinkField';
import type { CreateSupportPlanData } from '../services/supportPlanService';
import CommentSection from '../components/CommentSection';

const getStatusStyle = (status: string) => {
  switch (status?.toLowerCase()) {
    case 'active': return { bg: 'bg-green-100 dark:bg-green-900/30', text: 'text-green-800 dark:text-green-300', border: 'border-green-200 dark:border-green-800' };
    case 'inactive': return { bg: 'bg-gray-100 dark:bg-gray-700', text: 'text-gray-800 dark:text-gray-300', border: 'border-gray-200 dark:border-gray-600' };
    case 'expired': return { bg: 'bg-red-100 dark:bg-red-900/30', text: 'text-red-800 dark:text-red-300', border: 'border-red-200 dark:border-red-800' };
    default: return { bg: 'bg-gray-100 dark:bg-gray-700', text: 'text-gray-800 dark:text-gray-300', border: 'border-gray-200 dark:border-gray-600' };
  }
};

interface AuditLogEntry {
  name: string;
  owner: string;
  creation: string;
  changes: Array<{ field: string; oldValue: any; newValue: any }>;
}

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

  const [canDelete, setCanDelete] = useState(true);
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  const [auditLogs, setAuditLogs] = useState<AuditLogEntry[]>([]);
  const [auditLogsLoading, setAuditLogsLoading] = useState(false);
  // const [auditLogsExpanded, setAuditLogsExpanded] = useState(true);
  const [auditLogsExpanded, setAuditLogsExpanded] = useState(false);
  const [showAllLogs, setShowAllLogs] = useState(false);

  const [formData, setFormData] = useState<CreateSupportPlanData>({
    support_plan: '',
    frequency: 'Quarterly',
    max_downtime_hrs: 0,
    asset: null,
    starting_date: null,
    penalty_factor: 5,
    custom_contractwarranty: 'Contract',
    custom_contract_value: '',
    warranty: 0,
    warranty_start_date: null,
    warranty_end_date: null,
    war_status: 'Active',
    extended_warranty: 0,
    start: null,
    end: null,
    service_contract: 1,
    spare_parts: 1,
    spare_parts_labour: 0,
    labour: 0,
    ppm_only: 0,
    no: 0,
    start_date: null,
    end_date: null,
    service_contract_status: 'Active',
    vendor: null,
    asset_list: [],
  });

  const { supportPlan, loading, error, refetch } = useSupportPlanDetails(isNewPlan ? null : slaName || null);
  const { createSupportPlan, updateSupportPlan, deleteSupportPlan, loading: saving } = useSupportPlanMutations();

  const [isEditing, setIsEditing] = useState(isNewPlan || startInEditMode);

  const fetchAuditLogs = useCallback(async () => {
    if (isNewPlan || !slaName) return;
    setAuditLogsLoading(true);
    try {
      const response = await fetch(`/api/resource/Version?filters=[["ref_doctype","=","Support Plans"],["docname","=","${encodeURIComponent(slaName)}"]]&fields=["name","owner","creation","data"]&order_by=creation desc&limit=50`);
      const result = await response.json();
      if (result?.data && result.data.length > 0) {
        const parsedLogs: AuditLogEntry[] = result.data.map((version: any) => {
          let parsedData = { changed: [] };
          try { parsedData = JSON.parse(version.data || '{}'); } catch (e) { }
          return {
            name: version.name,
            owner: version.owner,
            creation: version.creation,
            changes: (parsedData.changed || []).map((change: any[]) => ({ field: change[0] || '', oldValue: change[1], newValue: change[2] }))
          };
        });
        setAuditLogs(parsedLogs);
      } else { setAuditLogs([]); }
    } catch (err) { console.error('Error fetching audit logs:', err); setAuditLogs([]); }
    finally { setAuditLogsLoading(false); }
  }, [isNewPlan, slaName]);

  useEffect(() => { fetchAuditLogs(); }, [fetchAuditLogs]);

  useEffect(() => {
    if (supportPlan && !isNewPlan) {
      setFormData({
        support_plan: supportPlan.support_plan || '',
        frequency: supportPlan.frequency || 'Quarterly',
        max_downtime_hrs: supportPlan.max_downtime_hrs || 0,
        asset: supportPlan.asset || null,
        starting_date: supportPlan.starting_date || null,
        penalty_factor: supportPlan.penalty_factor || 5,
        custom_contractwarranty: supportPlan.custom_contractwarranty || 'Contract',
        custom_contract_value: supportPlan.custom_contract_value || '',
        warranty: supportPlan.warranty || 0,
        warranty_start_date: supportPlan.warranty_start_date || null,
        warranty_end_date: supportPlan.warranty_end_date || null,
        war_status: supportPlan.war_status || 'Active',
        extended_warranty: supportPlan.extended_warranty || 0,
        start: supportPlan.start || null,
        end: supportPlan.end || null,
        service_contract: supportPlan.service_contract || 0,
        spare_parts: supportPlan.spare_parts || 0,
        spare_parts_labour: supportPlan.spare_parts_labour || 0,
        labour: supportPlan.labour || 0,
        ppm_only: supportPlan.ppm_only || 0,
        no: supportPlan.no || 0,
        start_date: supportPlan.start_date || null,
        end_date: supportPlan.end_date || null,
        service_contract_status: supportPlan.service_contract_status || 'Active',
        vendor: supportPlan.vendor || null,
        asset_list: supportPlan.asset_list || [],
      });
      if (!startInEditMode) setIsEditing(false);
    }
  }, [supportPlan, isNewPlan, startInEditMode]);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) => {
    const { name, value, type } = e.target;
    if (type === 'checkbox') {
      setFormData(prev => ({ ...prev, [name]: (e.target as HTMLInputElement).checked ? 1 : 0 }));
    } else if (type === 'number') {
      setFormData(prev => ({ ...prev, [name]: parseFloat(value) || 0 }));
    } else {
      setFormData(prev => ({ ...prev, [name]: value }));
    }
  };

  const handleSave = async () => {
    if (!formData.support_plan?.trim()) {
      toast.error('Support Plan Name is required', { position: "top-right", autoClose: 5000, icon: <FaTimesCircle /> });
      return;
    }
    try {
      if (isNewPlan) {
        const newPlan = await createSupportPlan(formData);
        toast.success('Support Plan created successfully!', { position: "top-right", autoClose: 3000, icon: <FaCheckCircle /> });
        navigate(`/sla/${newPlan.name}`);
      } else {
        await updateSupportPlan(slaName!, formData);
        toast.success('Support Plan updated successfully!', { position: "top-right", autoClose: 3000, icon: <FaCheckCircle /> });
        setIsEditing(false);
        refetch();
        setTimeout(() => fetchAuditLogs(), 500);
      }
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'Unknown error';
      toast.error(`Failed to save: ${errorMessage}`, { position: "top-right", autoClose: 6000, icon: <FaTimesCircle /> });
    }
  };

  const handleDelete = async () => {
    try {
      await deleteSupportPlan(slaName!);
      toast.success('Support Plan deleted successfully!', { position: "top-right", autoClose: 3000, icon: <FaCheckCircle /> });
      navigate(-1);
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'Unknown error';
      toast.error(`Failed to delete: ${errorMessage}`, { position: "top-right", autoClose: 6000, icon: <FaTimesCircle /> });
    }
  };

  const isFieldDisabled = useCallback((fieldname: string): boolean => !isEditing, [isEditing]);
  const formatFieldName = (fieldName: string): string => fieldName.replace(/^custom_/, '').replace(/_/g, ' ').replace(/\b\w/g, char => char.toUpperCase());
  const formatValue = (value: any): string => value === null || value === undefined || value === '' ? '(empty)' : String(value);
  const formatAuditDate = (dateStr: string): string => {
    if (!dateStr) return '';
    const date = new Date(dateStr);
    const now = new Date();
    const diffMs = now.getTime() - date.getTime();
    const diffMins = Math.floor(diffMs / 60000);
    const diffHours = Math.floor(diffMs / 3600000);
    const diffDays = Math.floor(diffMs / 86400000);
    if (diffMins < 1) return 'Just now';
    if (diffMins < 60) return `${diffMins} min${diffMins > 1 ? 's' : ''} ago`;
    if (diffHours < 24) return `${diffHours} hour${diffHours > 1 ? 's' : ''} ago`;
    if (diffDays < 7) return `${diffDays} day${diffDays > 1 ? 's' : ''} ago`;
    return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: date.getFullYear() !== now.getFullYear() ? 'numeric' : undefined, hour: '2-digit', minute: '2-digit' });
  };
  const formatUsername = (email: string): string => email ? email.split('@')[0] : 'Unknown';

  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-indigo-500 mx-auto"></div>
          <p className="mt-4 text-gray-600 dark:text-gray-400">Loading support plan...</p>
        </div>
      </div>
    );
  }

  if (error && !isNewPlan) {
    return (
      <div className="p-6 bg-gray-50 dark:bg-gray-900 min-h-screen">
        <div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-6">
          <h2 className="text-xl font-bold text-red-800 dark:text-red-300 mb-4">Error Loading Support Plan</h2>
          <p className="text-red-700 dark:text-red-400 mb-4">{error}</p>
          <button onClick={() => navigate(-1)} className="bg-indigo-600 hover:bg-indigo-700 text-white px-4 py-2 rounded">Back to Support Plans</button>
        </div>
      </div>
    );
  }

  const warStatusStyle = getStatusStyle(formData.war_status || '');
  const contractStatusStyle = getStatusStyle(formData.service_contract_status || '');

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

      {/* Header */}
      <div className="mb-6 flex justify-between items-center">
        <div className="flex items-center gap-4">
          <button onClick={() => navigate(-1)} className="text-gray-600 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200"><FaArrowLeft size={20} /></button>
          <div>
            <h1 className="text-2xl font-bold text-gray-800 dark:text-white flex items-center gap-3">
              {isNewPlan ? 'New Support Plan' : formData.support_plan || supportPlan?.name || 'Support Plan Details'}
              {!isNewPlan && formData.custom_contractwarranty && (
                <span className={`px-3 py-1 rounded-full text-sm font-medium ${formData.custom_contractwarranty === 'Contract' ? 'bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300' : 'bg-purple-100 dark:bg-purple-900/30 text-purple-700 dark:text-purple-300'}`}>
                  {formData.custom_contractwarranty}
                </span>
              )}
            </h1>
            <p className="text-gray-600 dark:text-gray-400 mt-1">{isNewPlan ? 'Create a new support plan' : `ID: ${slaName}`}</p>
          </div>
        </div>
        <div className="flex gap-3">
          {!isNewPlan && !isEditing && (
            <>
              <button onClick={() => setIsEditing(true)} className="bg-indigo-600 hover:bg-indigo-700 text-white px-4 py-2 rounded-lg flex items-center gap-2"><FaEdit />Edit</button>
              {canDelete && <button onClick={() => setShowDeleteConfirm(true)} className="bg-red-600 hover:bg-red-700 text-white px-4 py-2 rounded-lg flex items-center gap-2"><FaTrash />Delete</button>}
            </>
          )}
          {isEditing && (
            <>
              <button onClick={() => { if (isNewPlan) navigate(-1); else { setIsEditing(false); refetch(); } }} className="bg-gray-600 hover:bg-gray-700 text-white px-4 py-2 rounded-lg">Cancel</button>
              <button onClick={handleSave} disabled={saving} className="bg-green-600 hover:bg-green-700 text-white px-4 py-2 rounded-lg flex items-center gap-2 disabled:opacity-50"><FaSave />{saving ? 'Saving...' : 'Save'}</button>
            </>
          )}
        </div>
      </div>

      {/* Delete Confirmation Modal */}
      {showDeleteConfirm && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white dark:bg-gray-800 rounded-lg p-6 max-w-md w-full mx-4 shadow-xl">
            <div className="flex items-start gap-3 mb-4">
              <FaExclamationTriangle className="text-red-500 text-xl mt-0.5" />
              <div>
                <h3 className="text-lg font-semibold text-gray-800 dark:text-white">Delete Support Plan</h3>
                <p className="text-gray-600 dark:text-gray-400 mt-1">Are you sure you want to delete this support plan? This action cannot be undone.</p>
              </div>
            </div>
            <div className="flex justify-end gap-3">
              <button onClick={() => setShowDeleteConfirm(false)} className="px-4 py-2 bg-gray-300 hover:bg-gray-400 text-gray-700 rounded-lg">Cancel</button>
              <button onClick={handleDelete} disabled={saving} className="px-4 py-2 bg-red-600 hover:bg-red-700 text-white rounded-lg disabled:opacity-50">{saving ? 'Deleting...' : 'Delete'}</button>
            </div>
          </div>
        </div>
      )}

      {/* Form */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Main Content */}
        <div className="lg:col-span-2 space-y-6">
          {/* Basic Information */}
          <div className="bg-white dark:bg-gray-800 rounded-xl shadow-md p-6 border border-gray-200 dark:border-gray-700">
            <h2 className="text-lg font-semibold text-gray-800 dark:text-white mb-4 pb-2 border-b border-gray-200 dark:border-gray-700 flex items-center gap-2">
              <FaFileContract className="text-indigo-500" />Basic Information
            </h2>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Support Plan Name <span className="text-red-500">*</span></label>
                <input type="text" name="support_plan" value={formData.support_plan || ''} onChange={handleChange} disabled={isFieldDisabled('support_plan')} placeholder="Enter plan name" className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-white disabled:bg-gray-100 dark:disabled:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-indigo-500" />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Contract/Warranty Type</label>
                <select name="custom_contractwarranty" value={formData.custom_contractwarranty || ''} onChange={handleChange} disabled={isFieldDisabled('custom_contractwarranty')} className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-white disabled:bg-gray-100 dark:disabled:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-indigo-500">
                  <option value="Contract">Contract</option>
                  <option value="Warranty">Warranty</option>
                </select>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Frequency</label>
                <select name="frequency" value={formData.frequency || ''} onChange={handleChange} disabled={isFieldDisabled('frequency')} className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-white disabled:bg-gray-100 dark:disabled:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-indigo-500">
                  <option value="Monthly">Monthly</option>
                  <option value="Quarterly">Quarterly</option>
                  <option value="Half-Yearly">Half-Yearly</option>
                  <option value="Yearly">Yearly</option>
                </select>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Contract Value</label>
                <input type="text" name="custom_contract_value" value={formData.custom_contract_value || ''} onChange={handleChange} disabled={isFieldDisabled('custom_contract_value')} placeholder="e.g., 10000" className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-white disabled:bg-gray-100 dark:disabled:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-indigo-500" />
              </div>
              <div>
                <LinkField label="Asset" doctype="Asset" value={formData.asset || ''} onChange={(val) => setFormData({ ...formData, asset: val || null })} disabled={isFieldDisabled('asset')} placeholder="Select Asset" />
              </div>
              <div>
                <LinkField label="Vendor" doctype="Supplier" value={formData.vendor || ''} onChange={(val) => setFormData({ ...formData, vendor: val || null })} disabled={isFieldDisabled('vendor')} placeholder="Select Vendor" />
              </div>
            </div>
          </div>

          {/* Performance Settings */}
          <div className="bg-white dark:bg-gray-800 rounded-xl shadow-md p-6 border border-gray-200 dark:border-gray-700">
            <h2 className="text-lg font-semibold text-gray-800 dark:text-white mb-4 pb-2 border-b border-gray-200 dark:border-gray-700 flex items-center gap-2">
              <FaCog className="text-orange-500" />Performance Settings
            </h2>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Max Downtime (hrs)</label>
                <input type="number" name="max_downtime_hrs" value={formData.max_downtime_hrs || 0} onChange={handleChange} disabled={isFieldDisabled('max_downtime_hrs')} min="0" className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-white disabled:bg-gray-100 dark:disabled:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-indigo-500" />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Penalty Factor (%)</label>
                <input type="number" name="penalty_factor" value={formData.penalty_factor || 0} onChange={handleChange} disabled={isFieldDisabled('penalty_factor')} min="0" className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-white disabled:bg-gray-100 dark:disabled:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-indigo-500" />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Starting Date</label>
                <input type="date" name="starting_date" value={formData.starting_date || ''} onChange={handleChange} disabled={isFieldDisabled('starting_date')} className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-white disabled:bg-gray-100 dark:disabled:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-indigo-500" />
              </div>
            </div>
          </div>

          {/* Warranty Section */}
          <div className="bg-white dark:bg-gray-800 rounded-xl shadow-md p-6 border border-gray-200 dark:border-gray-700">
            <h2 className="text-lg font-semibold text-gray-800 dark:text-white mb-4 pb-2 border-b border-gray-200 dark:border-gray-700 flex items-center gap-2">
              <FaShieldAlt className="text-purple-500" />Warranty Information
            </h2>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="flex items-center gap-3">
                <input type="checkbox" name="warranty" checked={!!formData.warranty} onChange={handleChange} disabled={isFieldDisabled('warranty')} className="h-4 w-4 text-indigo-600 rounded" />
                <label className="text-sm font-medium text-gray-700 dark:text-gray-300">Has Warranty</label>
              </div>
              <div className="flex items-center gap-3">
                <input type="checkbox" name="extended_warranty" checked={!!formData.extended_warranty} onChange={handleChange} disabled={isFieldDisabled('extended_warranty')} className="h-4 w-4 text-indigo-600 rounded" />
                <label className="text-sm font-medium text-gray-700 dark:text-gray-300">Extended Warranty</label>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Warranty Status</label>
                <select name="war_status" value={formData.war_status || ''} onChange={handleChange} disabled={isFieldDisabled('war_status')} className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-white disabled:bg-gray-100 dark:disabled:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-indigo-500">
                  <option value="Active">Active</option>
                  <option value="Inactive">Inactive</option>
                  <option value="Expired">Expired</option>
                </select>
              </div>
              <div></div>
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Warranty Start Date</label>
                <input type="date" name="warranty_start_date" value={formData.warranty_start_date || ''} onChange={handleChange} disabled={isFieldDisabled('warranty_start_date')} className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-white disabled:bg-gray-100 dark:disabled:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-indigo-500" />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Warranty End Date</label>
                <input type="date" name="warranty_end_date" value={formData.warranty_end_date || ''} onChange={handleChange} disabled={isFieldDisabled('warranty_end_date')} className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-white disabled:bg-gray-100 dark:disabled:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-indigo-500" />
              </div>
            </div>
          </div>

          {/* Service Contract Section */}
          <div className="bg-white dark:bg-gray-800 rounded-xl shadow-md p-6 border border-gray-200 dark:border-gray-700">
            <h2 className="text-lg font-semibold text-gray-800 dark:text-white mb-4 pb-2 border-b border-gray-200 dark:border-gray-700 flex items-center gap-2">
              <FaWrench className="text-blue-500" />Service Contract
            </h2>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="flex items-center gap-3">
                <input type="checkbox" name="service_contract" checked={!!formData.service_contract} onChange={handleChange} disabled={isFieldDisabled('service_contract')} className="h-4 w-4 text-indigo-600 rounded" />
                <label className="text-sm font-medium text-gray-700 dark:text-gray-300">Has Service Contract</label>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Service Contract Status</label>
                <select name="service_contract_status" value={formData.service_contract_status || ''} onChange={handleChange} disabled={isFieldDisabled('service_contract_status')} className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-white disabled:bg-gray-100 dark:disabled:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-indigo-500">
                  <option value="Active">Active</option>
                  <option value="Inactive">Inactive</option>
                  <option value="Expired">Expired</option>
                </select>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Start Date</label>
                <input type="date" name="start_date" value={formData.start_date || ''} onChange={handleChange} disabled={isFieldDisabled('start_date')} className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-white disabled:bg-gray-100 dark:disabled:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-indigo-500" />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">End Date</label>
                <input type="date" name="end_date" value={formData.end_date || ''} onChange={handleChange} disabled={isFieldDisabled('end_date')} className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-white disabled:bg-gray-100 dark:disabled:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-indigo-500" />
              </div>
            </div>
            <div className="mt-4 pt-4 border-t border-gray-200 dark:border-gray-700">
              <h3 className="text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">Inclusions</h3>
              <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                <div className="flex items-center gap-2">
                  <input type="checkbox" name="spare_parts" checked={!!formData.spare_parts} onChange={handleChange} disabled={isFieldDisabled('spare_parts')} className="h-4 w-4 text-indigo-600 rounded" />
                  <label className="text-sm text-gray-600 dark:text-gray-400">Spare Parts</label>
                </div>
                <div className="flex items-center gap-2">
                  <input type="checkbox" name="spare_parts_labour" checked={!!formData.spare_parts_labour} onChange={handleChange} disabled={isFieldDisabled('spare_parts_labour')} className="h-4 w-4 text-indigo-600 rounded" />
                  <label className="text-sm text-gray-600 dark:text-gray-400">Spare Parts + Labour</label>
                </div>
                <div className="flex items-center gap-2">
                  <input type="checkbox" name="labour" checked={!!formData.labour} onChange={handleChange} disabled={isFieldDisabled('labour')} className="h-4 w-4 text-indigo-600 rounded" />
                  <label className="text-sm text-gray-600 dark:text-gray-400">Labour Only</label>
                </div>
                <div className="flex items-center gap-2">
                  <input type="checkbox" name="ppm_only" checked={!!formData.ppm_only} onChange={handleChange} disabled={isFieldDisabled('ppm_only')} className="h-4 w-4 text-indigo-600 rounded" />
                  <label className="text-sm text-gray-600 dark:text-gray-400">PPM Only</label>
                </div>
              </div>
            </div>

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

        </div>

        {/* Sidebar */}
        <div className="space-y-4">
          {/* Status Overview */}
          <div className="bg-white dark:bg-gray-800 rounded-xl shadow-md p-4 border border-gray-200 dark:border-gray-700">
            <h2 className="text-sm font-semibold text-gray-800 dark:text-white mb-3 pb-2 border-b border-gray-200 dark:border-gray-700 flex items-center gap-2">
              <FaFileContract className="text-indigo-500" size={14} />Status Overview
            </h2>
            <div className="space-y-3">
              <div className={`p-3 rounded-lg border ${formData.custom_contractwarranty === 'Contract' ? 'bg-blue-50 dark:bg-blue-900/20 border-blue-200 dark:border-blue-800' : 'bg-purple-50 dark:bg-purple-900/20 border-purple-200 dark:border-purple-800'}`}>
                <p className="text-[10px] text-gray-500 dark:text-gray-400">Type</p>
                <p className={`text-sm font-semibold ${formData.custom_contractwarranty === 'Contract' ? 'text-blue-700 dark:text-blue-300' : 'text-purple-700 dark:text-purple-300'}`}>{formData.custom_contractwarranty || 'Not Set'}</p>
              </div>
              {formData.custom_contractwarranty === 'Warranty' && (
                <div className={`p-3 rounded-lg border ${warStatusStyle.bg} ${warStatusStyle.border}`}>
                  <p className="text-[10px] text-gray-500 dark:text-gray-400">Warranty Status</p>
                  <p className={`text-sm font-semibold ${warStatusStyle.text}`}>{formData.war_status || 'Not Set'}</p>
                </div>
              )}
              {formData.custom_contractwarranty === 'Contract' && (
                <div className={`p-3 rounded-lg border ${contractStatusStyle.bg} ${contractStatusStyle.border}`}>
                  <p className="text-[10px] text-gray-500 dark:text-gray-400">Contract Status</p>
                  <p className={`text-sm font-semibold ${contractStatusStyle.text}`}>{formData.service_contract_status || 'Not Set'}</p>
                </div>
              )}
              {formData.frequency && (
                <div className="p-3 bg-indigo-50 dark:bg-indigo-900/20 rounded-lg border border-indigo-200 dark:border-indigo-800">
                  <p className="text-[10px] text-gray-500 dark:text-gray-400">Frequency</p>
                  <p className="text-sm font-semibold text-indigo-700 dark:text-indigo-300">{formData.frequency}</p>
                </div>
              )}
              {formData.custom_contract_value && (
                <div className="p-3 bg-green-50 dark:bg-green-900/20 rounded-lg border border-green-200 dark:border-green-800">
                  <p className="text-[10px] text-gray-500 dark:text-gray-400">Contract Value</p>
                  <p className="text-sm font-semibold text-green-700 dark:text-green-300">{new Intl.NumberFormat('en-US', { style: 'currency', currency: 'SAR' }).format(parseFloat(formData.custom_contract_value) || 0)}</p>
                </div>
              )}
            </div>
          </div>

          {/* Quick Info */}
          <div className="bg-white dark:bg-gray-800 rounded-xl shadow-md p-4 border border-gray-200 dark:border-gray-700">
            <h2 className="text-sm font-semibold text-gray-800 dark:text-white mb-3 pb-2 border-b border-gray-200 dark:border-gray-700 flex items-center gap-2">
              <FaCalendarAlt className="text-orange-500" size={14} />Quick Info
            </h2>
            <div className="space-y-2 text-sm">
              {formData.asset && <div className="flex justify-between"><span className="text-gray-500 dark:text-gray-400">Asset:</span><span className="text-gray-900 dark:text-white font-medium">{formData.asset}</span></div>}
              {formData.vendor && <div className="flex justify-between"><span className="text-gray-500 dark:text-gray-400">Vendor:</span><span className="text-gray-900 dark:text-white font-medium">{formData.vendor}</span></div>}
              {(formData.max_downtime_hrs ?? 0) > 0 && <div className="flex justify-between"><span className="text-gray-500 dark:text-gray-400">Max Downtime:</span><span className="text-gray-900 dark:text-white font-medium">{formData.max_downtime_hrs} hrs</span></div>}
              {(formData.penalty_factor ?? 0) > 0 && <div className="flex justify-between"><span className="text-gray-500 dark:text-gray-400">Penalty Factor:</span><span className="text-gray-900 dark:text-white font-medium">{formData.penalty_factor}%</span></div>}
            </div>
          </div>

          {/* Activity Log */}
          {!isNewPlan && (
            <div className="bg-white dark:bg-gray-800 rounded-xl shadow-md border border-gray-200 dark:border-gray-700 overflow-hidden">
              <div className="flex items-center justify-between p-3 border-b border-gray-200 dark:border-gray-700">
                <div className="flex items-center gap-2 cursor-pointer flex-1" onClick={() => setAuditLogsExpanded(!auditLogsExpanded)}>
                  <FaHistory className="text-blue-500" size={14} />
                  <h2 className="text-sm font-semibold text-gray-800 dark:text-white">Activity Log</h2>
                  {auditLogs.length > 0 && <span className="px-1.5 py-0.5 bg-blue-100 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400 rounded-full text-[10px] font-medium">{auditLogs.length}</span>}
                </div>
                <button onClick={() => setAuditLogsExpanded(!auditLogsExpanded)} className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 p-1">
                  {auditLogsExpanded ? <FaChevronUp size={12} /> : <FaChevronDown size={12} />}
                </button>
              </div>
              {auditLogsExpanded && (
                <div className="p-3">
                  {auditLogsLoading ? (
                    <div className="flex items-center justify-center py-4">
                      <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-blue-500 mr-2"></div>
                      <span className="text-xs text-gray-500">Loading...</span>
                    </div>
                  ) : auditLogs.length === 0 ? (
                    <p className="text-xs text-gray-500 dark:text-gray-400 text-center py-4">No changes recorded yet</p>
                  ) : (
                    <div className="relative">
                      <div className="absolute left-2 top-0 bottom-0 w-0.5 bg-gray-200 dark:bg-gray-700"></div>
                      <div className="space-y-3">
                        {(showAllLogs ? auditLogs : auditLogs.slice(0, 5)).map((log, index) => (
                          <div key={log.name} className="relative pl-6">
                            <div className={`absolute left-1 top-1 w-2.5 h-2.5 rounded-full border-2 border-white dark:border-gray-800 ${index === 0 ? 'bg-blue-500' : 'bg-gray-300 dark:bg-gray-600'}`}></div>
                            <div className={`p-2 rounded-lg ${index === 0 ? 'bg-blue-50 dark:bg-blue-900/20' : 'bg-gray-50 dark:bg-gray-700/50'}`}>
                              <div className="flex items-center justify-between mb-1">
                                <span className="text-[10px] font-medium text-gray-700 dark:text-gray-300">{formatUsername(log.owner)}</span>
                                <div className="flex items-center gap-1 text-[10px] text-gray-500"><FaClock size={8} />{formatAuditDate(log.creation)}</div>
                              </div>
                              {log.changes.length > 0 ? log.changes.map((change, i) => (
                                <div key={i} className="text-[10px]">
                                  <span className="font-medium text-gray-600 dark:text-gray-400">{formatFieldName(change.field)}</span>
                                  <span className="text-gray-500"> changed from </span>
                                  <span className="px-1 py-0.5 bg-red-100 dark:bg-red-900/30 text-red-600 dark:text-red-400 rounded text-[9px]">{formatValue(change.oldValue)}</span>
                                  <span className="text-gray-500"> → </span>
                                  <span className="px-1 py-0.5 bg-green-100 dark:bg-green-900/30 text-green-600 dark:text-green-400 rounded text-[9px]">{formatValue(change.newValue)}</span>
                                </div>
                              )) : <p className="text-[10px] text-gray-500 italic">Document updated</p>}
                            </div>
                          </div>
                        ))}
                      </div>
                      {auditLogs.length > 5 && (
                        <div className="mt-3 text-center">
                          <button onClick={() => setShowAllLogs(!showAllLogs)} className="inline-flex items-center gap-1 px-2 py-1 text-[10px] font-medium text-blue-600 dark:text-blue-400 hover:bg-blue-50 dark:hover:bg-blue-900/20 rounded-md">
                            {showAllLogs ? <><FaChevronUp size={8} />Show Less</> : <><FaChevronDown size={8} />Show All ({auditLogs.length})</>}
                          </button>
                        </div>
                      )}
                      {supportPlan?.creation && supportPlan?.owner && (
                        <div className="relative pl-6 mt-3">
                          <div className="absolute left-1 top-1 w-2.5 h-2.5 rounded-full border-2 border-white dark:border-gray-800 bg-green-500"></div>
                          <div className="p-2 rounded-lg bg-green-50 dark:bg-green-900/20 border border-green-100 dark:border-green-800/50">
                            <div className="flex items-center justify-between mb-1">
                              <span className="text-[10px] font-medium text-gray-700 dark:text-gray-300">{formatUsername(supportPlan.owner)}</span>
                              <div className="flex items-center gap-1 text-[10px] text-gray-500"><FaClock size={8} />{formatAuditDate(supportPlan.creation)}</div>
                            </div>
                            <span className="inline-flex items-center gap-1 px-1.5 py-0.5 bg-green-100 dark:bg-green-800/50 text-green-700 dark:text-green-300 rounded text-[10px] font-medium">
                              <FaCheckCircle size={8} />Created this Support Plan
                            </span>
                          </div>
                        </div>
                      )}
                    </div>
                  )}
                </div>
              )}
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default SupportPlanDetail;