// lib/screens/marine/manual/marine_manual_report_status_log.dart

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';
import 'dart:convert'; // Added for jsonDecode

// Core Providers and Services
import 'package:environment_monitoring_app/auth_provider.dart';
import 'package:environment_monitoring_app/services/local_storage_service.dart';

// Data Models for Reconstruction
import 'package:environment_monitoring_app/models/marine_manual_npe_report_data.dart';
import 'package:environment_monitoring_app/models/marine_manual_pre_departure_checklist_data.dart';
import 'package:environment_monitoring_app/models/marine_manual_sonde_calibration_data.dart';
import 'package:environment_monitoring_app/models/marine_manual_equipment_maintenance_data.dart';

// Services for Resubmission
import 'package:environment_monitoring_app/services/marine_npe_report_service.dart';
import 'package:environment_monitoring_app/services/marine_manual_pre_departure_service.dart';
import 'package:environment_monitoring_app/services/marine_manual_sonde_calibration_service.dart';
import 'package:environment_monitoring_app/services/marine_manual_equipment_maintenance_service.dart';

// --- START: ADDED HELPER CLASS ---
/// A simple class to hold an image file and its associated remark.
class ImageLogEntry {
  final File file;
  final String? remark;
  ImageLogEntry({required this.file, this.remark});
}
// --- END: ADDED HELPER CLASS ---

/// A generic data holder for any log entry, identical to the one in the data status log.
class SubmissionLogEntry {
  final String type;
  final String title;
  final String stationCode;
  final String senderName;
  final DateTime submissionDateTime;
  final String? reportId;
  final String status;
  final String message;
  final Map<String, dynamic> rawData;
  final String serverName;
  final String? apiStatusRaw;
  final String? ftpStatusRaw;
  bool isResubmitting;

  SubmissionLogEntry({
    required this.type,
    required this.title,
    required this.stationCode,
    required this.senderName,
    required this.submissionDateTime,
    this.reportId,
    required this.status,
    required this.message,
    required this.rawData,
    required this.serverName,
    this.apiStatusRaw,
    this.ftpStatusRaw,
    this.isResubmitting = false,
  });
}

class MarineManualReportStatusLog extends StatefulWidget {
  const MarineManualReportStatusLog({super.key});

  @override
  State<MarineManualReportStatusLog> createState() =>
      _MarineManualReportStatusLogState();
}

