import 'package:flutter/material.dart';
import 'package:inventory_system/screens/title_bar.dart';
import 'package:inventory_system/screens/nav_bar.dart';
import 'package:inventory_system/screens/bottom_nav_bar.dart';
import 'package:inventory_system/services/item_movement_service.dart'; // Import service
import 'package:inventory_system/services/api_service.dart'; // Import ApiService for image base URL
import 'package:collection/collection.dart'; // Import for groupBy

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

  @override
  State<ItemMovementAllUserScreen> createState() => _ItemMovementAllUserScreenState();
}

class _ItemMovementAllUserScreenState extends State<ItemMovementAllUserScreen>
    with SingleTickerProviderStateMixin {
  int _selectedIndex = 0;

  late TabController _tabController;

  String _selectedDropdownValue = 'All';
  final List<String> _dropdownOptions = ['All', 'Item', 'Station'];

  int? _expandedIndex;
  Key _tabViewKey = UniqueKey();

  final TextEditingController _pendingSearchController = TextEditingController();
  final TextEditingController _completeSearchController = TextEditingController();
  final TextEditingController _assignSearchController = TextEditingController();

  List<Map<String, dynamic>> _allMovements = []; // Will hold fetched data
  List<Map<String, dynamic>> _pendingFiltered = [];
  List<Map<String, dynamic>> _completeFiltered = [];
  List<Map<String, dynamic>> _assignFiltered = [];

  final ItemMovementService _itemMovementService = ItemMovementService(); // Service instance
  bool _isLoading = true;
  String? _errorMessage;

  @override
  void initState() {
    super.initState();
    _fetchInitialData(); // Call fetch data
    _pendingSearchController.addListener(_applyFilters);
    _completeSearchController.addListener(_applyFilters);
    _assignSearchController.addListener(_applyFilters);

    _tabController = TabController(length: 3, vsync: this);
    _tabController.addListener(() {
      if (!_tabController.indexIsChanging && _expandedIndex != null) {
        setState(() {
          _expandedIndex = null;
          _tabViewKey = UniqueKey();
        });
      }
    });
  }

  Future<void> _fetchInitialData() async {
    setState(() {
      _isLoading = true;
      _errorMessage = null;
    });
    try {
      final rawMovements = (await _itemMovementService.fetchItemMovements()).cast<Map<String, dynamic>>();
      if (!mounted) return;

      // 1. Group by UniqueID
      final grouped = groupBy(rawMovements, (Map<String, dynamic> m) => m['uniqueID']);
      
      List<Map<String, dynamic>> processedList = [];

      // 2. Process each group to find the LATEST valid movement
      for (var entry in grouped.entries) {
        var movements = entry.value;
        // Sort Newest to Oldest by date
        movements.sort((a, b) {
           final dateA = DateTime.tryParse(a['sendDate'] ?? a['date'] ?? '') ?? DateTime(0);
           final dateB = DateTime.tryParse(b['sendDate'] ?? b['date'] ?? '') ?? DateTime(0);
           return dateB.compareTo(dateA);
        });
        
        if (movements.isNotEmpty) {
          final latest = movements.first;
          
          // 3. Filter Logic: Hide if 'Return' or 'Ready To Deploy' is the CURRENT status
          bool isReturn = latest['toOther'] == 'Return' && (latest['movementComplete'] == 1 || latest['movementComplete'] == true);
          bool isReady = latest['latestStatus'] == 'Ready To Deploy' && (latest['movementComplete'] == 1 || latest['movementComplete'] == true);
          
          if (!isReturn && !isReady) {
            processedList.add(latest);
          }
        }
      }

      setState(() {
        _allMovements = processedList;
        _applyFilters(); // Apply filters on the processed list
        _isLoading = false;
      });
    } catch (e) {
      if (!mounted) return;
      setState(() {
        _errorMessage = 'Failed to load data: $e';
        _isLoading = false;
      });
      debugPrint('Error fetching initial data for ItemMovementAllUserScreen: $e');
    }
  }

  @override
  void dispose() {
    _pendingSearchController.removeListener(_applyFilters);
    _completeSearchController.removeListener(_applyFilters);
    _assignSearchController.removeListener(_applyFilters);

    _pendingSearchController.dispose();
    _completeSearchController.dispose();
    _assignSearchController.dispose();

    _tabController.dispose();
    super.dispose();
  }

  // Refactored _applyFilters to apply to _allMovements
  void _applyFilters() {
    final pendingQuery = _pendingSearchController.text.toLowerCase();
    final completeQuery = _completeSearchController.text.toLowerCase();
    final assignQuery = _assignSearchController.text.toLowerCase();

    setState(() {
      _pendingFiltered = _allMovements
          .where((m) => !(m['movementComplete'] as bool? ?? false) && _matchesQuery(m, pendingQuery))
          .toList();
      _completeFiltered = _allMovements
          .where((m) => (m['movementComplete'] as bool? ?? false) && _matchesQuery(m, completeQuery))
          .toList();
      _assignFiltered = _allMovements
          .where((m) => m['action'] == 'Assign' && _matchesQuery(m, assignQuery))
          .toList();
      _expandedIndex = null;
    });
  }

  bool _matchesQuery(Map<String, dynamic> m, String q) {
    if (q.isEmpty) return true;
    final keys = [
      'productName', 'uniqueID', 'action', 'productCategory', 'latestStatus',
      'toStationName', 'lastStationName', 'toStoreName', 'lastStoreName',
      'toUserName', 'lastUserName', 'remark', 'consignmentNote', 'id'
    ];
    for (final k in keys) {
      final v = m[k]?.toString().toLowerCase();
      if (v != null && v.contains(q)) return true;
    }
    return false;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF5F5F7),
      appBar: TitleBar(
        title: 'Item Movement',
        actions: [
          Container(
            margin: const EdgeInsets.symmetric(vertical: 8, horizontal: 16),
            padding: const EdgeInsets.symmetric(horizontal: 12),
            decoration: BoxDecoration(
              color: Colors.grey.shade200,
              borderRadius: BorderRadius.circular(12),
            ),
            child: DropdownButtonHideUnderline(
              child: DropdownButton<String>(
                value: _selectedDropdownValue,
                icon: const Icon(Icons.keyboard_arrow_down),
                items: _dropdownOptions.map((String value) {
                  return DropdownMenuItem<String>(
                    value: value,
                    child: Text(value),
                  );
                }).toList(),
                onChanged: (newValue) {
                  if (newValue == 'Item') {
                    Navigator.pushNamed(context, '/item_movement_item_user');
                  }
                  if (newValue == 'Station') {
                    Navigator.pushNamed(context, '/item_movement_station_user');
                  }
                  setState(() {
                    _selectedDropdownValue = newValue!;
                  });
                },
              ),
            ),
          ),
        ],
      ),
      drawer: const NavBar(isAdmin: false, selectedScreen: AppScreen.itemMovementUser),
      body: _isLoading
          ? const Center(child: CircularProgressIndicator())
          : _errorMessage != null
              ? Center(child: Padding(padding: const EdgeInsets.all(16.0), child: Text(_errorMessage!, style: const TextStyle(color: Colors.red, fontSize: 16), textAlign: TextAlign.center)))
              : RefreshIndicator(
                  onRefresh: _fetchInitialData,
                  child: Column(
                    children: [
                      Container(
                        color: Colors.white,
                        child: TabBar(
                          controller: _tabController,
                          onTap: (index) {
                            setState(() {
                              _expandedIndex = null;
                              _tabViewKey = UniqueKey();
                            });
                          },
                          labelColor: Colors.purple.shade800,
                          unselectedLabelColor: Colors.grey.shade600,
                          indicatorColor: Colors.purple.shade800,
                          indicatorWeight: 3,
                          tabs: const [
                            Tab(text: 'Pending Item'),
                            Tab(text: 'Complete Item'),
                            Tab(text: 'Assign Station'),
                          ],
                        ),
                      ),
                      Expanded(
                        child: TabBarView(
                          controller: _tabController,
                          key: _tabViewKey,
                          children: [
                            _buildTabPage(
                              controller: _pendingSearchController,
                              items: _pendingFiltered,
                              tabType: 'pending',
                            ),
                            _buildTabPage(
                              controller: _completeSearchController,
                              items: _completeFiltered,
                              tabType: 'complete',
                            ),
                            _buildTabPage(
                              controller: _assignSearchController,
                              items: _assignFiltered,
                              tabType: 'assign',
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
      bottomNavigationBar: BottomNavBar(
        selectedIndex: _selectedIndex,
        onItemTapped: (index) {
          if (index == 0) {
            Navigator.pop(context);
          } else if (index == 1) {
            if (mounted) {
              Navigator.pushNamed(context, '/scan');
            }
          } else {
            setState(() {
              _selectedIndex = index;
            });
          }
        },
      ),
    );
  }

  Widget _buildTabPage({
    required TextEditingController controller,
    required List<Map<String, dynamic>> items,
    required String tabType,
  }) {
    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: Column(
        children: [
          TextField(
            controller: controller,
            onChanged: (_) {
              _applyFilters(); // Call _applyFilters directly
            },
            decoration: InputDecoration(
              hintText: 'Search',
              hintStyle: TextStyle(color: Colors.grey.shade400),
              prefixIcon: const Icon(Icons.search),
              suffixIcon: controller.text.isNotEmpty
                  ? IconButton(
                      icon: const Icon(Icons.clear),
                      onPressed: () {
                        controller.clear();
                        _applyFilters(); // Call _applyFilters directly
                      },
                    )
                  : null,
              filled: true,
              fillColor: Colors.white,
              border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(12),
                borderSide: BorderSide.none,
              ),
            ),
          ),
          const SizedBox(height: 16),
          Expanded(
            child: RefreshIndicator(
              onRefresh: _fetchInitialData,
              child: ListView.builder(
                itemCount: items.length,
                itemBuilder: (context, index) {
                  final item = items[index];
                  return _buildItemCard(item, index, tabType);
                },
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// Builds a single item card with an expandable details section.
  Widget _buildItemCard(Map<String, dynamic> item, int index, String tabType) {
    final bool isExpanded = _expandedIndex == index;
    final String imageUrl = item['productImage'] ?? ''; // Use productImage from API

    return Padding(
      padding: const EdgeInsets.only(bottom: 12.0),
      child: Container(
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(16),
          border: Border.all(color: Colors.grey.shade300, width: 1),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Padding(
              padding: const EdgeInsets.all(16.0),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // Image + Product code (PID) under it
                  Column(
                    children: [
                      Container(
                        width: 80,
                        height: 80,
                        decoration: BoxDecoration(
                          color: Colors.grey.shade100,
                          borderRadius: BorderRadius.circular(12),
                          border: Border.all(color: Colors.grey.shade200),
                        ),
                        child: imageUrl.isNotEmpty
                            ? Image.network(
                                ApiService.baseUrl + imageUrl, // Use ApiService.baseUrl
                                fit: BoxFit.cover,
                                errorBuilder: (context, error, stackTrace) => const Icon(Icons.broken_image, color: Colors.grey),
                              )
                            : const Icon(Icons.image_not_supported, color: Colors.grey),
                      ),
                      const SizedBox(height: 6),
                      Text(
                        item['uniqueID'] ?? '-', // Use uniqueID from API
                        style: const TextStyle(
                          fontFamily: 'monospace',
                          fontSize: 12,
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(width: 16),
                  // Main Info
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          item['productName'] ?? '-', // Use productName from API
                          style: const TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        const SizedBox(height: 4),
                        Text('ID: ${item['id'] ?? '-'}', style: TextStyle(color: Colors.grey.shade600)),
                        const SizedBox(height: 2),
                        Text(item['date'] ?? '-', style: TextStyle(color: Colors.grey.shade600)), // Use 'date' from API
                      ],
                    ),
                  ),
                ],
              ),
            ),
            // "More Details" Toggle Button
            InkWell(
              onTap: () {
                setState(() {
                  // Only one open at a time
                  _expandedIndex = isExpanded ? null : index;
                });
              },
              child: Container(
                padding: const EdgeInsets.symmetric(vertical: 12),
                decoration: BoxDecoration(
                  border: Border(top: BorderSide(color: Colors.grey.shade200)),
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      isExpanded ? 'Less Details' : 'More Details',
                      style: TextStyle(
                        fontSize: 14,
                        fontWeight: FontWeight.w600,
                        color: Colors.blue.shade600, // align with other pages
                      ),
                    ),
                    const SizedBox(width: 4),
                    Icon(
                      isExpanded ? Icons.keyboard_arrow_up : Icons.keyboard_arrow_down,
                      color: Colors.blue.shade600, // align with other pages
                      size: 20,
                    ),
                  ],
                ),
              ),
            ),
            // The expandable section
            AnimatedSize(
              duration: const Duration(milliseconds: 300),
              curve: Curves.fastOutSlowIn,
              child: isExpanded
                  ? _buildDetailsSection(item, tabType)
                  : const SizedBox.shrink(),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildDetailsSection(Map<String, dynamic> item, String tabType) {
    // Build tiles per requirements; Note (assign) shown below tiles.
    List<Widget> tiles = [];
    String? remark = item['remark']; // Use 'remark' from API

    switch (tabType) {
      case 'pending':
        tiles = [
          _buildDetailItem('Action', item['action'] ?? 'N/A'),
          _buildDetailItem('Product Category', item['productCategory'] ?? 'N/A'), // Use productCategory
          _buildDetailItem('Status', item['latestStatus'] ?? 'N/A'), // Use latestStatus
          _buildDetailItem('From Station', item['lastStationName'] ?? 'N/A'),
          _buildDetailItem('From Store', item['lastStoreName'] ?? 'N/A'),
          _buildDetailItem('Quantity', item['quantity']?.toString() ?? 'N/A'),
          _buildDetailItem('From User', item['lastUserName'] ?? 'N/A'),
          _buildDetailItem('To User', item['toUserName'] ?? 'N/A'),
        ];
        break;
      case 'assign':
        tiles = [
          _buildDetailItem('Action', item['action'] ?? 'N/A'),
          _buildDetailItem('Station User PIC', item['toUserName'] ?? 'N/A'), // Assume toUserName is PIC
          _buildDetailItem('Quantity', item['quantity']?.toString() ?? 'N/A'),
          _buildDetailItem('From Station', item['lastStationName'] ?? 'N/A'),
          _buildDetailItem('To Station', item['toStationName'] ?? 'N/A'), // Use toStationName
          _buildDetailItem('Last Store', item['lastStoreName'] ?? 'N/A'),
        ];
        break;
      case 'complete':
        tiles = [
          _buildDetailItem('Action', item['action'] ?? 'N/A'),
          _buildDetailItem('Product Category', item['productCategory'] ?? 'N/A'),
          _buildDetailItem('Quantity', item['quantity']?.toString() ?? 'N/A'),
          _buildDetailItem('From Station', item['lastStationName'] ?? 'N/A'),
          _buildDetailItem('To Station', item['toStationName'] ?? 'N/A'),
          _buildDetailItem('From User', item['lastUserName'] ?? 'N/A'),
          _buildDetailItem('To User', item['toUserName'] ?? 'N/A'),
          _buildDetailItem('From Store', item['lastStoreName'] ?? 'N/A'),
          _buildDetailItem('To Store', item['toStoreName'] ?? 'N/A'),
          _buildDetailItem('Latest Status', item['latestStatus'] ?? 'N/A'),
        ];
        break;
    }

    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.grey.shade50,
        border: Border(top: BorderSide(color: Colors.grey.shade200)),
      ),
      child: LayoutBuilder(
        builder: (context, constraints) {
          const double spacing = 16;
          final double tileWidth = (constraints.maxWidth - (spacing * 2)) / 3;
          return Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Wrap(
                spacing: spacing,
                runSpacing: 12,
                children: tiles
                    .map((w) => SizedBox(width: tileWidth, child: w))
                    .toList(),
              ),
              if (remark != null && remark.toString().trim().isNotEmpty) ...[
                const SizedBox(height: 12),
                Text(
                  'Remark', // Changed 'Note' to 'Remark'
                  style: TextStyle(
                    fontSize: 12,
                    color: Colors.grey.shade600,
                  ),
                ),
                const SizedBox(height: 2),
                Text(
                  remark,
                  style: const TextStyle(
                    fontSize: 14,
                    fontWeight: FontWeight.w600,
                  ),
                ),
              ],
            ],
          );
        },
      ),
    );
  }

  /// A helper widget to display a label and its value.
  Widget _buildDetailItem(String label, String value) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          label,
          style: TextStyle(
            fontSize: 12,
            color: Colors.grey.shade600,
          ),
        ),
        const SizedBox(height: 2),
        Text(
          value,
          style: const TextStyle(
            fontSize: 14,
            fontWeight: FontWeight.w600,
          ),
          softWrap: true,
        ),
      ],
    );
  }
}
