import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:file_picker/file_picker.dart';
import 'package:image_picker/image_picker.dart';
import 'package:inventory_system/services/api_service.dart';
import 'package:inventory_system/services/item_movement_service.dart';
import 'package:inventory_system/services/item_service.dart';
import 'package:inventory_system/services/session_manager.dart';
import 'package:inventory_system/services/station_service.dart';
import 'package:inventory_system/services/store_service.dart';
import 'package:inventory_system/screens/title_bar.dart';

class ScanResultUserScreen extends StatefulWidget {
  final String scannedCode;

  const ScanResultUserScreen({super.key, required this.scannedCode});

  @override
  State<ScanResultUserScreen> createState() => _ScanResultUserScreenState();
}

class _ScanResultUserScreenState extends State<ScanResultUserScreen> {
  final ItemService _itemService = ItemService();
  final ItemMovementService _itemMovementService = ItemMovementService();
  final StationService _stationService = StationService();
  final StoreService _storeService = StoreService();

  bool _isLoading = true;
  String? _errorMessage;
  Map<String, dynamic>? _item;
  Map<String, dynamic>? _currentUser;
  dynamic _inventoryMasterId; // from StoreSpecificMaster

  // Derived state (displayStatus from Vue)
  String? _displayStatus; // 'arrived', 'return', 'requestAgain', 'differentUser' or null
  List<dynamic> _stationList = [];

  // Form State
  final TextEditingController _remarkController = TextEditingController();
  final TextEditingController _cancelRemarkController = TextEditingController();
  String? _consignmentNoteBase64;
  String? _consignmentNoteFileName;
  dynamic _selectedStationId;

  @override
  void initState() {
    super.initState();
    _loadData();
  }

  Future<void> _loadData() async {
    setState(() {
      _isLoading = true;
      _errorMessage = null;
    });

    try {
      _currentUser = SessionManager.instance.currentUser;
      if (_currentUser == null) {
        throw Exception("User session not found.");
      }

      final uniqueID = widget.scannedCode.contains('/') 
          ? widget.scannedCode.split('/').last 
          : widget.scannedCode;

      // Fetch Item
      _item = await _itemService.getItem(uniqueID);
      if (_item == null) {
         throw Exception("Item not found.");
      }

      // Fetch Stations (User specific)
      final allStations = await _stationService.fetchStations();
      _stationList = allStations.where((s) => s['stationPicID'] == _currentUser!['id']).toList();

      // Fetch Store Info (to get InventoryMasterId)
      if (_item!['toStore'] != null) {
          final stores = await _storeService.fetchStores();
          final store = stores.firstWhere((s) => s['id'] == _item!['toStore'], orElse: () => {});
          if (store.isNotEmpty) {
             _inventoryMasterId = store['userId']; 
          }
      }

      _determineDisplayStatus();

    } catch (e) {
      setState(() => _errorMessage = e.toString());
    } finally {
      setState(() => _isLoading = false);
    }
  }

  void _determineDisplayStatus() {
    if (_item == null || _currentUser == null) return;

    final currentUserId = _currentUser!['id'];
    final toOther = _item!['toOther'];
    final latestStatus = _item!['latestStatus'];
    
    // Vue uses `thisItem.currentUserId`. Check if it exists, otherwise fallback to `toUser`.
    final itemCurrentUserId = _item!.containsKey('currentUserId') ? _item!['currentUserId'] : _item!['toUser'];
    
    final movementComplete = _item!['movementComplete'] == true || _item!['movementComplete'] == 1;
    
    debugPrint("--- Scan Result Debug ---");
    debugPrint("Current User ID: $currentUserId");
    debugPrint("Item Data: $_item");
    debugPrint("Item Movement ID: ${_item!['movementId']}");
    debugPrint("To Other: $toOther");
    debugPrint("Latest Status: $latestStatus");
    debugPrint("Item Current User ID (from map): $itemCurrentUserId");
    debugPrint("Movement Complete: $movementComplete");

    // Logic from Vue:
    // 1. Arrived
    if (_item!['movementId'] != null && 
        toOther == "On Delivery" && 
        latestStatus == null && 
        itemCurrentUserId.toString() == currentUserId.toString() && 
        !movementComplete) {
      _displayStatus = "arrived";
    } 
    // 2. Return
    else if (_item!['movementId'] != null && 
             latestStatus != null && 
             itemCurrentUserId.toString() == currentUserId.toString() && 
             latestStatus != "Ready To Deploy") {
      _displayStatus = "return";
    }
    // 3. Request Again
    else if (_item!['movementId'] != null && 
             toOther == "Return" && 
             latestStatus == null && 
             _item!['toUser'].toString() == currentUserId.toString()) {
      _displayStatus = "requestAgain";
    }
    // 4. Different User
    else {
      _displayStatus = "differentUser";
    }
    debugPrint("Determined Display Status: $_displayStatus");
  }