class _MarineManualReportStatusLogState
    extends State<MarineManualReportStatusLog> {
  // Services for loading and resubmitting
  late LocalStorageService _localStorageService;
  late MarineNpeReportService _npeReportService;
  late MarineManualPreDepartureService _preDepartureService;
  late MarineManualSondeCalibrationService _sondeCalibrationService;
  late MarineManualEquipmentMaintenanceService _equipmentMaintenanceService;

  // State variables for logs, categorized as requested
  List<SubmissionLogEntry> _preSamplingLogs = [];
  List<SubmissionLogEntry> _reportLogs = [];
  List<SubmissionLogEntry> _filteredPreSamplingLogs = [];
  List<SubmissionLogEntry> _filteredReportLogs = [];

  final TextEditingController _preSamplingSearchController =
  TextEditingController();
  final TextEditingController _reportSearchController = TextEditingController();

  bool _isLoading = true;
  final Map<String, bool> _isResubmitting = {};

  // --- START: COPIED FROM SCREEN FILE ---
  // This is the "single source of truth" for categories
  final Map<String, List<String>> _checklistSections = {
    'INTERNAL - IN-SITU SAMPLING': [
      // Section title matches PDF
      'Marine manual Standard Operation Procedure (SOP)', // Item text matches PDF
      'Back-up Sampling Sheet & Chain of Custody form', // Item text matches PDF
      'Calibration worksheet', // Item text matches PDF
      'YSI EXO 2 Sonde include sensor (pH/Turbidity/Conductivity/Dissolved Oxygen)', // Item text matches PDF
      'Spare set sensor (pH/Turbidity/Conductivity/Dissolved Oxygen)', // Item text matches PDF
      'YSI serial cable', // Item text matches PDF
      'Van Dorn Sampler (with rope & messenger)', // Item text matches PDF
      'Laptop', // Item text matches PDF
      'Smartphone pre-installed with application (Apps for manual sampling-MMS)', // Item text matches PDF
      'GPS navigation', // Item text matches PDF
      'Calibration standards (pH/Turbidity/Conductivity)', // Item text matches PDF
      'Distilled water (D.I.)', // Item text matches PDF
      'Universal pH indicator paper', // Item text matches PDF
      'Alcohol swab', // Item text matches PDF
      'Personal Floating Devices (PFD)', // Item text matches PDF
      'First aid kits', // Item text matches PDF
      'Disposable gloves', // Item text matches PDF
      'Black plastic bags', // Item text matches PDF
      'Marker pen, pen, clear tapes, brown tapes & scissors', // Item text matches PDF
      'Energizer battery', // Item text matches PDF
      'EXO battery opener and EXO magnet', // Item text matches PDF
      'Laminated white paper', // Item text matches PDF
      'Clear glass bottle (blue сар)', // Item text matches PDF
      'Proper sampling attires & shoes', // Item text matches PDF
      'Raincoat/Poncho', // Item text matches PDF
      'Ice packets', // Item text matches PDF
    ],
    'INTERNAL-TARBALL SAMPLING': [
      // Section title matches PDF
      'Measuring tape (100 meter)', // Item text matches PDF
      'Steel raking', // Item text matches PDF
      'Aluminum foil', // Item text matches PDF
      'Zipper bags', // Item text matches PDF
    ],
    'EXTERNAL - LABORATORY': [
      // Section title matches PDF
      'Sufficient sets of cooler box and sampling bottles with label', // Item text matches PDF
      'Field duplicate sampling bottles (if any)', // Item text matches PDF
      'Blank samples sampling bottles (if any)', // Item text matches PDF
      'Preservatives (acid & alkaline)', // Item text matches PDF
    ],
  };
  // --- END: COPIED FROM SCREEN FILE ---

  @override
  void initState() {
    super.initState();
    // Controllers and initial load
    _preSamplingSearchController.addListener(_filterLogs);
    _reportSearchController.addListener(_filterLogs);
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    // Initialize all required services from Provider
    _localStorageService =
        Provider.of<LocalStorageService>(context, listen: false);
    _npeReportService =
        Provider.of<MarineNpeReportService>(context, listen: false);
    _preDepartureService = Provider.of<MarineManualPreDepartureService>(context,
        listen: false);
    _sondeCalibrationService = Provider.of<MarineManualSondeCalibrationService>(
        context,
        listen: false);
    _equipmentMaintenanceService =
        Provider.of<MarineManualEquipmentMaintenanceService>(context,
            listen: false);

    // Load logs after services are initialized
    if (_isLoading) {
      _loadAllLogs();
    }
  }

  @override
  void dispose() {
    _preSamplingSearchController.dispose();
    _reportSearchController.dispose();
    super.dispose();
  }

  /// Loads all logs from local storage and categorizes them.
  Future<void> _loadAllLogs() async {
    setState(() => _isLoading = true);

    // Fetch all individual log types
    final preDepartureLogs =
    await _localStorageService.getAllPreDepartureLogs();
    final sondeCalibrationLogs =
    await _localStorageService.getAllSondeCalibrationLogs();
    final equipmentMaintenanceLogs =
    await _localStorageService.getAllEquipmentMaintenanceLogs();
    final npeReportLogs = await _localStorageService.getAllNpeLogs();

    final List<SubmissionLogEntry> tempPreSampling = [];
    final List<SubmissionLogEntry> tempReport = [];

    // 1. Process Pre-Departure Logs -> Pre-Sampling
    for (var log in preDepartureLogs) {
      final dateStr = log['submissionDate'] ?? '';
      tempPreSampling.add(SubmissionLogEntry(
        type: 'Pre-Departure Checklist',
        title: 'Pre-Departure Checklist',
        stationCode: 'N/A',
        senderName: (log['reporterName'] as String?) ?? 'Unknown User',
        submissionDateTime: DateTime.tryParse(dateStr) ??
            DateTime.fromMillisecondsSinceEpoch(0),
        reportId: log['reportId']?.toString(),
        status: log['submissionStatus'] ?? 'L1',
        message: log['submissionMessage'] ?? 'No status message.',
        rawData: log,
        serverName: log['serverConfigName'] ?? 'Unknown Server',
        apiStatusRaw: log['api_status'],
      ));
    }

    // 2. Process Sonde Calibration Logs -> Pre-Sampling
    for (var log in sondeCalibrationLogs) {
      final dateStr = log['startDateTime'] ?? '';
      tempPreSampling.add(SubmissionLogEntry(
        type: 'Sonde Calibration',
        title: 'Sonde Calibration',
        stationCode: log['location'] ?? 'N/A',
        senderName: (log['calibratedByUserName'] as String?) ?? 'Unknown User',
        submissionDateTime: DateTime.tryParse(dateStr) ??
            DateTime.fromMillisecondsSinceEpoch(0),
        reportId: log['reportId']?.toString(),
        status: log['submissionStatus'] ?? 'L1',
        message: log['submissionMessage'] ?? 'No status message.',
        rawData: log,
        serverName: log['serverConfigName'] ?? 'Unknown Server',
        apiStatusRaw: log['api_status'],
      ));
    }

    // 3. Process Equipment Maintenance Logs -> Pre-Sampling
    for (var log in equipmentMaintenanceLogs) {
      final dateStr = log['maintenanceDate'] ?? '';
      tempPreSampling.add(SubmissionLogEntry(
        type: 'Equipment Maintenance',
        title: 'Equipment Maintenance',
        stationCode: log['location'] ?? 'N/A',
        senderName: (log['conductedByUserName'] as String?) ?? 'Unknown User',
        submissionDateTime: DateTime.tryParse(dateStr) ??
            DateTime.fromMillisecondsSinceEpoch(0),
        reportId: log['reportId']?.toString(),
        status: log['submissionStatus'] ?? 'L1',
        message: log['submissionMessage'] ?? 'No status message.',
        rawData: log,
        serverName: log['serverConfigName'] ?? 'Unknown Server',
        apiStatusRaw: log['api_status'],
      ));
    }

    // 4. Process NPE Report Logs -> Report
    for (var log in npeReportLogs) {
      final dateStr = log['eventDate'] ?? '';
      final timeStr = log['eventTime'] ?? '';
      final title = log['selectedStation']?['man_station_name'] ??
          log['selectedStation']?['tbl_station_name'] ??
          log['locationDescription'] ??
          'NPE Report';
      final stationCode = log['selectedStation']?['man_station_code'] ??
          log['selectedStation']?['tbl_station_code'] ??
          'N/A';

      tempReport.add(SubmissionLogEntry(
        type: 'NPE Report',
        title: title,
        stationCode: stationCode,
        senderName: (log['firstSamplerName'] as String?) ?? 'Unknown User',
        submissionDateTime: DateTime.tryParse('$dateStr $timeStr') ??
            DateTime.fromMillisecondsSinceEpoch(0),
        reportId: log['reportId']?.toString(),
        status: log['submissionStatus'] ?? 'L1',
        message: log['submissionMessage'] ?? 'No status message.',
        rawData: log,
        serverName: log['serverConfigName'] ?? 'Unknown Server',
        apiStatusRaw: log['api_status'],
        ftpStatusRaw: log['ftp_status'],
      ));
    }

    // Sort logs by date (descending)
    tempPreSampling
        .sort((a, b) => b.submissionDateTime.compareTo(a.submissionDateTime));
    tempReport
        .sort((a, b) => b.submissionDateTime.compareTo(a.submissionDateTime));

    if (mounted) {
      setState(() {
        _preSamplingLogs = tempPreSampling;
        _reportLogs = tempReport;
        _isLoading = false;
      });
      _filterLogs();
    }
  }

  /// Filters logs based on search query.
  void _filterLogs() {
    final preSamplingQuery = _preSamplingSearchController.text.toLowerCase();
    final reportQuery = _reportSearchController.text.toLowerCase();

    setState(() {
      _filteredPreSamplingLogs = _preSamplingLogs
          .where((log) => _logMatchesQuery(log, preSamplingQuery))
          .toList();
      _filteredReportLogs = _reportLogs
          .where((log) => _logMatchesQuery(log, reportQuery))
          .toList();
    });
  }

  bool _logMatchesQuery(SubmissionLogEntry log, String query) {
    if (query.isEmpty) return true;
    return log.title.toLowerCase().contains(query) ||
        log.stationCode.toLowerCase().contains(query) ||
        log.serverName.toLowerCase().contains(query) ||
        log.type.toLowerCase().contains(query) ||
        log.senderName.toLowerCase().contains(query) ||
        (log.reportId?.toLowerCase() ?? '').contains(query);
  }

  /// Helper to reconstruct a File object from a stored path.
  File? _createFileFromPath(String? path) {
    if (path != null && path.isNotEmpty) {
      return File(path);
    }
    return null;
  }

  /// Reconstructs the data model from raw log data and triggers resubmission.
  Future<void> _resubmitData(SubmissionLogEntry log) async {
    final logKey = log.reportId ?? log.submissionDateTime.toIso8601String();
    if (mounted) {
      setState(() {
        _isResubmitting[logKey] = true;
      });
    }

    try {
      final authProvider = Provider.of<AuthProvider>(context, listen: false);
      final appSettings = authProvider.appSettings;

      Map<String, dynamic> result = {};
      final logData = log.rawData;

      switch (log.type) {
        case 'Pre-Departure Checklist':
          final data = MarineManualPreDepartureChecklistData();
          data.reporterUserId = logData['reporterUserId'];
          data.submissionDate = logData['submissionDate'];
          // Reconstruct maps
          if (logData['checklistItems'] != null) {
            data.checklistItems =
            Map<String, bool>.from(logData['checklistItems']);
          }
          if (logData['remarks'] != null) {
            data.remarks = Map<String, String>.from(logData['remarks']);
          }
          result = await _preDepartureService.submitChecklist(
            data: data,
            authProvider: authProvider,
            appSettings: appSettings,
            context: context,
            logDirectory: log.rawData['logDirectory'] as String?,
          );
          break;

        case 'Sonde Calibration':
          final data = MarineManualSondeCalibrationData();
          data.calibratedByUserId = logData['calibratedByUserId'];
          data.sondeSerialNumber = logData['sondeSerialNumber'];
          data.firmwareVersion = logData['firmwareVersion'];
          data.korVersion = logData['korVersion'];
          data.location = logData['location'];
          data.startDateTime = logData['startDateTime'];
          data.endDateTime = logData['endDateTime'];
          data.ph7Mv = (logData['ph_7_mv'] as num?)?.toDouble();
          data.ph7Before = (logData['ph_7_before'] as num?)?.toDouble();
          data.ph7After = (logData['ph_7_after'] as num?)?.toDouble();
          data.ph10Mv = (logData['ph_10_mv'] as num?)?.toDouble();
          data.ph10Before = (logData['ph_10_before'] as num?)?.toDouble();
          data.ph10After = (logData['ph_10_after'] as num?)?.toDouble();
          data.condBefore = (logData['cond_before'] as num?)?.toDouble();
          data.condAfter = (logData['cond_after'] as num?)?.toDouble();
          data.doBefore = (logData['do_before'] as num?)?.toDouble();
          data.doAfter = (logData['do_after'] as num?)?.toDouble();
          data.turbidity0Before =
              (logData['turbidity_0_before'] as num?)?.toDouble();
          data.turbidity0After =
              (logData['turbidity_0_after'] as num?)?.toDouble();
          data.turbidity124Before =
              (logData['turbidity_124_before'] as num?)?.toDouble();
          data.turbidity124After =
              (logData['turbidity_124_after'] as num?)?.toDouble();
          data.calibrationStatus = logData['calibration_status'];
          data.remarks = logData['remarks'];

          result = await _sondeCalibrationService.submitCalibration(
            data: data,
            authProvider: authProvider,
            appSettings: appSettings,
            context: context,
            logDirectory: log.rawData['logDirectory'] as String?,
          );
          break;

        case 'Equipment Maintenance':
          final data = MarineManualEquipmentMaintenanceData();
          data.conductedByUserId = logData['conductedByUserId'];
          data.maintenanceDate = logData['maintenanceDate'];
          data.lastMaintenanceDate = logData['lastMaintenanceDate'];
          data.scheduleMaintenance = logData['scheduleMaintenance'];
          data.isReplacement = logData['isReplacement'] ?? false;
          data.timeStart = logData['timeStart'];
          data.timeEnd = logData['timeEnd'];
          data.location = logData['location'];
          data.ysiSondeComments = logData['ysiSondeComments'];
          data.ysiSensorComments = logData['ysiSensorComments'];
          data.vanDornComments = logData['vanDornComments'];
          data.vanDornCurrentSerial = logData['vanDornCurrentSerial'];
          data.vanDornNewSerial = logData['vanDornNewSerial'];

          // Reconstruct complex maps
          if (logData['ysiSondeChecks'] != null) {
            data.ysiSondeChecks =
            Map<String, bool>.from(logData['ysiSondeChecks']);
          }
          if (logData['ysiSensorChecks'] != null) {
            data.ysiSensorChecks =
                (logData['ysiSensorChecks'] as Map<String, dynamic>).map(
                      (key, value) => MapEntry(key, Map<String, bool>.from(value)),
                );
          }
          if (logData['ysiReplacements'] != null) {
            data.ysiReplacements =
                (logData['ysiReplacements'] as Map<String, dynamic>).map(
                      (key, value) => MapEntry(key, Map<String, String>.from(value)),
                );
          }
          if (logData['vanDornChecks'] != null) {
            data.vanDornChecks =
                (logData['vanDornChecks'] as Map<String, dynamic>).map(
                      (key, value) => MapEntry(key, Map<String, bool>.from(value)),
                );
          }
          if (logData['vanDornReplacements'] != null) {
            data.vanDornReplacements =
                (logData['vanDornReplacements'] as Map<String, dynamic>).map(
                      (key, value) => MapEntry(key, Map<String, String>.from(value)),
                );
          }

          result = await _equipmentMaintenanceService.submitMaintenanceReport(
            data: data,
            authProvider: authProvider,
            appSettings: appSettings,
            context: context,
            logDirectory: log.rawData['logDirectory'] as String?,
          );
          break;

        case 'NPE Report':
          final data = MarineManualNpeReportData();
          data.firstSamplerName = logData['firstSamplerName'];
          data.firstSamplerUserId = logData['firstSamplerUserId'];
          data.eventDate = logData['eventDate'];
          data.eventTime = logData['eventTime'];
          data.locationDescription = logData['locationDescription'];
          data.stateName = logData['stateName'];
          data.selectedStation = logData['selectedStation'];
          data.latitude = logData['latitude'];
          data.longitude = logData['longitude'];
          data.oxygenSaturation =
              (logData['oxygenSaturation'] as num?)?.toDouble();
          data.electricalConductivity =
              (logData['electricalConductivity'] as num?)?.toDouble();
          data.oxygenConcentration =
              (logData['oxygenConcentration'] as num?)?.toDouble();
          data.turbidity = (logData['turbidity'] as num?)?.toDouble();
          data.ph = (logData['ph'] as num?)?.toDouble();
          data.temperature = (logData['temperature'] as num?)?.toDouble();
          data.possibleSource = logData['possibleSource'];
          data.image1Remark = logData['image1Remark'];
          data.image2Remark = logData['image2Remark'];
          data.image3Remark = logData['image3Remark'];
          data.image4Remark = logData['image4Remark'];
          data.tarballClassificationId = logData['tarballClassificationId'];
          data.selectedTarballClassification =
          logData['selectedTarballClassification'];

          // Reconstruct maps
          if (logData['fieldObservations'] != null) {
            data.fieldObservations =
            Map<String, bool>.from(logData['fieldObservations']);
          }

          // Reconstruct files from stored paths
          data.image1 = _createFileFromPath(logData['image1Path']);
          data.image2 = _createFileFromPath(logData['image2Path']);
          data.image3 = _createFileFromPath(logData['image3Path']);
          data.image4 = _createFileFromPath(logData['image4Path']);

          result = await _npeReportService.submitNpeReport(
            data: data,
            authProvider: authProvider,
            logDirectory: log.rawData['logDirectory'] as String?,
          );
          break;

        default:
          throw Exception('Unknown log type for resubmission: ${log.type}');
      }

      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
              content:
              Text(result['message'] ?? 'Resubmission process completed.')),
        );
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('Resubmission failed: $e')),
        );
      }
    } finally {
      if (mounted) {
        setState(() {
          _isResubmitting.remove(logKey);
        });
        _loadAllLogs(); // Refresh the log list
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    final hasAnyLogs = _preSamplingLogs.isNotEmpty || _reportLogs.isNotEmpty;

    return Scaffold(
      appBar: AppBar(title: const Text('Marine Report Status Log')),
      body: _isLoading
          ? const Center(child: CircularProgressIndicator())
          : RefreshIndicator(
        onRefresh: _loadAllLogs,
        child: !hasAnyLogs
            ? const Center(child: Text('No submission logs found.'))
            : ListView(
          padding: const EdgeInsets.all(8.0),
          children: [
            _buildCategorySection(
              'Pre-Sampling Log',
              _filteredPreSamplingLogs,
              _preSamplingSearchController,
            ),
            _buildCategorySection(
              'NPE Report Log',
              _filteredReportLogs,
              _reportSearchController,
            ),
          ],
        ),
      ),
    );
  }

  /// Builds a collapsible card for a category of logs.
  Widget _buildCategorySection(String category, List<SubmissionLogEntry> logs,
      TextEditingController searchController) {
    return Card(
      margin: const EdgeInsets.symmetric(vertical: 8.0),
      child: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(category,
                style: Theme.of(context)
                    .textTheme
                    .titleLarge
                    ?.copyWith(fontWeight: FontWeight.bold)),
            Padding(
              padding: const EdgeInsets.symmetric(vertical: 8.0),
              child: TextField(
                controller: searchController,
                decoration: InputDecoration(
                  hintText: 'Search in this category...',
                  prefixIcon: const Icon(Icons.search, size: 20),
                  isDense: true,
                  border: const OutlineInputBorder(),
                  suffixIcon: searchController.text.isNotEmpty
                      ? IconButton(
                    icon: const Icon(Icons.clear),
                    onPressed: () {
                      searchController.clear();
                    },
                  )
                      : null,
                ),
              ),
            ),
            const Divider(),
            if (logs.isEmpty)
              const Padding(
                  padding: EdgeInsets.all(16.0),
                  child: Center(
                      child:
                      Text('No logs match your search in this category.')))
            else
              ListView.builder(
                shrinkWrap: true,
                physics: const NeverScrollableScrollPhysics(),
                itemCount: logs.length,
                itemBuilder: (context, index) {
                  return _buildLogListItem(logs[index]);
                },
              ),
          ],
        ),
      ),
    );
  }

  /// Builds an ExpansionTile for a single log entry.
  Widget _buildLogListItem(SubmissionLogEntry log) {
    final logKey = log.reportId ?? log.submissionDateTime.toIso8601String();
    final isResubmitting = _isResubmitting[logKey] ?? false;

    // Determine status icon and color
    final bool isFullSuccess = log.status == 'S4';
    final bool isPartialSuccess = log.status == 'S3' || log.status == 'L4';
    final bool canResubmit = !isFullSuccess;

    IconData statusIcon;
    Color statusColor;

    if (isFullSuccess) {
      statusIcon = Icons.check_circle_outline;
      statusColor = Colors.green;
    } else if (isPartialSuccess) {
      statusIcon = Icons.warning_amber_rounded;
      statusColor = Colors.orange;
    } else {
      statusIcon = Icons.error_outline;
      statusColor = Colors.red;
    }

    final titleWidget = RichText(
      text: TextSpan(
        style: Theme.of(context)
            .textTheme
            .bodyLarge
            ?.copyWith(fontWeight: FontWeight.w500),
        children: <TextSpan>[
          TextSpan(text: '${log.title} '),
          if (log.stationCode != 'N/A')
            TextSpan(
              text: '(${log.stationCode})',
              style: Theme.of(context)
                  .textTheme
                  .bodySmall
                  ?.copyWith(fontWeight: FontWeight.normal),
            ),
        ],
      ),
    );

    final bool isDateValid = !log.submissionDateTime
        .isAtSameMomentAs(DateTime.fromMillisecondsSinceEpoch(0));
    final subtitle = isDateValid
        ? '${log.senderName} - ${DateFormat('yyyy-MM-dd HH:mm').format(log.submissionDateTime)}'
        : '${log.senderName} - Invalid Date';

    return ExpansionTile(
      key: PageStorageKey(logKey),
      leading: Icon(statusIcon, color: statusColor),
      title: titleWidget,
      subtitle: Text(subtitle),
      trailing: canResubmit
          ? (isResubmitting
          ? const SizedBox(
          height: 24,
          width: 24,
          child: CircularProgressIndicator(strokeWidth: 3))
          : IconButton(
          icon: const Icon(Icons.sync, color: Colors.blue),
          tooltip: 'Resubmit',
          onPressed: () => _resubmitData(log)))
          : null,
      children: [
        Padding(
          padding: const EdgeInsets.fromLTRB(16, 8, 16, 16),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              _buildDetailRow('Submission Type:', log.type),
              _buildDetailRow('High-Level Status:', log.status),
              _buildDetailRow('Server:', log.serverName),
              _buildDetailRow('Report ID:', log.reportId ?? 'N/A'),
              _buildGranularStatus('API', log.apiStatusRaw),
              _buildGranularStatus('FTP', log.ftpStatusRaw),
              _buildDetailRow('Message:', log.message),

              const Divider(height: 10),
              Padding(
                padding: const EdgeInsets.symmetric(vertical: 8.0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    TextButton.icon(
                      icon: Icon(Icons.list_alt,
                          color: Theme.of(context).colorScheme.primary),
                      label: Text('View Data',
                          style: TextStyle(
                              color: Theme.of(context).colorScheme.primary)),
                      onPressed: () => _showDataDialog(context, log),
                    ),
                    TextButton.icon(
                      icon: Icon(Icons.photo_library_outlined,
                          color: Theme.of(context).colorScheme.secondary),
                      label: Text('View Images',
                          style: TextStyle(
                              color: Theme.of(context).colorScheme.secondary)),
                      onPressed: () => _showImageDialog(context, log),
                    ),
                  ],
                ),
              ),
            ],
          ),
        )
      ],
    );
  }

  Widget _buildDetailRow(String label, String value) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 4.0),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Expanded(
              flex: 2,
              child: Text(label,
                  style: const TextStyle(fontWeight: FontWeight.bold))),
          const SizedBox(width: 8),
          Expanded(flex: 3, child: Text(value)),
        ],
      ),
    );
  }

  // =========================================================================
  // --- START: MODIFIED SECTION FOR VIEW DATA / VIEW IMAGE FUNCTIONALITY ---
  // =========================================================================

  /// Helper to safely get a string value from the raw data map.
  String? _getString(Map<String, dynamic> data, String key) {
    final value = data[key];
    if (value == null) return null;
    return value.toString();
  }

  /// Builds a formatted category header row for the data list.
  Widget _buildCategoryHeader(
      BuildContext context, String title, IconData icon) {
    return Padding(
      padding: const EdgeInsets.only(top: 16.0, bottom: 8.0),
      child: Row(
        children: [
          Icon(icon, size: 20, color: Theme.of(context).primaryColor),
          const SizedBox(width: 8),
          Text(
            title,
            style: TextStyle(
              fontWeight: FontWeight.bold,
              fontSize: 16,
              color: Theme.of(context).primaryColor,
            ),
          ),
        ],
      ),
    );
  }

  /// Builds a formatted Section header (replacement for _buildCategoryRow).
  Widget _buildSectionHeader(
      BuildContext context, String title, IconData icon) {
    return Container(
      margin: const EdgeInsets.only(top: 16.0, bottom: 8.0),
      padding: const EdgeInsets.all(8.0),
      decoration: BoxDecoration(
        color: Colors.grey.shade200,
        borderRadius: BorderRadius.circular(4),
      ),
      child: Row(
        children: [
          Icon(icon, size: 18, color: Theme.of(context).primaryColor),
          const SizedBox(width: 8),
          Expanded(
            child: Text(
              title,
              style: TextStyle(
                fontWeight: FontWeight.bold,
                fontSize: 15,
                color: Theme.of(context).primaryColor,
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// Builds a responsive data row (replacement for _buildDataTableRow).
  /// Uses Column for better responsiveness on small screens if needed,
  /// or Row with Expanded to allow wrapping.
  Widget _buildResponsiveDataRow(String label, String? value,
      {Color? valueColor}) {
    String displayValue =
    (value == null || value.isEmpty || value == 'null') ? 'N/A' : value;

    if (displayValue == '-999.0' || displayValue == '-999') {
      displayValue = 'N/A';
    }

    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 6.0, horizontal: 4.0),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Expanded(
            flex: 2,
            child: Text(
              label,
              style: const TextStyle(
                fontWeight: FontWeight.bold,
                fontSize: 14.0,
              ),
            ),
          ),
          const SizedBox(width: 8),
          Expanded(
            flex: 3,
            child: Text(
              displayValue,
              style: TextStyle(
                fontSize: 14.0,
                color: (displayValue == 'N/A') ? Colors.grey : valueColor,
              ),
              textAlign: TextAlign.left,
            ),
          ),
        ],
      ),
    );
  }

  /// Shows the categorized and formatted data log in a dialog
  void _showDataDialog(BuildContext context, SubmissionLogEntry log) {
    final Map<String, dynamic> data = log.rawData;
    Widget dialogContent; // This will hold either a ListView or a Column

    if (log.type == 'Pre-Departure Checklist') {
      // --- Handle Pre-Departure Checklist (Existing Logic) ---
      final items = Map<String, bool>.from(data['checklistItems'] ?? {});
      final remarks = Map<String, String>.from(data['remarks'] ?? {});

      final List<Widget> contentWidgets = [];

      for (final categoryEntry in _checklistSections.entries) {
        final categoryTitle = categoryEntry.key;
        final categoryItems = categoryEntry.value;

        contentWidgets.add(_buildCategoryHeader(
            context, categoryTitle, Icons.check_box_outlined));

        contentWidgets.addAll(categoryItems.map((itemName) {
          final bool value = items[itemName] ?? false;
          final String remark = remarks[itemName] ?? '';
          final String status = value ? 'Yes' : 'No';

          return Padding(
            padding: const EdgeInsets.symmetric(vertical: 8.0, horizontal: 8.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Expanded(
                      flex: 3,
                      child: Text(
                        itemName,
                        style: const TextStyle(
                          fontWeight: FontWeight.bold,
                          fontSize: 14.0,
                        ),
                      ),
                    ),
                    const SizedBox(width: 8),
                    Expanded(
                      flex: 1,
                      child: Text(
                        status,
                        style: TextStyle(
                          fontSize: 14.0,
                          color: value
                              ? Colors.green.shade700
                              : Colors.red.shade700,
                          fontWeight: FontWeight.bold,
                        ),
                        textAlign: TextAlign.end,
                      ),
                    ),
                  ],
                ),
                if (remark.isNotEmpty)
                  Padding(
                    padding: const EdgeInsets.only(top: 6.0, left: 8.0),
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          "Remark: ",
                          style: TextStyle(
                            fontSize: 13.0,
                            color: Colors.grey.shade700,
                            fontStyle: FontStyle.italic,
                          ),
                        ),
                        Expanded(
                          child: Text(
                            remark,
                            style: TextStyle(
                              fontSize: 13.0,
                              color: Colors.grey.shade700,
                              fontStyle: FontStyle.italic,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
              ],
            ),
          );
        }).toList());
        contentWidgets.add(const Divider(height: 16));
      }

      // Handle other items
      final Set<String> allCategorizedItems =
      _checklistSections.values.expand((list) => list).toSet();
      final List<Widget> otherItems = [];

      for (final itemEntry in items.entries) {
        if (!allCategorizedItems.contains(itemEntry.key)) {
          final key = itemEntry.key;
          final value = itemEntry.value;
          final status = value ? 'Yes' : 'No';
          final remark = remarks[key] ?? '';

          otherItems.add(Padding(
            padding: const EdgeInsets.symmetric(vertical: 8.0, horizontal: 8.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Expanded(
                        flex: 3,
                        child: Text(key,
                            style: const TextStyle(
                                fontWeight: FontWeight.bold, fontSize: 14.0))),
                    const SizedBox(width: 8),
                    Expanded(
                        flex: 1,
                        child: Text(status,
                            style: TextStyle(
                                fontSize: 14.0,
                                color: value
                                    ? Colors.green.shade700
                                    : Colors.red.shade700,
                                fontWeight: FontWeight.bold),
                            textAlign: TextAlign.end)),
                  ],
                ),
                if (remark.isNotEmpty)
                  Padding(
                    padding: const EdgeInsets.only(top: 6.0, left: 8.0),
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text("Remark: ",
                            style: TextStyle(
                                fontSize: 13.0,
                                color: Colors.grey.shade700,
                                fontStyle: FontStyle.italic)),
                        Expanded(
                            child: Text(remark,
                                style: TextStyle(
                                    fontSize: 13.0,
                                    color: Colors.grey.shade700,
                                    fontStyle: FontStyle.italic))),
                      ],
                    ),
                  ),
              ],
            ),
          ));
        }
      }

      if (otherItems.isNotEmpty) {
        contentWidgets.add(
            _buildCategoryHeader(context, "Other Items", Icons.help_outline));
        contentWidgets.addAll(otherItems);
      }

      if (contentWidgets.isEmpty) {
        dialogContent = const Center(child: Text('No checklist items found.'));
      } else {
        dialogContent = Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: contentWidgets,
        );
      }
    } else {
      // --- START: Handle ALL OTHER Log Types (NOW USING RESPONSIVE WIDGETS) ---
      final List<Widget> listWidgets = [];

      // --- Helper for nested maps ---
      void addNestedMapRows(Map<String, dynamic> map) {
        map.forEach((key, value) {
          if (value is Map) {
            listWidgets.add(_buildResponsiveDataRow(key, ''));
            value.forEach((subKey, subValue) {
              listWidgets.add(_buildResponsiveDataRow(
                  '  $subKey', subValue?.toString() ?? 'N/A'));
            });
          } else {
            listWidgets.add(
                _buildResponsiveDataRow(key, value?.toString() ?? 'N/A'));
          }
        });
      }
      // --- End Helper ---

      switch (log.type) {
        case 'Sonde Calibration':
          listWidgets.add(
              _buildSectionHeader(context, 'Sonde Info', Icons.info_outline));
          listWidgets.add(_buildResponsiveDataRow(
              'Sonde Serial #', _getString(data, 'sondeSerialNumber')));
          listWidgets.add(_buildResponsiveDataRow(
              'Firmware Version', _getString(data, 'firmwareVersion')));
          listWidgets.add(_buildResponsiveDataRow(
              'KOR Version', _getString(data, 'korVersion')));
          listWidgets.add(
              _buildResponsiveDataRow('Location', _getString(data, 'location')));
          listWidgets.add(_buildResponsiveDataRow(
              'Start Time', _getString(data, 'startDateTime')));
          listWidgets.add(_buildResponsiveDataRow(
              'End Time', _getString(data, 'endDateTime')));
          listWidgets.add(_buildResponsiveDataRow(
              'Status', _getString(data, 'calibration_status')));
          listWidgets.add(
              _buildResponsiveDataRow('Remarks', _getString(data, 'remarks')));

          listWidgets.add(
              _buildSectionHeader(context, 'pH 7.0', Icons.science_outlined));
          listWidgets
              .add(_buildResponsiveDataRow('MV', _getString(data, 'ph_7_mv')));
          listWidgets.add(
              _buildResponsiveDataRow('Before', _getString(data, 'ph_7_before')));
          listWidgets.add(
              _buildResponsiveDataRow('After', _getString(data, 'ph_7_after')));

          listWidgets.add(
              _buildSectionHeader(context, 'pH 10.0', Icons.science_outlined));
          listWidgets.add(
              _buildResponsiveDataRow('MV', _getString(data, 'ph_10_mv')));
          listWidgets.add(_buildResponsiveDataRow(
              'Before', _getString(data, 'ph_10_before')));
          listWidgets.add(
              _buildResponsiveDataRow('After', _getString(data, 'ph_10_after')));

          listWidgets.add(
              _buildSectionHeader(context, 'Conductivity', Icons.thermostat));
          listWidgets.add(_buildResponsiveDataRow(
              'Before', _getString(data, 'cond_before')));
          listWidgets.add(
              _buildResponsiveDataRow('After', _getString(data, 'cond_after')));

          listWidgets.add(
              _buildSectionHeader(context, 'Dissolved Oxygen', Icons.air));
          listWidgets.add(
              _buildResponsiveDataRow('Before', _getString(data, 'do_before')));
          listWidgets.add(
              _buildResponsiveDataRow('After', _getString(data, 'do_after')));

          listWidgets.add(
              _buildSectionHeader(context, 'Turbidity', Icons.waves));
          listWidgets.add(_buildResponsiveDataRow(
              '0 NTU Before', _getString(data, 'turbidity_0_before')));
          listWidgets.add(_buildResponsiveDataRow(
              '0 NTU After', _getString(data, 'turbidity_0_after')));
          listWidgets.add(_buildResponsiveDataRow(
              '124 NTU Before', _getString(data, 'turbidity_124_before')));
          listWidgets.add(_buildResponsiveDataRow(
              '124 NTU After', _getString(data, 'turbidity_124_after')));
          break;

        case 'Equipment Maintenance':
          listWidgets.add(_buildSectionHeader(
              context, 'YSI Sonde Checks', Icons.build_circle_outlined));
          if (data['ysiSondeChecks'] != null) {
            addNestedMapRows(Map<String, dynamic>.from(data['ysiSondeChecks']));
          }
          listWidgets.add(_buildResponsiveDataRow(
              'Comments', _getString(data, 'ysiSondeComments')));

          listWidgets.add(_buildSectionHeader(
              context, 'YSI Sensor Checks', Icons.sensors));
          if (data['ysiSensorChecks'] != null) {
            addNestedMapRows(
                Map<String, dynamic>.from(data['ysiSensorChecks']));
          }
          listWidgets.add(_buildResponsiveDataRow(
              'Comments', _getString(data, 'ysiSensorComments')));

          listWidgets.add(_buildSectionHeader(
              context, 'YSI Replacements', Icons.published_with_changes));
          if (data['ysiReplacements'] != null) {
            addNestedMapRows(
                Map<String, dynamic>.from(data['ysiReplacements']));
          }

          listWidgets.add(
              _buildSectionHeader(context, 'Van Dorn Checks', Icons.opacity));
          if (data['vanDornChecks'] != null) {
            addNestedMapRows(Map<String, dynamic>.from(data['vanDornChecks']));
          }
          listWidgets.add(_buildResponsiveDataRow(
              'Comments', _getString(data, 'vanDornComments')));
          listWidgets.add(_buildResponsiveDataRow(
              'Current Serial', _getString(data, 'vanDornCurrentSerial')));
          listWidgets.add(_buildResponsiveDataRow(
              'New Serial', _getString(data, 'vanDornNewSerial')));

          listWidgets.add(_buildSectionHeader(context, 'Van Dorn Replacements',
              Icons.published_with_changes));
          if (data['vanDornReplacements'] != null) {
            addNestedMapRows(
                Map<String, dynamic>.from(data['vanDornReplacements']));
          }
          break;

        case 'NPE Report':
          listWidgets.add(
              _buildSectionHeader(context, 'Event Info', Icons.calendar_today));
          listWidgets.add(
              _buildResponsiveDataRow('Date', _getString(data, 'eventDate')));
          listWidgets.add(
              _buildResponsiveDataRow('Time', _getString(data, 'eventTime')));
          listWidgets.add(_buildResponsiveDataRow(
              'Sampler', _getString(data, 'firstSamplerName')));

          listWidgets.add(_buildSectionHeader(
              context, 'Location', Icons.location_on_outlined));
          if (data['selectedStation'] != null) {
            listWidgets.add(_buildResponsiveDataRow(
                'Station',
                _getString(data['selectedStation'], 'man_station_name') ??
                    _getString(data['selectedStation'], 'tbl_station_name')));
          } else {
            listWidgets.add(_buildResponsiveDataRow(
                'Location', _getString(data, 'locationDescription')));
            listWidgets.add(
                _buildResponsiveDataRow('State', _getString(data, 'stateName')));
          }
          listWidgets.add(
              _buildResponsiveDataRow('Latitude', _getString(data, 'latitude')));
          listWidgets.add(_buildResponsiveDataRow(
              'Longitude', _getString(data, 'longitude')));

          listWidgets.add(
              _buildSectionHeader(context, 'Parameters', Icons.bar_chart));
          listWidgets.add(_buildResponsiveDataRow(
              'Oxygen Conc (mg/L)', _getString(data, 'oxygenConcentration')));
          listWidgets.add(_buildResponsiveDataRow(
              'Oxygen Sat (%)', _getString(data, 'oxygenSaturation')));
          listWidgets.add(_buildResponsiveDataRow('pH', _getString(data, 'ph')));
          listWidgets.add(_buildResponsiveDataRow('Conductivity (µS/cm)',
              _getString(data, 'electricalConductivity')));
          listWidgets.add(_buildResponsiveDataRow(
              'Temperature (°C)', _getString(data, 'temperature')));
          listWidgets.add(_buildResponsiveDataRow(
              'Turbidity (NTU)', _getString(data, 'turbidity')));

          listWidgets.add(_buildSectionHeader(
              context, 'Observations', Icons.warning_amber_rounded));
          if (data['fieldObservations'] != null) {
            final observations =
            Map<String, bool>.from(data['fieldObservations']);
            observations.forEach((key, value) {
              if (value) listWidgets.add(_buildResponsiveDataRow(key, 'Checked'));
            });
          }
          listWidgets.add(_buildResponsiveDataRow(
              'Other Remarks', _getString(data, 'othersObservationRemark')));
          listWidgets.add(_buildResponsiveDataRow(
              'Possible Source', _getString(data, 'possibleSource')));
          if (data['selectedTarballClassification'] != null) {
            listWidgets.add(_buildResponsiveDataRow(
                'Tarball Class',
                _getString(data['selectedTarballClassification'],
                    'classification_name')));
          }
          break;

        default:
          listWidgets.add(_buildResponsiveDataRow(
              'Error', 'No data view configured for log type: ${log.type}'));
      }

      // Assign the content
      dialogContent = Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: listWidgets,
      );
      // --- END: Handle ALL OTHER Log Types ---
    }

    showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: Text('${log.title} (${log.stationCode})'),
          content: SizedBox(
            width: double.maxFinite,
            child: SingleChildScrollView(
              child: dialogContent,
            ),
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              child: const Text('Close'),
            ),
          ],
        );
      },
    );
  }
  // --- END: MODIFIED METHOD ---

  /// Shows the image gallery dialog
  void _showImageDialog(BuildContext context, SubmissionLogEntry log) {
    final List<ImageLogEntry> imageEntries = [];

    if (log.type == 'NPE Report') {
      // NPE images are stored with 'image#Path' keys in the log
      const imageRemarkMap = {
        'image1Path': 'image1Remark',
        'image2Path': 'image2Remark',
        'image3Path': 'image3Remark',
        'image4Path': 'image4Remark',
      };
      _addImagesToList(log, imageRemarkMap, imageEntries);
    }

    if (imageEntries.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('No images are attached to this log.'),
          backgroundColor: Colors.orange,
        ),
      );
      return;
    }

    showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: Text('Images for ${log.title}'),
          content: SizedBox(
            width: double.maxFinite,
            child: GridView.builder(
              shrinkWrap: true,
              itemCount: imageEntries.length,
              gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 2,
                crossAxisSpacing: 8,
                mainAxisSpacing: 8,
              ),
              itemBuilder: (context, index) {
                final imageEntry = imageEntries[index];
                final bool hasRemark =
                    imageEntry.remark != null && imageEntry.remark!.isNotEmpty;

                return Card(
                  clipBehavior: Clip.antiAlias,
                  elevation: 2,
                  child: Stack(
                    fit: StackFit.expand,
                    children: [
                      Image.file(
                        imageEntry.file,
                        fit: BoxFit.cover,
                        errorBuilder: (context, error, stack) {
                          return const Center(
                            child: Icon(
                              Icons.broken_image,
                              color: Colors.grey,
                              size: 40,
                            ),
                          );
                        },
                      ),
                      if (hasRemark)
                        Positioned(
                          bottom: 0,
                          left: 0,
                          right: 0,
                          child: Container(
                            padding: const EdgeInsets.all(6.0),
                            decoration: BoxDecoration(
                              gradient: LinearGradient(
                                begin: Alignment.bottomCenter,
                                end: Alignment.topCenter,
                                colors: [
                                  Colors.black.withOpacity(0.8),
                                  Colors.black.withOpacity(0.0)
                                ],
                              ),
                            ),
                            child: Text(
                              imageEntry.remark!,
                              style: const TextStyle(
                                color: Colors.white,
                                fontSize: 12,
                                fontWeight: FontWeight.bold,
                              ),
                              maxLines: 2,
                              overflow: TextOverflow.ellipsis,
                            ),
                          ),
                        ),
                    ],
                  ),
                );
              },
            ),
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              child: const Text('Close'),
            ),
          ],
        );
      },
    );
  }

  /// Helper for _showImageDialog
  void _addImagesToList(SubmissionLogEntry log,
      Map<String, String?> imageRemarkMap, List<ImageLogEntry> imageEntries) {
    for (final entry in imageRemarkMap.entries) {
      final imageKey = entry.key;
      final remarkKey = entry.value;

      final path = log.rawData[imageKey];
      if (path != null && path is String && path.isNotEmpty) {
        final file = File(path);
        if (file.existsSync()) {
          final remark =
          (remarkKey != null ? log.rawData[remarkKey] as String? : null);
          imageEntries.add(ImageLogEntry(file: file, remark: remark));
        }
      }
    }
  }

  /// Helper to build granular status (copied from data log)
  Widget _buildGranularStatus(String type, String? jsonStatus) {
    if (jsonStatus == null || jsonStatus.isEmpty) {
      // Return an empty row for "API Status: N/A" if it was the default
      if (type == 'API') {
        return _buildDetailRow('API Status:', 'N/A');
      }
      return Container();
    }

    List<dynamic> statuses;
    try {
      statuses = jsonDecode(jsonStatus);
    } catch (_) {
      return _buildDetailRow('$type Status:', jsonStatus);
    }

    if (statuses.isEmpty) {
      if (type == 'API') {
        return _buildDetailRow('API Status:', 'N/A');
      }
      return Container();
    }

    return Padding(
      padding: const EdgeInsets.only(top: 8.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text('$type Status:',
              style: const TextStyle(fontWeight: FontWeight.bold)),
          ...statuses.map((s) {
            final serverName =
                s['server_name'] ?? s['config_name'] ?? 'Server N/A';
            final status = s['message'] ?? 'N/A';
            final bool isSuccess = s['success'] as bool? ?? false;
            final IconData icon =
            isSuccess ? Icons.check_circle_outline : Icons.error_outline;
            final Color color = isSuccess ? Colors.green : Colors.red;
            String detailLabel = (s['type'] != null) ? '(${s['type']})' : '';

            return Padding(
              padding:
              const EdgeInsets.symmetric(vertical: 3.0, horizontal: 8.0),
              child: Row(
                children: [
                  Icon(icon, size: 16, color: color),
                  const SizedBox(width: 5),
                  Expanded(child: Text('$serverName $detailLabel: $status')),
                ],
              ),
            );
          }).toList(),
        ],
      ),
    );
  }

// =========================================================================
// --- END: MODIFIED SECTION ---
// =========================================================================
}