// 5. Replace your existing _buildDataTable method with this grouped version
Widget _buildDataTable(BuildContext context) {
  if (filteredData.isEmpty) {
    return const SizedBox(
      height: 50,
      child: Center(child: Text('No available data')),
    );
  }

  final isDesktop = !ResponsiveLayout.isMobile(context);
  final groupedData = _groupedEnquiries;

  return LayoutBuilder(
    builder: (context, constraints) {
      double minWidth = constraints.maxWidth < 1300 ? 1300 : constraints.maxWidth;

      return ScrollConfiguration(
        behavior: const MaterialScrollBehavior().copyWith(
          dragDevices: {PointerDeviceKind.mouse, PointerDeviceKind.touch},
        ),
        child: SingleChildScrollView(
          scrollDirection: Axis.horizontal,
          child: SingleChildScrollView(
            scrollDirection: Axis.vertical,
            child: ConstrainedBox(
              constraints: BoxConstraints(minWidth: minWidth),
              child: Column(
                children: [
                  // Table Header (sticky)
                  Container(
                    color: Color(0xFFEDF6F5),
                    child: _buildTableHeader(isDesktop),
                  ),

                  // Grouped Rows
                  ...groupedData.entries.map((entry) {
                    final status = entry.key;
                    final items = entry.value;
                    final isExpanded = groupExpanded[status] ?? true;

                    return Column(
                      children: [
                        // Group Header
                        _buildGroupHeader(status, items.length),

                        // Group Rows (if expanded)
                        if (isExpanded)
                          ...items.isEmpty
                              ? [
                                  Padding(
                                    padding: EdgeInsets.all(20),
                                    child: Text(
                                      'No records found',
                                      style: GoogleFonts.inter(
                                        fontSize: 12,
                                        color: Colors.grey,
                                        fontStyle: FontStyle.italic,
                                      ),
                                    ),
                                  ),
                                ]
                              : items.asMap().entries.map((itemEntry) {
                                  final index = itemEntry.key;
                                  final item = itemEntry.value;
                                  final startIndex = (currentPage - 1) * itemsPerPage;
                                  final sno = startIndex + index + 1;

                                  return _buildGroupedDataRow(
                                    item,
                                    sno,
                                    isDesktop,
                                  );
                                }).toList(),
                      ],
                    );
                  }).toList(),
                ],
              ),
            ),
          ),
        ),
      );
    },
  );
}

// 6. Build table header
Widget _buildTableHeader(bool isDesktop) {
  return Padding(
    padding: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
    child: Row(
      children: [
        _buildHeaderCell('Received Date', 120),
        _buildHeaderCell('Partner *', 110),
        _buildHeaderCell('Assigned To *', 110),
        _buildHeaderCell('Broker *', 100),
        _buildHeaderCell('Insurer *', 110),
        _buildHeaderCell('Insured Name *', 120),
        _buildHeaderCell('Vehicle No *', 120),
        _buildHeaderCell('Vehicle Type *', 110),
        _buildHeaderCell('Email', 150),
        _buildHeaderCell('Mobile', 100),
        _buildHeaderCell('Documents', 100),
        _buildHeaderCell('Remarks', 120),
        if (roleId != 'staff') _buildHeaderCell('Action', 100),
        _buildHeaderCell('Assigned Date', 120),
        _buildHeaderCell('Premium', 100),
        _buildHeaderCell('Payment Mode', 100),
        _buildHeaderCell('Policy Number', 120),
        _buildHeaderCell('Status', 100),
      ],
    ),
  );
}

Widget _buildHeaderCell(String label, double width) {
  return Container(
    width: width,
    padding: EdgeInsets.symmetric(horizontal: 4),
    child: Text(
      label,
      style: GoogleFonts.inter(
        fontSize: 12,
        fontWeight: FontWeight.w600,
        color: Colors.black87,
      ),
    ),
  );
}

