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'; // For groupBy

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

  @override
  State<ItemMovementItemUserScreen> createState() => _ItemMovementItemUserScreenState();
}

class _ItemMovementItemUserScreenState extends State<ItemMovementItemUserScreen> {
  // Services
  final ItemMovementService _itemMovementService = ItemMovementService();

  // State
  bool _isLoading = true;
  String? _errorMessage;
  List<Map<String, dynamic>> _allMovements = []; // Raw movements from service
  List<Map<String, dynamic>> _groupedItems = []; // Grouped and sorted movements
  List<Map<String, dynamic>> _filteredItems = []; // Filtered for search

  String _selectedDropdownValue = 'Item';
  final List<String> _dropdownOptions = ['All', 'Item', 'Station'];
  final TextEditingController _searchController = TextEditingController();
  int _selectedIndex = 0; // bottom nav index

  int? _expandedItemIndex;
  final Set<String> _expandedMovements = {};
  final Set<String> _showFullHistory = {}; 

  @override
  void initState() {
    super.initState();
    _fetchInitialData();
    _searchController.addListener(_applyFilter);
  }

  @override
  void dispose() {
    _searchController.dispose();
    super.dispose();
  }

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

      // Group movements by uniqueID
      final grouped = groupBy(_allMovements, (Map<String, dynamic> m) => m['uniqueID']);
      
