import React, { useState, useEffect, useRef, useCallback } from 'react';
import { useParams, useNavigate, useSearchParams } from 'react-router-dom';
import { useItemDetails, useItemMutations } from '../hooks/useItem';
import { FaArrowLeft, FaSave, FaEdit, FaCheck, FaTrashAlt, FaSync } from 'react-icons/fa';
import type { CreateItemData } from '../services/itemService';
import LinkField from '../components/LinkField';
import API_CONFIG from '../config/api';
import useDefaultHospital from '../hooks/useDefaultHospital';
import CommentSection from '../components/CommentSection';
import ActivityLog from '../components/ActivityLog';

const ItemDetail: React.FC = () => {
  const { itemName } = useParams<{ itemName: string }>();
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const duplicateFromItem = searchParams.get('duplicate');
  
  const isNewItem = itemName === 'new';
  const isDuplicating = isNewItem && !!duplicateFromItem;
  
  // Balance Qty state (fetched from Bin doctype)
  const [balanceQty, setBalanceQty] = useState<number>(0);
  const [balanceQtyLoading, setBalanceQtyLoading] = useState<boolean>(false);

  // Form data state
  const [formData, setFormData] = useState<CreateItemData>({
    item_code: '',
    item_name: '',
    item_group: '',
    custom_hospital_name: '',
    custom_part_description: '',
    stock_uom: 'Nos',
    custom_item_cost_per_unit: 0,
    disabled: 0,
    is_stock_item: 1,
    opening_stock: 0,
    valuation_rate: 0,
    standard_rate: 0,
    custom_last_calibration_date: '',
    custom_next_due_calibration_date: '',
    description: '',
    brand: '',
    custom_warranty_in_months: '',
    valuation_method: '',
    has_batch_no: 0,
    has_serial_no: 0,
    is_purchase_item: 1,
    is_sales_item: 1,
    country_of_origin: 'Saudi Arabia',
  });

  const { item, loading, error, refetch: refetchItem } = useItemDetails(
    isDuplicating ? duplicateFromItem : (isNewItem ? null : itemName || null)
  );
  const { createItem, updateItem, submitItem, loading: saving } = useItemMutations();

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

  useDefaultHospital(setFormData, {
    enabled: isNewItem && !isDuplicating,
    fields: ['custom_hospital_name'],
  });

  // Check document status
  const docstatus = item?.docstatus ?? 0;
  const isSubmitted = docstatus === 1;
  const isCancelled = docstatus === 2;
  const isDraft = docstatus === 0;

  // Check if Calibration Information should be shown
  const showCalibrationInfo = formData.item_group === 'Tools';

  // Fetch Balance Qty from Bin doctype
  const fetchBalanceQty = useCallback(async (itemCode: string) => {
    if (!itemCode) return;
    
    setBalanceQtyLoading(true);
    try {
      // Get CSRF token
      let csrfToken: string | null = null;
      if (typeof window !== 'undefined' && (window as any).csrf_token) {
        csrfToken = (window as any).csrf_token;
      }
      
      // Build filters and fields for Frappe API
      const filters = JSON.stringify([['item_code', '=', itemCode]]);
      const fields = JSON.stringify(['actual_qty', 'warehouse']);
      
      const url = `${API_CONFIG.BASE_URL}/api/resource/Bin?filters=${encodeURIComponent(filters)}&fields=${encodeURIComponent(fields)}&limit_page_length=0`;
      
      const headers: Record<string, string> = {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      };
      
      if (csrfToken) {
        headers['X-Frappe-CSRF-Token'] = csrfToken;
      }
      
      const response = await fetch(url, {
        method: 'GET',
        headers,
        credentials: 'include', // Include cookies for session auth
      });
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      
      const result = await response.json();
      
      // Sum up actual_qty from all warehouses
      const totalQty = result.data?.reduce((sum: number, bin: any) => {
        return sum + (bin.actual_qty || 0);
      }, 0) || 0;
      
      setBalanceQty(totalQty);
    } catch (err) {
      console.error('Failed to fetch balance qty:', err);
      setBalanceQty(0);
    } finally {
      setBalanceQtyLoading(false);
    }
  }, []);

  // Fetch balance qty when item is loaded (for existing items)
  useEffect(() => {
    if (!isNewItem && item?.item_code) {
      fetchBalanceQty(item.item_code);
    }
  }, [isNewItem, item?.item_code, fetchBalanceQty]);

  // Load item data when item is fetched
  useEffect(() => {
    if (item && !isDuplicating) {
      setFormData({
        item_code: item.item_code || '',
        item_name: item.item_name || '',
        item_group: item.item_group || '',
        custom_hospital_name: item.custom_hospital_name || '',
        custom_part_description: item.custom_part_description || '',
        stock_uom: item.stock_uom || 'Nos',
        custom_item_cost_per_unit: item.custom_item_cost_per_unit || 0,
        disabled: item.disabled || 0,
        is_stock_item: item.is_stock_item ?? 1,
        opening_stock: item.opening_stock || 0,
        valuation_rate: item.valuation_rate || 0,
        standard_rate: item.standard_rate || 0,
        custom_last_calibration_date: item.custom_last_calibration_date || '',
        custom_next_due_calibration_date: item.custom_next_due_calibration_date || '',
        description: item.description || '',
        brand: item.brand || '',
        custom_warranty_in_months: item.custom_warranty_in_months || '',
        valuation_method: item.valuation_method || '',
        has_batch_no: item.has_batch_no || 0,
        has_serial_no: item.has_serial_no || 0,
        is_purchase_item: item.is_purchase_item ?? 1,
        is_sales_item: item.is_sales_item ?? 1,
        country_of_origin: item.country_of_origin || 'Saudi Arabia',
        uoms: item.uoms || [],
        item_defaults: item.item_defaults || [],
      });
      setIsEditing(false);
    } else if (isDuplicating && item) {
      // When duplicating, copy data but clear name/code
      setFormData({
        item_code: '',
        item_name: item.item_name || '',
        item_group: item.item_group || '',
        custom_hospital_name: item.custom_hospital_name || '',
        custom_part_description: item.custom_part_description || '',
        stock_uom: item.stock_uom || 'Nos',
        custom_item_cost_per_unit: item.custom_item_cost_per_unit || 0,
        disabled: 0,
        is_stock_item: item.is_stock_item ?? 1,
        opening_stock: item.opening_stock || 0,
        valuation_rate: item.valuation_rate || 0,
        standard_rate: item.standard_rate || 0,
        custom_last_calibration_date: item.custom_last_calibration_date || '',
        custom_next_due_calibration_date: item.custom_next_due_calibration_date || '',
        description: item.description || '',
        brand: item.brand || '',
        custom_warranty_in_months: item.custom_warranty_in_months || '',
        valuation_method: item.valuation_method || '',
        has_batch_no: item.has_batch_no || 0,
        has_serial_no: item.has_serial_no || 0,
        is_purchase_item: item.is_purchase_item ?? 1,
        is_sales_item: item.is_sales_item ?? 1,
        country_of_origin: item.country_of_origin || 'Saudi Arabia',
        uoms: item.uoms || [],
        item_defaults: item.item_defaults || [],
      });
    }
  }, [item, isDuplicating]);

  const handleSave = async () => {
    try {
      if (isNewItem) {
        const newItem = await createItem(formData);
        navigate(`/inventory/${newItem.name}`);
      } else {
        await updateItem(itemName!, formData);
        await refetchItem();
        // Refresh balance qty after update
        if (formData.item_code) {
          fetchBalanceQty(formData.item_code);
        }
        setIsEditing(false);
        alert('Item updated successfully!');
      }
    } catch (err) {
      alert(`Failed to save: ${err instanceof Error ? err.message : 'Unknown error'}`);
    }
  };

  const handleSubmit = async () => {
    if (!itemName || isNewItem) {
      alert('Please save the item first before submitting.');
      return;
    }
    try {
      await submitItem(itemName);
      await refetchItem();
      setIsEditing(false);
      alert('Item submitted successfully!');
    } catch (err) {
      alert(`Failed to submit: ${err instanceof Error ? err.message : 'Unknown error'}`);
    }
  };

  const isFieldDisabled = useCallback((fieldname: string): boolean => {
    if (!isEditing) return true;
    if (isCancelled) return true;
    if (isSubmitted) {
      // For submitted items, most fields are read-only
      // Only allow editing certain fields if needed
      return true;
    }
    return false;
  }, [isEditing, isCancelled, isSubmitted]);

  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 item...</p>
        </div>
      </div>
    );
  }

  if (error && !isNewItem) {
    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-6">
          <h2 className="text-xl font-bold text-red-800 dark:text-red-300 mb-4">Error Loading Item</h2>
          <p className="text-red-700 dark:text-red-400 mb-4">{error}</p>
          <button
            onClick={() => navigate('/inventory')}
            className="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded"
          >
            Back to Inventory
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="p-4 sm:p-6 bg-gray-50 dark:bg-gray-900 min-h-screen 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('/inventory')}
            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-3xl font-bold text-gray-800 dark:text-white">
              {isNewItem ? 'New Item' : item?.item_name || item?.item_code || 'Item'}
            </h1>
            <p className="text-gray-600 dark:text-gray-400 mt-1">
              {isNewItem ? 'Create a new item' : `Item Code: ${item?.item_code || itemName}`}
            </p>
          </div>
        </div>
        <div className="flex gap-3">
          {!isNewItem && !isEditing && isDraft && (
            <button
              onClick={() => setIsEditing(true)}
              className="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg flex items-center gap-2"
            >
              <FaEdit />
              Edit
            </button>
          )}
          {isEditing && (
            <>
              <button
                onClick={() => {
                  if (isNewItem) {
                    navigate('/inventory');
                  } else {
                    setIsEditing(false);
                    refetchItem();
                  }
                }}
                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>
              {/* {!isNewItem && isDraft && (
                <button
                  onClick={handleSubmit}
                  disabled={saving}
                  className="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg flex items-center gap-2 disabled:opacity-50"
                >
                  <FaCheck />
                  Submit
                </button>
              )} */}
            </>
          )}
        </div>
      </div>

      {/* Form */}
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
          {/* Basic Information */}
          <div className="md:col-span-2">
            <h2 className="text-xl font-semibold text-gray-800 dark:text-white mb-4">Basic Information</h2>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              Item Code <span className="text-red-500">*</span>
            </label>
            <input
              type="text"
              value={formData.item_code}
              onChange={(e) => setFormData({ ...formData, item_code: e.target.value })}
              disabled={isFieldDisabled('item_code') || !isNewItem}
              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"
              required
            />
          </div>

          {/* <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              Item Name <span className="text-red-500">*</span>
            </label>
            <input
              type="text"
              value={formData.item_name}
              onChange={(e) => setFormData({ ...formData, item_name: e.target.value })}
              disabled={isFieldDisabled('item_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"
              required
            />
          </div> */}

          <div>
            {/* <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              Hospital Name <span className="text-red-500">*</span>
            </label> */}
            <LinkField
              label="Hospital"
              doctype="Company"
              value={formData.custom_hospital_name || ''}
              onChange={(value) => setFormData({ ...formData, custom_hospital_name: value })}
              disabled={isFieldDisabled('custom_hospital_name')}
              placeholder="Select Hospital"
              filters={{ domain: 'Healthcare' }}/>
          </div>


          <div>
            {/* <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              Item Group
            </label> */}
            <LinkField
              label="Item Group"
              doctype="Item Group"
              value={formData.item_group || ''}
              onChange={(value) => setFormData({ ...formData, item_group: value })}
              disabled={isFieldDisabled('item_group')}
              placeholder="Select item group"
              />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              Stock UOM
            </label>
            <input
              type="text"
              value={formData.stock_uom}
              onChange={(e) => setFormData({ ...formData, stock_uom: e.target.value })}
              disabled={isFieldDisabled('stock_uom')}
              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"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              Part Description
            </label>
            <input
              type="text"
              value={formData.custom_part_description}
              onChange={(e) => setFormData({ ...formData, custom_part_description: e.target.value })}
              disabled={isFieldDisabled('custom_part_description')}
              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"
            />
          </div>

          {/* <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              Brand
            </label>
            <input
              type="text"
              value={formData.brand}
              onChange={(e) => setFormData({ ...formData, brand: e.target.value })}
              disabled={isFieldDisabled('brand')}
              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"
            />
          </div> */}

          {/* Stock Information */}
          <div className="md:col-span-2 mt-6">
            <h2 className="text-xl font-semibold text-gray-800 dark:text-white mb-4">Stock Information</h2>
          </div>

          <div className="md:col-span-2">
            <div className="grid grid-cols-1 md:grid-cols-3 gap-6 items-end">
              {/* Is Stock Item */}
              <div className="flex items-center gap-2 h-[42px]">
                <input
                  type="checkbox"
                  id="is_stock_item"
                  checked={formData.is_stock_item === 1}
                  onChange={(e) => setFormData({ ...formData, is_stock_item: e.target.checked ? 1 : 0 })}
                  disabled={isFieldDisabled('is_stock_item')}
                  className="w-4 h-4"
                />
                <label htmlFor="is_stock_item" className="text-sm font-medium text-gray-700 dark:text-gray-300">
                  Is Stock Item
                </label>
              </div>

              {/* Opening Stock - Only show for NEW items when is_stock_item is checked */}
              {isNewItem && formData.is_stock_item === 1 && (
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    Opening Stock
                  </label>
                  <input
                    type="number"
                    value={formData.opening_stock}
                    onChange={(e) => setFormData({ ...formData, opening_stock: parseFloat(e.target.value) || 0 })}
                    disabled={isFieldDisabled('opening_stock')}
                    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"
                  />
                </div>
              )}

              {/* Valuation Rate - Only show for NEW items when is_stock_item is checked */}
              {isNewItem && formData.is_stock_item === 1 && (
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    Valuation Rate
                  </label>
                  <input
                    type="number"
                    step="0.01"
                    value={formData.valuation_rate}
                    onChange={(e) => setFormData({ ...formData, valuation_rate: parseFloat(e.target.value) || 0 })}
                    disabled={isFieldDisabled('valuation_rate')}
                    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"
                  />
                </div>
              )}

              {/* Balance Qty - Only show for EXISTING items when is_stock_item is checked */}
              {!isNewItem && formData.is_stock_item === 1 && (
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    Balance Qty
                  </label>
                  <div className="flex items-center gap-2">
                    <input
                      type="number"
                      value={balanceQty}
                      readOnly
                      className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-gray-100 dark:bg-gray-800 text-gray-900 dark:text-white cursor-not-allowed"
                    />
                    <button
                      type="button"
                      onClick={() => formData.item_code && fetchBalanceQty(formData.item_code)}
                      disabled={balanceQtyLoading}
                      className="p-2 text-blue-600 hover:text-blue-700 dark:text-blue-400 dark:hover:text-blue-300 disabled:opacity-50"
                      title="Refresh Balance Qty"
                    >
                      <FaSync className={balanceQtyLoading ? 'animate-spin' : ''} />
                    </button>
                  </div>
                </div>
              )}
            </div>
          </div>

          {/* <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              Standard Rate
            </label>
            <input
              type="number"
              step="0.01"
              value={formData.standard_rate}
              onChange={(e) => setFormData({ ...formData, standard_rate: parseFloat(e.target.value) || 0 })}
              disabled={isFieldDisabled('standard_rate')}
              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"
            />
          </div> */}

          {/* Calibration Information - Only show when Item Group is "Tools" */}
          {showCalibrationInfo && (
            <>
              <div className="md:col-span-2 mt-6">
                <h2 className="text-xl font-semibold text-gray-800 dark:text-white mb-4">Calibration Information</h2>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Last Calibration Date
                </label>
                <input
                  type="date"
                  value={formData.custom_last_calibration_date}
                  onChange={(e) => setFormData({ ...formData, custom_last_calibration_date: e.target.value })}
                  disabled={isFieldDisabled('custom_last_calibration_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"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Next Due Calibration Date
                </label>
                <input
                  type="date"
                  value={formData.custom_next_due_calibration_date}
                  onChange={(e) => setFormData({ ...formData, custom_next_due_calibration_date: e.target.value })}
                  disabled={isFieldDisabled('custom_next_due_calibration_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"
                />
              </div>
            </>
          )}

          {/* Additional Information */}
          <div className="md:col-span-2 mt-6">
            <h2 className="text-xl font-semibold text-gray-800 dark:text-white mb-4">Additional Information</h2>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              Description
            </label>
            <textarea
              value={formData.description}
              onChange={(e) => setFormData({ ...formData, description: e.target.value })}
              disabled={isFieldDisabled('description')}
              rows={3}
              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"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              Warranty (Months)
            </label>
            <input
              type="text"
              value={formData.custom_warranty_in_months}
              onChange={(e) => setFormData({ ...formData, custom_warranty_in_months: e.target.value })}
              disabled={isFieldDisabled('custom_warranty_in_months')}
              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"
            />
          </div>

          {/* <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              Country of Origin
            </label>
            <input
              type="text"
              value={formData.country_of_origin}
              onChange={(e) => setFormData({ ...formData, country_of_origin: e.target.value })}
              disabled={isFieldDisabled('country_of_origin')}
              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"
            />
          </div> */}

          {/* <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              Is Purchase Item
            </label>
            <input
              type="checkbox"
              checked={formData.is_purchase_item === 1}
              onChange={(e) => setFormData({ ...formData, is_purchase_item: e.target.checked ? 1 : 0 })}
              disabled={isFieldDisabled('is_purchase_item')}
              className="w-4 h-4"
            />
          </div> */}

          {/* <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              Is Sales Item
            </label>
            <input
              type="checkbox"
              checked={formData.is_sales_item === 1}
              onChange={(e) => setFormData({ ...formData, is_sales_item: e.target.checked ? 1 : 0 })}
              disabled={isFieldDisabled('is_sales_item')}
              className="w-4 h-4"
            />
          </div> */}

          {/* <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              Has Batch No
            </label>
            <input
              type="checkbox"
              checked={formData.has_batch_no === 1}
              onChange={(e) => setFormData({ ...formData, has_batch_no: e.target.checked ? 1 : 0 })}
              disabled={isFieldDisabled('has_batch_no')}
              className="w-4 h-4"
            />
          </div> */}

          {/* <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              Has Serial No
            </label>
            <input
              type="checkbox"
              checked={formData.has_serial_no === 1}
              onChange={(e) => setFormData({ ...formData, has_serial_no: e.target.checked ? 1 : 0 })}
              disabled={isFieldDisabled('has_serial_no')}
              className="w-4 h-4"
            />
          </div> */}

          {/* <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              Disabled
            </label>
            <input
              type="checkbox"
              checked={formData.disabled === 1}
              onChange={(e) => setFormData({ ...formData, disabled: e.target.checked ? 1 : 0 })}
              disabled={isFieldDisabled('disabled')}
              className="w-4 h-4"
            />
          </div> */}
        </div>
      </div>

      {!isNewItem && !isDuplicating && (
        <div className="mt-6 space-y-6">
          <CommentSection
            referenceDoctype="Item"
            referenceName={itemName || null}
            title="Comments & Discussion"
            pollInterval={30000}
            initialLimit={5}
          />
          <ActivityLog
            doctype="Item"
            docname={itemName || null}
            creationDate={item?.creation}
            createdBy={item?.owner}
            initialVisible={5}
            startCollapsed={true}
          />
        </div>
      )}
    </div>
  );
};

export default ItemDetail;