// 7. Build grouped data row (container-based instead of DataTable)
Widget _buildGroupedDataRow(
  Map<String, dynamic> item,
  int sno,
  bool isDesktop,
) {
  final id = int.tryParse(item['id'].toString()) ?? 0;
  final selectId = item['id'].toString() ?? '0';
  final editing = isEditingRow[id] ?? false;

  final bool isNewRow =
      int.tryParse(id.toString()) != null &&
      int.parse(id.toString()) > 1000000000000;

  return Container(
    decoration: BoxDecoration(
      color: editing ? Color(0xFFf8f9fa) : Colors.white,
      border: Border(
        bottom: BorderSide(color: Colors.grey.shade200, width: 0.5),
      ),
    ),
    child: InkWell(
      onTap: () {
        // Optional: handle row tap
      },
      child: Padding(
        padding: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
        child: Row(
          children: [
            // Received Date
            _buildDataCell(
              formatDateTimeForTable(item['created_on'], newLine: true),
              120,
            ),

            // Partner
            _buildDataCell(
              editing ? null : item['agent_name'] ?? '-',
              110,
              widget: editing ? buildAgentName(context, fromHeader: false) : null,
            ),

            // Assigned To
            _buildDataCell(
              editing ? null : item['assigned_to_name'] ?? '-',
              110,
              widget: editing ? buildSelectStaffMem(context) : null,
              subtitle: editing ? null : item['agent_code'],
            ),

            // Broker
            _buildDataCell(
              editing ? null : item['broker_name'] ?? '-',
              100,
              widget: editing ? buildBroker(context) : null,
            ),

            // Insurer
            _buildDataCell(
              editing ? null : item['insurer_short_name'] ?? '-',
              110,
              widget: editing ? buildInsurer(context, fromHeader: false) : null,
            ),

            // Insured Name
            _buildDataCell(
              editing ? null : item['insured_name'] ?? '-',
              120,
              widget: editing ? buildInsuredName(context, fromHeader: false) : null,
            ),

            // Vehicle No
            _buildDataCell(
              editing ? null : item['reg_no'] ?? '-',
              120,
              widget: editing ? buildVehicleNumber(context) : null,
            ),

            // Vehicle Type
            _buildDataCell(
              editing ? null : _wrapText(item['vehicle_type'] ?? '-', 13),
              110,
              widget: editing ? buildVehicleType(context) : null,
            ),

            // Email
            _buildDataCell(
              editing ? null : item['email'] ?? '-',
              150,
              widget: editing ? buildEmail(context) : null,
            ),

            // Mobile
            _buildDataCell(
              editing ? null : item['mobile'] ?? '-',
              100,
              widget: editing ? buildPhNumber(context) : null,
            ),

            // Documents
            _buildDocumentCell(selectId, editing, 100),

            // Remarks
            _buildDataCell(
              editing ? null : _truncateText(item['remarks'] ?? '-', 10),
              120,
              widget: editing ? buildRemarks(context) : null,
              tooltip: item['remarks'],
            ),

            // Action (if not staff)
            if (roleId != 'staff')
              _buildActionCell(item, id, editing, isNewRow, 100),

            // Assigned Date
            _buildDataCell(
              formatDateTimeForTable(item['updated_on'], newLine: true),
              120,
            ),

            // Premium
            _buildPremiumCell(item, 100),

            // Payment Mode
            _buildDataCell(item['payment_mode'] ?? '-', 100),

            // Policy Number
            _buildDataCell(item['policy_number'] ?? '-', 120),

            // Status
            _buildStatusCell(item, 100),
          ],
        ),
      ),
    ),
  );
}

// 8. Helper widget builders
Widget _buildDataCell(
  String? text,
  double width, {
  Widget? widget,
  String? subtitle,
  String? tooltip,
}) {
  if (widget != null) {
    return Container(
      width: width,
      padding: EdgeInsets.symmetric(horizontal: 4),
      child: widget,
    );
  }

  Widget child = Column(
    crossAxisAlignment: CrossAxisAlignment.start,
    mainAxisAlignment: MainAxisAlignment.center,
    children: [
      Text(
        text ?? '-',
        style: GoogleFonts.inter(
          fontSize: 12,
          fontWeight: FontWeight.w500,
        ),
        maxLines: 3,
        overflow: TextOverflow.ellipsis,
      ),
      if (subtitle != null)
        Text(
          subtitle,
          style: GoogleFonts.inter(
            fontSize: 10,
            fontWeight: FontWeight.w400,
            color: Colors.grey,
          ),
        ),
    ],
  );

  if (tooltip != null && tooltip.isNotEmpty) {
    child = Tooltip(
      message: tooltip,
      waitDuration: Duration(milliseconds: 400),
      child: child,
    );
  }

  return Container(
    width: width,
    padding: EdgeInsets.symmetric(horizontal: 4),
    child: child,
  );
}