      List<Map<String, dynamic>> processedItems = [];

      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);
        });

        // Filter Logic from Web App
        // Find first occurrence of 'Return' complete
        int stopIndex = movements.indexWhere((m) => 
          m['toOther'] == 'Return' && (m['movementComplete'] == 1 || m['movementComplete'] == true)
        );

        // Find first occurrence of 'Ready To Deploy' complete
        int nextIndex = movements.indexWhere((m) => 
          m['latestStatus'] == 'Ready To Deploy' && (m['movementComplete'] == 1 || m['movementComplete'] == true)
        );

        if (stopIndex != -1) {
          movements = movements.sublist(0, stopIndex);
        }

        if (nextIndex != -1) {
          movements = movements.sublist(0, nextIndex);
        }

        if (movements.isNotEmpty) {
           processedItems.add({
            'pid': entry.key,
            'uniqueID': movements.first['uniqueID'],
            'history': movements,
            'productName': movements.first['productName'],
            'productImage': movements.first['productImage'],
          });
        }
      }

      setState(() {
        _groupedItems = processedItems;
        _filteredItems = List.of(_groupedItems); 
        _isLoading = false;
      });
    } catch (e) {
      if (!mounted) return;
      setState(() {
        _errorMessage = 'Failed to load data: $e';
        _isLoading = false;
      });
      debugPrint('Error fetching initial data for ItemMovementItemUserScreen: $e');
    }
  }

  void _applyFilter() {
    final query = _searchController.text.trim().toLowerCase();
    setState(() {
      _filteredItems = _groupedItems
          .where((item) => (item['pid'] as String?)?.toLowerCase().contains(query) ?? false)
          .toList();
      _expandedItemIndex = null;
      _expandedMovements.clear();
      _showFullHistory.clear();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF5F5F7),
      appBar: TitleBar(
        title: 'Item Movement',
        actions: [
          _buildDropdown(),
        ],
      ),
      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)))
          : Padding(
                  padding: const EdgeInsets.fromLTRB(16, 16, 16, 0),
                  child: Column(
                    children: [
                      _buildSearchBar(),
                      const SizedBox(height: 16),
                      Expanded(
                        child: _filteredItems.isEmpty
                            ? const Center(child: Text('No items found.'))
                            : RefreshIndicator(
                                onRefresh: _fetchInitialData,
                                child: ListView.builder(
                                  itemCount: _filteredItems.length,
                                  itemBuilder: (context, index) {
                                    final item = _filteredItems[index];
                                    final isExpanded = _expandedItemIndex == index;
                                    return _buildItemCard(item, index, isExpanded);
                                  },
                                ),
                              ),
                      ),
                    ],
                  ),
                ),
      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 _buildExpandedCardContent(Map<String, dynamic> item) {
    final List<dynamic> history = item['history'];
    final latestMovement = history.first as Map<String, dynamic>;
    final pid = item['pid'] as String;
    final bool isHistoryVisible = _showFullHistory.contains(pid);

    return Padding(
      padding: const EdgeInsets.all(12.0),      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            'Latest Movement',
            style: TextStyle(fontSize: 14, fontWeight: FontWeight.bold),
          ),
          const SizedBox(height: 8),
          _buildMovementDetailCard(latestMovement), 
          const SizedBox(height: 12),
          
          if (history.length > 1)
            InkWell(
              onTap: () {
                setState(() {
                  if (isHistoryVisible) {
                    _showFullHistory.remove(pid);
                  } else {
                    _showFullHistory.add(pid);
                  }
                });
              },
              child: Center(
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Text(
                      isHistoryVisible ? 'Hide History' : 'View History',
                      style: TextStyle(
                          color: Colors.grey.shade800,
                          fontWeight: FontWeight.w600),
                    ),
                    const SizedBox(width: 4),
                    Icon(
                      isHistoryVisible ? Icons.keyboard_arrow_up : Icons.keyboard_arrow_down,
                      size: 18,
                      color: Colors.grey.shade800,
                    ),
                  ],
                ),
              ),
            ),
          
          AnimatedSize(
            duration: const Duration(milliseconds: 300),
            curve: Curves.fastOutSlowIn,
            child: isHistoryVisible
                ? _buildHistoryList(history) 
                : const SizedBox.shrink(),     
          ),
        ],
      ),
    );
  }

  Widget _buildHistoryList(List<dynamic> history) {
    // Skip the first one as it is "Latest Movement"
    final olderMovements = history.skip(1).toList();
    
    return Padding(
      padding: const EdgeInsets.only(top: 12.0),
      child: Column(
        children: olderMovements.map((m) => Padding(
          padding: const EdgeInsets.only(bottom: 12.0),
          child: _buildMovementDetailCard(m as Map<String, dynamic>),
        )).toList(),
      ),
    );
  }

  // --- HELPER WIDGETS ---

  Widget _buildDropdown() {
    return 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 == 'All') {
              Navigator.pushReplacementNamed(context, '/item_movement_all_user');
            }
            if (newValue == 'Station') {
              Navigator.pushReplacementNamed(context, '/item_movement_station_user');
            }
            setState(() {
              _selectedDropdownValue = newValue!;
            });
          },
        ),
      ),
    );
  }

  Widget _buildSearchBar() {
    return TextField(
      controller: _searchController,
      decoration: InputDecoration(
        hintText: 'Search by item code',
        hintStyle: TextStyle(color: Colors.grey.shade400),
        prefixIcon: const Icon(Icons.search),
        suffixIcon: _searchController.text.isNotEmpty
            ? IconButton(
          icon: const Icon(Icons.clear),
          onPressed: () => _searchController.clear(),
        )
            : null,
        filled: true,
        fillColor: Colors.white,
        border: OutlineInputBorder(
          borderRadius: BorderRadius.circular(12),
          borderSide: BorderSide.none,
        ),
      ),
    );
  }

  Widget _buildItemCard(Map<String, dynamic> item, int index, bool isExpanded) {
    final headerBg = isExpanded ? Colors.blue.shade50 : Colors.white;
    final headerBorder = isExpanded ? Colors.blue.shade200 : Colors.grey.shade300;
    final pid = item['pid'];

    return Container(
      margin: const EdgeInsets.only(bottom: 12),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: headerBorder),
      ),
      child: Column(
        children: [
          InkWell(
            onTap: () {
              setState(() {
                _expandedItemIndex = isExpanded ? null : index;
                if (!isExpanded) {
                  _showFullHistory.remove(pid);
                }
              });
            },
            child: Container(
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: headerBg,
                borderRadius: const BorderRadius.vertical(top: Radius.circular(11)),
                border: Border(bottom: BorderSide(color: headerBorder)),
              ),
              child: Row(
                children: [
                  Expanded(
                    child: Text(
                      'Item : ${item['pid'] ?? 'N/A'}', 
                      style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                    ),
                  ),
                  Text(
                    isExpanded ? 'Hide Details' : 'Show Details',
                    style: TextStyle(
                      fontSize: 12,
                      fontWeight: FontWeight.w600,
                      color: isExpanded ? Colors.blue.shade700 : Colors.grey.shade700,
                    ),
                  ),
                  const SizedBox(width: 4),
                  Icon(
                    isExpanded ? Icons.keyboard_arrow_up : Icons.keyboard_arrow_down,
                    size: 20,
                    color: isExpanded ? Colors.blue.shade700 : Colors.grey.shade700,
                  ),
                ],
              ),
            ),
          ),
          AnimatedSize(
            duration: const Duration(milliseconds: 300),
            curve: Curves.fastOutSlowIn,
            child: isExpanded
                ? _buildExpandedCardContent(item)
                : const SizedBox.shrink(),
          ),
        ],
      ),
    );
  }

  Widget _buildMovementDetailCard(Map<String, dynamic> movement) {
    final movementId = movement['id'].toString(); // Ensure String key for Set
    final bool isInnerExpanded = _expandedMovements.contains(movementId);

    // --- Web App Logic for Labels and Colors ---
    String toOther = movement['toOther'] ?? '';
    String action = movement['action'] ?? '';
    bool isToStation = movement['toStation'] != null;
    bool isMovementComplete = (movement['movementComplete'] == 1 || movement['movementComplete'] == true);
    String latestStatus = movement['latestStatus'] ?? '';

    // 1. Status Heading
    String statusHeading = 'Assign';
    Color statusHeadingColor = Colors.blue;

    if (toOther == 'Return') {
      statusHeading = 'Return';
      statusHeadingColor = Colors.orange; // Web: text-warning
    } else if (toOther == 'On Delivery') {
      statusHeading = 'Receive';
      statusHeadingColor = Colors.blue; // Web: text-primary
    } else if (isToStation) {
      statusHeading = 'Change';
      statusHeadingColor = Colors.green; // Web: text-success
    } else {
       // Default 'Assign' (text-info in web, usually light blue/cyan)
       statusHeading = 'Assign';
       statusHeadingColor = Colors.cyan; 
    }

    // 2. Completion Status
    String completionStatus = 'Incomplete';
    Color completionColor = Colors.red;

    if (isMovementComplete && latestStatus != 'Ready To Deploy') {
      completionStatus = 'Complete';
      completionColor = Colors.green; // Web: text-success
    } else if (latestStatus == 'Ready To Deploy') {
      completionStatus = 'Canceled';
      completionColor = Colors.red;
    } else {
      completionStatus = 'Incomplete';
      completionColor = Colors.red;
    }

    return Container(
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(10),
        border: Border.all(color: Colors.grey.shade300),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // Header Row: Status Heading | Dates | Completion
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // Left: Heading
              Expanded(
                flex: 2,
                child: Text(
                  statusHeading,
                  style: TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                    color: statusHeadingColor,
                  ),
                ),
              ),
              // Right: Completion & Expand
               Expanded(
                 flex: 3,
                 child: Column(
                   crossAxisAlignment: CrossAxisAlignment.end,
                   children: [
                     Text(
                       completionStatus,
                       style: TextStyle(
                         color: completionColor,
                         fontWeight: FontWeight.bold,
                         fontSize: 14
                       ),
                     ),
                     const SizedBox(height: 8),
                     _outlinedButton(
                        isInnerExpanded ? 'Hide Details' : 'Show Details',
                        Colors.blue.shade700,
                        onTap: () {
                          setState(() {
                            if (isInnerExpanded) {
                              _expandedMovements.remove(movementId);
                            } else {
                              _expandedMovements.add(movementId);
                            }
                          });
                        },
                      ),
                   ],
                 ),
               )
            ],
          ),
          const SizedBox(height: 8),
          // Dates and Action
          _kvGrid('Send Date', _formatDate(movement['sendDate']), 
                  'Receive Date', action != 'Assign' ? _formatDate(movement['receiveDate']) : 'Not arrive'),
          const SizedBox(height: 4),
           _kvGrid('Action', action, 'Status', latestStatus.isNotEmpty ? latestStatus : toOther),

          AnimatedSize(
            duration: const Duration(milliseconds: 300),
            curve: Curves.fastOutSlowIn,
            child: isInnerExpanded
                ? Column(
              children: [
                const SizedBox(height: 16),
                _buildMovementFlow(movement),
                const SizedBox(height: 12),
                Row(
                  children: [
                    Expanded(child: _actionButton('Remark', isPrimary: true)),
                    const SizedBox(width: 12),
                    Expanded(child: _actionButton('Consignment Note')),
                  ],
                ),
              ],
            )
                : const SizedBox.shrink(),
          ),
        ],
      ),
    );
  }
  
  String _formatDate(String? dateStr) {
    if (dateStr == null || dateStr.isEmpty) return '';
    try {
       final date = DateTime.parse(dateStr);
       // Simple format: YYYY-MM-DD HH:MM:SS
       return '${date.year}-${date.month.toString().padLeft(2,'0')}-${date.day.toString().padLeft(2,'0')} ${date.hour.toString().padLeft(2,'0')}:${date.minute.toString().padLeft(2,'0')}:${date.second.toString().padLeft(2,'0')}';
    } catch (_) {
      return dateStr;
    }
  }

  Widget _buildMovementFlow(Map<String, dynamic> movement) {
    // Start/End Logic from Web App
    // Start Icon
    IconData startIcon = Icons.warehouse;
    bool isToStation = movement['toStation'] != null;
    String toOther = movement['toOther'] ?? '';

    if (isToStation) {
      startIcon = Icons.location_on; // fas fa-map-marker-alt
    } else if (toOther != 'On Delivery') {
      startIcon = Icons.person; // fas fa-user
    } else {
      startIcon = Icons.warehouse; // fas fa-warehouse
    }

    // End Icon
    IconData endIcon = Icons.warehouse;
    bool isLastStation = movement['lastStation'] != null;
    
    if (isLastStation) {
      endIcon = Icons.location_on;
    } else if (toOther != 'On Delivery') {
      endIcon = Icons.warehouse;
    } else {
      endIcon = Icons.person;
    }

    return Container(
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: Colors.grey.shade50,
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: Colors.grey.shade200),
      ),
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              _flowStep(startIcon, 'Start'),
              Column(
                children: [
                  const Icon(Icons.arrow_forward, size: 20, color: Colors.black54),
                  const SizedBox(height: 4),
                  Text(
                    movement['latestStatus'] ?? movement['toOther'] ?? '',
                    style: const TextStyle(fontSize: 12, fontWeight: FontWeight.w600),
                  ),
                ],
              ),
              _flowStep(endIcon, 'End'),
            ],
          ),
          const SizedBox(height: 8),
          const Divider(),
          const SizedBox(height: 8),
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // START COLUMN (Web uses to... variables)
              Expanded(
                child: Column(
                  children: [
                     if (movement['toUserName'] != null) _kvFlow('User:', movement['toUserName']),
                     if (movement['toStationName'] != null) _kvFlow('Station:', movement['toStationName']),
                     if (movement['toStoreName'] != null) _kvFlow('Store:', movement['toStoreName']),
                  ],
                ),
              ),
              const SizedBox(width: 16),
              // END COLUMN (Web uses last... variables)
              Expanded(
                child: Column(
                  children: [
                    if (movement['lastUserName'] != null) _kvFlow('User:', movement['lastUserName']),
                    if (movement['lastStationName'] != null) _kvFlow('Station:', movement['lastStationName']),
                    if (movement['lastStoreName'] != null) _kvFlow('Store:', movement['lastStoreName']),
                  ],
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _flowStep(IconData icon, String label) {
    return Column(
      children: [
        Icon(icon, size: 28, color: Colors.blueGrey),
        const SizedBox(height: 4),
        Text(label, style: const TextStyle(fontWeight: FontWeight.bold)),
      ],
    );
  }

  Widget _kvGrid(String label1, String? value1, String label2, String? value2) {
    return Row(
      children: [
        Expanded(child: _kv(label1, value1)),
        Expanded(child: _kv(label2, value2)),
      ],
    );
  }

  Widget _kv(String label, String? value) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 4.0),
      child: 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: 13, fontWeight: FontWeight.w600),
          ),
        ],
      ),
    );
  }

  Widget _kvFlow(String label, String? value) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(label, style: TextStyle(fontSize: 12, color: Colors.grey.shade600)),
        const SizedBox(width: 4),
        Expanded(
          child: Text(
            value ?? '-',
            style: const TextStyle(fontSize: 12, fontWeight: FontWeight.w600),
          ),
        ),
      ],
    );
  }

  Widget _outlinedButton(String text, Color color, {VoidCallback? onTap}) {
    return InkWell(
      onTap: onTap,
      borderRadius: BorderRadius.circular(6),
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(6),
          border: Border.all(color: color.withOpacity(0.7)),
        ),
        child: Text(
          text,
          style: TextStyle(color: color, fontSize: 12, fontWeight: FontWeight.bold),
        ),
      ),
    );
  }

  Widget _actionButton(String text, {bool isPrimary = false}) {
    return ElevatedButton(
      onPressed: () {},
      style: isPrimary
          ? ElevatedButton.styleFrom(
        backgroundColor: Colors.blue.shade600,
        foregroundColor: Colors.white,
        elevation: 0,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
      )
          : OutlinedButton.styleFrom(
        foregroundColor: Colors.blue.shade700,
        side: BorderSide(color: Colors.blue.shade300),
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
      ),
      child: Text(text),
    );
  }
}