  Future<void> _receiveItem({bool andReturn = false}) async {
    if (!andReturn) {
       bool confirm = await _showConfirmationDialog("Are you sure you already received this item?");
       if (!confirm) return;
    }

    setState(() => _isLoading = true);
    try {
      final now = DateTime.now();
      final formData = {
        'Id': _item!['movementId'], 
        'LastStore': _item!['toStore'],
        'LatestStatus': "Delivered",
        'ReceiveDate': now.add(const Duration(hours: 8)).toIso8601String(),
        'MovementComplete': true,
      };

      await _itemMovementService.updateItemMovementUser(formData);

      if (mounted) {
        if (andReturn) {
           await _loadData(); // Refresh item state
           await _returnItem();
        } else {
          ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('Success! Item has been successfully received.')));
          Navigator.pop(context); // Redirect to scanner
        }
      }
    } catch (e) {
      if (mounted) ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('Error: $e')));
    } finally {
      if (mounted && !andReturn) setState(() => _isLoading = false);
    }
  }

  Future<void> _returnItem() async {
    await _returnItemAction();
  }

  Future<void> _showReturnDialog({bool receiveFirst = false}) async {
    _remarkController.clear();
    _consignmentNoteBase64 = null;
    _consignmentNoteFileName = null;

    await showDialog(
      context: context,
      builder: (context) => StatefulBuilder(
        builder: (context, setDialogState) {
          return AlertDialog(
            title: const Text("Return Item"),
            content: SingleChildScrollView(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                   TextField(
                     controller: _remarkController,
                     decoration: const InputDecoration(labelText: "Remark"),
                   ),
                   const SizedBox(height: 12),
                   _buildFilePicker(setDialogState),
                ],
              ),
            ),
            actions: [
              TextButton(onPressed: () => Navigator.pop(context), child: const Text("Cancel")),
              ElevatedButton(
                onPressed: () {
                  Navigator.pop(context); // Close dialog
                  if (receiveFirst) {
                    _receiveItem(andReturn: true);
                  } else {
                    _returnItemAction();
                  }
                },
                child: const Text("Submit"),
              )
            ],
          );
        }
      )
    );
  }

  Future<void> _returnItemAction() async {
    setState(() => _isLoading = true);
    try {
      final now = DateTime.now();
      final formData = {
        'ItemId': _item!['itemID'],
        'ToStation': _item!['toStation'], 
        'ToStore': _item!['toStore'], 
        'ToUser': _currentUser!['id'],
        'ToOther': "Return",
        'SendDate': now.add(const Duration(hours: 8)).toIso8601String(),
        'Action': "StockIn",
        'Quantity': _item!['quantity'],
        'Remark': _remarkController.text,
        'ConsignmentNote': _consignmentNoteBase64,
        'Date': now.add(const Duration(hours: 8)).toIso8601String(),
        'LastUser': _inventoryMasterId, 
        'LastStore': _item!['toStore'],
        'LastStation': _item!['toStation'],
        'LatestStatus': null,
        'ReceiveDate': null,
        'MovementComplete': false,
      };

      await _itemMovementService.returnItemMovementUser(formData);

      if (mounted) {
         ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('Success! Item is on the delivery to return.')));
         Navigator.pop(context); // Exit after return
      }
    } catch (e) {
      if (mounted) ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('Error: $e')));
       setState(() => _isLoading = false);
    }
  }

  Future<void> _showDeployStationDialog() async {
    _remarkController.clear();
    _consignmentNoteBase64 = null;
    _consignmentNoteFileName = null;
    _selectedStationId = null;

    await showDialog(
      context: context,
      builder: (context) => StatefulBuilder(
        builder: (context, setDialogState) {
          return AlertDialog(
            title: Text(_item!['toStation'] == null ? "Deploy Station" : "Change Station"),
            content: SingleChildScrollView(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  DropdownButtonFormField(
                    value: _selectedStationId,
                    hint: const Text("Select Station"),
                    items: _stationList.map<DropdownMenuItem>((s) => DropdownMenuItem(value: s['stationId'], child: Text(s['stationName']))).toList(),
                    onChanged: (val) => setDialogState(() => _selectedStationId = val),
                    decoration: const InputDecoration(border: OutlineInputBorder()),
                  ),
                  if (_stationList.isEmpty)
                    const Padding(padding: EdgeInsets.only(top: 8), child: Text("No Station Assigned to You", style: TextStyle(color: Colors.red, fontSize: 12))),
                  const SizedBox(height: 12),
                  TextField(
                     controller: _remarkController,
                     decoration: const InputDecoration(labelText: "Remark"),
                   ),
                   const SizedBox(height: 12),
                   _buildFilePicker(setDialogState),
                ],
              ),
            ),
            actions: [
              TextButton(onPressed: () => Navigator.pop(context), child: const Text("Cancel")),
              ElevatedButton(
                onPressed: () {
                  if (_selectedStationId == null) {
                     return;
                  }
                  Navigator.pop(context);
                  _deployStationAction();
                },
                child: const Text("Deploy"),
              )
            ],
          );
        }
      )
    );
  }

  Future<void> _deployStationAction() async {
    setState(() => _isLoading = true);
    try {
      final now = DateTime.now();
      final formData = {
        'ItemId': _item!['itemID'],
        'ToStation': _item!['toStation'], 
        'ToStore': _item!['toStore'],
        'ToUser': _currentUser!['id'],
        'ToOther': "Delivered",
        'SendDate': now.add(const Duration(hours: 8)).toIso8601String(),
        'Action': "Assign",
        'Quantity': _item!['quantity'],
        'Remark': _remarkController.text,
        'ConsignmentNote': _consignmentNoteBase64,
        'Date': now.add(const Duration(hours: 8)).toIso8601String(),
        'LastUser': _currentUser!['id'],
        'LastStore': _item!['toStore'],
        'LastStation': _selectedStationId, 
        'LatestStatus': "Delivered",
        'ReceiveDate': now.add(const Duration(hours: 8)).toIso8601String(),
        'MovementComplete': true,
      };

      await _itemMovementService.stationItemMovementUser(formData);

      if (mounted) {
         ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('Success! Item assigned to the Station.')));
         Navigator.pop(context); // Redirect to scanner
      }
    } catch (e) {
      if (mounted) ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('Error: $e')));
      setState(() => _isLoading = false);
    }
  }

  Future<void> _confirmCancelItemMovement() async {
    bool confirm = await showDialog(
      context: context, 
      builder: (c) => AlertDialog(
        title: const Text('Confirm Cancellation'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Text('Are you sure you want to cancel this item movement?'),
            const SizedBox(height: 10),
            TextField(
              controller: _cancelRemarkController,
              decoration: const InputDecoration(labelText: "Reason for Cancellation", border: OutlineInputBorder()),
            )
          ],
        ),
        actions: [
          TextButton(onPressed: () => Navigator.pop(c, false), child: const Text('No')),
          TextButton(onPressed: () => Navigator.pop(c, true), child: const Text('Yes')),
        ],
      )
    ) ?? false;

    if (!confirm) return;

    setState(() => _isLoading = true);

    try {
      final originalMovement = await _itemMovementService.getItemMovementById(_item!['movementId']);
      final currentRemark = originalMovement['remark'] ?? '';

      await _itemMovementService.updateItemMovementMaster({
        'Id': _item!['movementId'],
        'MovementComplete': true,
        'LatestStatus': 'Cancelled',
        'Remark': '$currentRemark${currentRemark.isNotEmpty ? ' / ' : ''}Movement cancelled: ${_cancelRemarkController.text}',
      });

      final registrationMovementData = {
        'ItemId': _item!['itemID'],
        'ToStore': _currentUser!['store'],
        'ToUser': _currentUser!['id'],
        'ToOther': null,
        'sendDate': null,
        'Action': 'Register',
        'Quantity': _item!['movementQuantity'] ?? _item!['quantity'], 
        'Remark': null,
        'ConsignmentNote': null,
        'LastUser': _currentUser!['id'],
        'LastStore': _currentUser!['store'],
        'LatestStatus': 'Ready To Deploy',
        'receiveDate': null,
        'MovementComplete': true,
      };
      await _itemMovementService.addItemMovement(registrationMovementData);

      await _itemService.updateItemQuantity({
        'ItemId': _item!['itemID'],
        'MovementId': _item!['movementId']
      });

      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('Cancelled successfully')),
        );
        Navigator.pop(context);
      }

    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('Error: $e')),
        );
      }
    } finally {
      if (mounted) setState(() => _isLoading = false);
    }
  }

  Widget _buildFilePicker(StateSetter setDialogState) {
     return Column(
       crossAxisAlignment: CrossAxisAlignment.start,
       children: [
         const Text("Consignment Note", style: TextStyle(fontWeight: FontWeight.bold)),
         const SizedBox(height: 8),
         Row(
           children: [
             ElevatedButton.icon(
               onPressed: () async {
                  final XFile? image = await ImagePicker().pickImage(source: ImageSource.camera);
                  if (image != null) {
                    final bytes = await image.readAsBytes();
                    setDialogState(() {
                      _consignmentNoteBase64 = base64Encode(bytes);
                      _consignmentNoteFileName = image.name;
                    });
                  }
               }, 
               icon: const Icon(Icons.camera_alt, size: 16), 
               label: const Text("Cam")
             ),
             const SizedBox(width: 8), 
             Expanded(child: Text(_consignmentNoteFileName ?? "", overflow: TextOverflow.ellipsis)),
             if (_consignmentNoteFileName != null)
               IconButton(
                 icon: const Icon(Icons.close, color: Colors.red),
                 onPressed: () => setDialogState(() {
                   _consignmentNoteBase64 = null;
                   _consignmentNoteFileName = null;
                 })
               )
           ],
         )
       ],
     );
  }

  Future<bool> _showConfirmationDialog(String message) async {
    return await showDialog(
      context: context, 
      builder: (c) => AlertDialog(
        title: const Text('Confirm'),
        content: Text(message),
        actions: [
          TextButton(onPressed: () => Navigator.pop(c, false), child: const Text('No')),
          TextButton(onPressed: () => Navigator.pop(c, true), child: const Text('Yes')),
        ],
      )
    ) ?? false;
  }

  @override
  Widget build(BuildContext context) {
    if (_isLoading) {
      return const Scaffold(
        body: Center(child: CircularProgressIndicator()),
      );
    }

    if (_errorMessage != null) {
      return Scaffold(
        appBar: const TitleBar(title: 'Error'),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              const Icon(Icons.error_outline, size: 64, color: Colors.red),
              const SizedBox(height: 16),
              Text(_errorMessage!, textAlign: TextAlign.center),
              const SizedBox(height: 16),
              ElevatedButton(
                onPressed: () => Navigator.pop(context),
                child: const Text('Go Back'),
              )
            ],
          ),
        ),
      );
    }

    if (_item == null) {
      return Scaffold(
        appBar: const TitleBar(title: 'Not Found'),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              const Text("Item not found."),
              ElevatedButton(onPressed: () => Navigator.pop(context), child: const Text("Back"))
            ],
          ),
        ),
      );
    }

    return DefaultTabController(
      length: 2,
      child: Scaffold(
        backgroundColor: const Color(0xFFF5F5F7),
        appBar: const TitleBar(title: 'Scan Result'),
        body: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            children: [
              _buildTabs(),
              const SizedBox(height: 12),
              Expanded(
                child: TabBarView(
                  children: [
                    _buildItemMovementTab(),
                    _buildItemInformationTab(),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildTabs() {
    return Container(
      padding: const EdgeInsets.all(4),
      decoration: BoxDecoration(
        color: Colors.purple.shade50,
        borderRadius: BorderRadius.circular(12),
      ),
      child: SizedBox(
        height: 44,
        child: TabBar(
          isScrollable: false,
          indicatorSize: TabBarIndicatorSize.tab,
          indicatorPadding: EdgeInsets.zero,
          labelPadding: EdgeInsets.zero,
          dividerColor: Colors.transparent,
          indicator: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(10),
            border: Border.all(color: Colors.purple.shade100),
          ),
          labelColor: Colors.purple.shade900,
          unselectedLabelColor: Colors.black54,
          tabs: const [
            Tab(child: Center(child: Text('Item Movement'))),
            Tab(child: Center(child: Text('Item Information'))),
          ],
        ),
      ),
    );
  }

  Widget _buildItemMovementTab() {
    final stationName = _item!['toStationName'] ?? (_item!['toStation'] == null ? 'No Station Deploy (Self Assign)' : 'Unknown Station');
    final picName = _item!['toUserName'] ?? _currentUser!['fullName'] ?? 'N/A';

    return SingleChildScrollView(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Center(
            child: Column(
              children: [
                const SizedBox(height: 4),
                const Text(
                  'Item Status:',
                  style: TextStyle(fontWeight: FontWeight.w700, fontSize: 16),
                ),
                const SizedBox(height: 4),
                Text(
                  _item!['latestStatus'] ?? _item!['toOther'] ?? 'N/A',
                  style: TextStyle(color: Colors.blue.shade700, fontSize: 14, fontWeight: FontWeight.bold),
                ),
              ],
            ),
          ),
          const SizedBox(height: 8),
          _buildFramedImage(_item!),
          const SizedBox(height: 16),
          _buildKV('Item Name', _item!['productName'] ?? 'N/A', icon: Icons.edit_note_rounded),
          _buildKV('Part Number', _item!['partNumber'] ?? 'N/A', icon: Icons.confirmation_number_rounded),
          _buildKV('Serial Number', _item!['serialNumber'] ?? 'N/A', icon: Icons.numbers_rounded),
          _buildKV('Station', stationName, icon: Icons.place_rounded), // Added Station
          _buildKV('PIC', picName, icon: Icons.person),
          
          const SizedBox(height: 12),
          _buildSenderInfoSection(_item!), // Renamed to _buildSenderInfoSection
          const SizedBox(height: 16),

          _buildDynamicActionSection(),
        ],
      ),
    );
  }

  Widget _buildItemInformationTab() {
    final picName = _item!['toUserName'] ?? _currentUser!['fullName'] ?? 'N/A';
    final stationName = _item!['toStationName'] ?? (_item!['toStation'] == null ? 'No Station Deploy (Self Assign)' : 'Unknown Station'); // Added stationName

    return SingleChildScrollView(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          const SizedBox(height: 8),
          _buildFramedImage(_item!),
          const SizedBox(height: 16),
           _buildKV('Unique ID', _item!['uniqueID'] ?? 'N/A', icon: Icons.qr_code),
          _buildKV('Item Name', _item!['productName'] ?? 'N/A', icon: Icons.edit_note_rounded),
          _buildKV('Category', _item!['category'] ?? 'N/A', icon: Icons.category),
          _buildKV('Part Number', _item!['partNumber'] ?? 'N/A', icon: Icons.confirmation_number_rounded),
          _buildKV('Serial Number', _item!['serialNumber'] ?? 'N/A', icon: Icons.numbers_rounded),
          _buildKV('Station', stationName, icon: Icons.place_rounded), // Added Station
           _buildKV('PIC', picName, icon: Icons.person),
          _buildKV('Quantity', _item!['quantity']?.toString() ?? '0', icon: Icons.production_quantity_limits),
        ],
      ),
    );
  }

  Widget _buildDynamicActionSection() {
    if (_displayStatus == "arrived") {
      return Column(
        children: [
           Card(
            elevation: 2,
            child: Padding(
              padding: const EdgeInsets.all(16.0),
              child: Column(
                children: [
                  const Text("Cancel Item Movement", style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold, color: Colors.red)),
                  const SizedBox(height: 8),
                  TextField(
                    controller: _cancelRemarkController,
                    decoration: const InputDecoration(labelText: 'Reason for Cancellation', border: OutlineInputBorder()),
                  ),
                  const SizedBox(height: 12),
                  ElevatedButton(
                    onPressed: _confirmCancelItemMovement,
                    style: ElevatedButton.styleFrom(backgroundColor: Colors.red, foregroundColor: Colors.white),
                    child: const Text("Confirm Cancel"),
                  )
                ],
              ),
            ),
          ),
          const SizedBox(height: 16),
          Row(
            children: [
              Expanded(
                child: ElevatedButton(
                  onPressed: () => _showReturnDialog(receiveFirst: true),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.grey.shade700,
                    foregroundColor: Colors.white,
                     padding: const EdgeInsets.symmetric(vertical: 12)
                  ),
                  child: const Text("Return Item"),
                ),
              ),
              const SizedBox(width: 16),
              Expanded(
                child: ElevatedButton(
                  onPressed: () => _receiveItem(),
                   style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.blue.shade700,
                    foregroundColor: Colors.white,
                     padding: const EdgeInsets.symmetric(vertical: 12)
                  ),
                  child: const Text("Receive Item"),
                ),
              ),
            ],
          )
        ],
      );
    } else if (_displayStatus == "return") {
       return Column(
        children: [
          Row(
            children: [
              Expanded(
                child: ElevatedButton(
                  onPressed: () => _showReturnDialog(),
                   style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.white,
                    foregroundColor: Colors.black,
                     padding: const EdgeInsets.symmetric(vertical: 12)
                  ),
                  child: const Text("Return Item"),
                ),
              ),
              const SizedBox(width: 16),
              Expanded(
                child: ElevatedButton(
                  onPressed: () => _showDeployStationDialog(),
                   style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.purple.shade500,
                    foregroundColor: Colors.white,
                     padding: const EdgeInsets.symmetric(vertical: 12)
                  ),
                  child: Text(_item!['toStation'] == null ? "Deploy Station" : "Change Station"),
                ),
              ),
            ],
          )
        ],
      );
    }
    
    if (_displayStatus == "requestAgain" || _displayStatus == "differentUser") {
       return Center(
         child: Column(
           children: [
             if (_displayStatus == "requestAgain")
              const Card(
                color: Colors.redAccent,
                child: Padding(
                  padding: EdgeInsets.all(16),
                  child: Text("The item has been registered as returned.\nYou need to request this item again to use it legally.", 
                    textAlign: TextAlign.center, style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold)),
                ),
              ),
             if (_displayStatus == "differentUser")
              const Card(
                color: Colors.orangeAccent,
                child: Padding(
                  padding: EdgeInsets.all(16),
                  child: Text("The item is not assigned to you.\nYou need to request this item to validly use it.", 
                    textAlign: TextAlign.center, style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold)),
                ),
              ),
              const SizedBox(height: 16),
             ElevatedButton(
               onPressed: () => Navigator.pop(context),
               child: const Text("Back to Scanner"),
             ),
           ],
         ),
       );
    }

    return const SizedBox.shrink();
  }

  Widget _buildKV(String label, String value, {IconData? icon}) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 6),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          if (icon != null) ...[
            Icon(icon, size: 18, color: Colors.black87),
            const SizedBox(width: 8),
          ],
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(label, style: TextStyle(color: Colors.grey.shade700, fontSize: 12, fontWeight: FontWeight.w600)),
                const SizedBox(height: 2),
                Text(value, style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w600)),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildFramedImage(Map<String, dynamic> item) {
    final imagePath = item['imageProduct'];
    ImageProvider imageProvider;
    
    if (imagePath != null && imagePath.toString().isNotEmpty) {
      if (imagePath.toString().startsWith('http')) {
        imageProvider = NetworkImage(imagePath);
      } else if (imagePath.toString().startsWith('/')) {
        imageProvider = NetworkImage('${ApiService.baseUrl}$imagePath');
      } else {
         imageProvider = const AssetImage('assets/images/ram.jpg'); 
      }
    } else {
      imageProvider = const AssetImage('assets/images/ram.jpg');
    }

    return Center(
      child: Container(
        padding: const EdgeInsets.all(12),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(16),
          border: Border.all(color: Colors.grey.shade300),
        ),
        child: Column(
          children: [
            ClipRRect(
              borderRadius: BorderRadius.circular(8),
              child: Image(
                image: imageProvider,
                width: 160,
                height: 100,
                fit: BoxFit.cover,
                errorBuilder: (c, e, s) => Image.asset('assets/images/ram.jpg', width: 160, height: 100),
              ),
            ),
            const SizedBox(height: 6),
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
              decoration: BoxDecoration(
                border: Border.all(color: Colors.grey.shade500),
                borderRadius: BorderRadius.circular(6),
              ),
              child: Text(item['uniqueID'] ?? '-', style: const TextStyle(fontSize: 12)),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildSenderInfoSection(Map<String, dynamic> item) {
    return Container(
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: Colors.purple.shade200),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Icon(Icons.info_rounded, color: Colors.purple.shade700),
              const SizedBox(width: 8),
              const Text('Sender Information', style: TextStyle(fontWeight: FontWeight.w700)),
            ],
          ),
          const SizedBox(height: 8),
          _buildKV('User', item['toUserName'] ?? 'N/A', icon: Icons.person_rounded),
        ],
      ),
    );
  }
}