Widget _buildDocumentCell(String selectId, bool editing, double width) {
  return Container(
    width: width,
    padding: EdgeInsets.symmetric(horizontal: 4),
    child: Material(
      color: Colors.transparent,
      child: InkWell(
        onTap: () async {
          final RenderBox button = context.findRenderObject() as RenderBox;
          final RenderBox overlay = Overlay.of(context).context.findRenderObject() as RenderBox;
          final Offset position = button.localToGlobal(Offset.zero, ancestor: overlay);

          await showMenu(
            context: context,
            position: RelativeRect.fromLTRB(
              position.dx,
              position.dy + button.size.height,
              overlay.size.width,
              0,
            ),
            items: [
              PopupMenuItem(
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: _buildPopupDownload(context, selectId, editing),
                ),
              ),
            ],
            color: Colors.white,
          );
        },
        child: Tooltip(
          message: editing ? 'Click To Upload Documents' : 'Click To View Documents',
          child: Icon(
            editing ? Icons.upload_file : Icons.download_for_offline,
            color: editing ? Colors.blue : Colors.green,
            size: 20,
          ),
        ),
      ),
    ),
  );
}

Widget _buildActionCell(
  Map<String, dynamic> item,
  int id,
  bool editing,
  bool isNewRow,
  double width,
) {
  return Container(
    width: width,
    padding: EdgeInsets.symmetric(horizontal: 4),
    child: Row(
      children: [
        if (editing) ...[
          IconButton(
            icon: Icon(Icons.check, color: Colors.green, size: 18),
            tooltip: "Save",
            onPressed: () => handleSave(id),
            padding: EdgeInsets.zero,
            constraints: BoxConstraints(),
          ),
          SizedBox(width: 4),
          IconButton(
            icon: Icon(
              isNewRow ? Icons.close : Icons.edit_off_sharp,
              color: isNewRow ? Colors.red : Colors.blue,
              size: 18,
            ),
            tooltip: isNewRow ? "Delete" : "Cancel Edit Mode",
            onPressed: () => handleCancel(id),
            padding: EdgeInsets.zero,
            constraints: BoxConstraints(),
          ),
        ] else ...[
          IconButton(
            icon: Icon(Icons.edit, color: Colors.blue, size: 18),
            tooltip: "Edit",
            onPressed: () => handleEdit(item),
            padding: EdgeInsets.zero,
            constraints: BoxConstraints(),
          ),
        ],
      ],
    ),
  );
}

Widget _buildPremiumCell(Map<String, dynamic> item, double width) {
  final showApproval = item['status'] == 'Proposal Created' ||
                        item['status'] == 'Proposal Rejected';

  return Container(
    width: width,
    padding: EdgeInsets.symmetric(horizontal: 4),
    child: showApproval
        ? InkWell(
            onTap: () => handleProposalAccept(context, item['id']),
            child: Text(
              'Click To\nApprove',
              style: GoogleFonts.inter(
                color: Colors.green,
                fontSize: 11,
                fontWeight: FontWeight.w700,
              ),
            ),
          )
        : Text(
            item['premium_amount']?.toString() ?? '-',
            style: GoogleFonts.inter(fontSize: 12, fontWeight: FontWeight.w500),
          ),
  );
}

Widget _buildStatusCell(Map<String, dynamic> item, double width) {
  return Container(
    width: width,
    padding: EdgeInsets.symmetric(horizontal: 4),
    child: Material(
      color: Colors.transparent,
      child: InkWell(
        onTap: () async {
          var status = item['status'];
          var enqId = item['id'];

          final prefs = await SharedPreferences.getInstance();
          await prefs.remove('enqStaffDataId');
          await prefs.setString('enqStaffDataId', enqId.toString());
          ref.read(quotationStaffIdProvider.notifier).state = enqId;
          buildStatusActions(context, status, enqId);
        },
        child: Tooltip(
          message: 'Click to View or Process Enquiry',
          waitDuration: Duration(milliseconds: 500),
          child: Text(
            item['status'] ?? '-',
            style: GoogleFonts.inter(
              fontSize: 12,
              fontWeight: FontWeight.w500,
            ),
            overflow: TextOverflow.ellipsis,
          ),
        ),
      ),
    ),
  );
}