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 'package:inventory_system/services/api_service.dart';
import 'package:collection/collection.dart';

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

  @override
  State<ItemMovementStationUserScreen> createState() => _ItemMovementStationUserScreenState();
}

class _ItemMovementStationUserScreenState extends State<ItemMovementStationUserScreen> {
  final ItemMovementService _itemMovementService = ItemMovementService();

  bool _isLoading = true;
  String? _errorMessage;
  List<Map<String, dynamic>> _allMovements = [];
  
  // Data Structure: Station Name -> List of Items (which contain history)
  Map<String, List<Map<String, dynamic>>> _groupedByStation = {};
  Map<String, List<Map<String, dynamic>>> _filteredStations = {}; // For display

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

  // Expansion States
  final Set<String> _expandedStations = {};
  final Set<String> _expandedItems = {}; // Key: "StationName_ItemPID"
  final Set<String> _expandedMovements = {}; // Key: MovementID
  final Set<String> _showFullHistory = {}; // Key: "StationName_ItemPID"

  @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;

      // 1. Group by UniqueID first
      final groupedByItem = groupBy(_allMovements, (Map<String, dynamic> m) => m['uniqueID']);
      
      Map<String, List<Map<String, dynamic>>> tempStationMap = {};

      // 2. Process each item (sort, filter history)
      for (var entry in groupedByItem.entries) {
        var movements = entry.value;
        
        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
        int stopIndex = movements.indexWhere((m) => 
          m['toOther'] == 'Return' && (m['movementComplete'] == 1 || m['movementComplete'] == true)
        );

        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) {
           final latest = movements.first;
           // Determine Station
           String station = latest['lastStationName'] ?? latest['toStationName'] ?? 'Self Assigned';
           
           if (!tempStationMap.containsKey(station)) {
             tempStationMap[station] = [];
           }

           tempStationMap[station]!.add({
             'pid': entry.key,
             'uniqueID': latest['uniqueID'],
             'history': movements,
             'productName': latest['productName'],
             'productImage': latest['productImage'],
           });
        }
      }

      // Sort Stations (Self Assigned / Unassigned last)
      var sortedKeys = tempStationMap.keys.toList()..sort((a, b) {
        if (a == 'Self Assigned' || a == 'Unassign Station') return 1;
        if (b == 'Self Assigned' || b == 'Unassign Station') return -1;
        return a.compareTo(b);
      });

      Map<String, List<Map<String, dynamic>>> finalMap = {};
      for (var key in sortedKeys) {
        finalMap[key] = tempStationMap[key]!;
      }

      setState(() {
        _groupedByStation = finalMap;
        _filteredStations = Map.of(_groupedByStation);
        _isLoading = false;
      });

    } catch (e) {
      if (!mounted) return;
      setState(() {
        _errorMessage = 'Failed to load data: $e';
        _isLoading = false;
      });
      debugPrint('Error fetching data: $e');
    }
  }

  void _applyFilter() {
    final query = _searchController.text.trim().toLowerCase();
    if (query.isEmpty) {
      setState(() {
        _filteredStations = Map.of(_groupedByStation);
      });
      return;
    }

    Map<String, List<Map<String, dynamic>>> filtered = {};
    _groupedByStation.forEach((station, items) {
      if (station.toLowerCase().contains(query)) {
        filtered[station] = items;
      }
    });

    setState(() {
      _filteredStations = filtered;
      // Auto expand if searching
      _expandedStations.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: Text(_errorMessage!, style: const TextStyle(color: Colors.red)))
              : Padding(
                  padding: const EdgeInsets.fromLTRB(16, 16, 16, 0),
                  child: Column(
                    children: [
                      _buildSearchBar(),
                      const SizedBox(height: 16),
                      Expanded(
                        child: _filteredStations.isEmpty
                            ? const Center(child: Text('No stations found.'))
                            : RefreshIndicator(
                                onRefresh: _fetchInitialData,
                                child: ListView.builder(
                                  itemCount: _filteredStations.length,
                                  itemBuilder: (context, index) {
                                    String stationName = _filteredStations.keys.elementAt(index);
                                    List<Map<String, dynamic>> items = _filteredStations[stationName]!;
                                    return _buildStationCard(stationName, items);
                                  },
                                ),
                              ),
                      ),
                    ],
                  ),
                ),
      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 _buildStationCard(String stationName, List<Map<String, dynamic>> items) {
    bool isExpanded = _expandedStations.contains(stationName);
    final headerBg = isExpanded ? Colors.white : Colors.white; // Keep white for station card as per web app style (or slight gray)
    // Web app: station-category card.

    return Container(
      margin: const EdgeInsets.only(bottom: 16),
      decoration: BoxDecoration(
        color: stationName == 'Unassign Station' || stationName == 'Self Assigned' ? Colors.grey.shade200 : Colors.white,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: Colors.grey.shade300),
        boxShadow: [BoxShadow(color: Colors.grey.withOpacity(0.1), blurRadius: 4, offset: const Offset(0, 2))]
      ),
      child: Column(
        children: [
          InkWell(
            onTap: () {
              setState(() {
                if (isExpanded) _expandedStations.remove(stationName);
                else _expandedStations.add(stationName);
              });
            },
            child: Padding(
              padding: const EdgeInsets.all(16),
              child: Row(
                children: [
                  Expanded(
                    child: Text(
                      stationName, 
                      style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                    ),
                  ),
                  Text(
                    isExpanded ? 'Hide Items' : 'Show Items',
                    style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: Colors.blue.shade700),
                  ),
                  const SizedBox(width: 4),
                  Icon(
                     isExpanded ? Icons.keyboard_arrow_up : Icons.keyboard_arrow_down,
                     color: Colors.blue.shade700,
                  ),
                ],
              ),
            ),
          ),
          AnimatedSize(
            duration: const Duration(milliseconds: 300),
            child: isExpanded 
              ? Column(
                  children: items.map((item) => _buildItemCard(item, stationName)).toList(),
                )
              : const SizedBox.shrink(),
          )
        ],
      ),
    );
  }

  Widget _buildItemCard(Map<String, dynamic> item, String stationName) {
    final String itemKey = '${stationName}_${item['pid']}';
    bool isExpanded = _expandedItems.contains(itemKey);
    final headerBg = isExpanded ? Colors.blue.shade50 : Colors.white;
    
    return Container(
      margin: const EdgeInsets.fromLTRB(8, 0, 8, 8),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: Colors.grey.shade300),
      ),
      child: Column(
        children: [
          InkWell(
            onTap: () {
               setState(() {
                 if (isExpanded) {
                   _expandedItems.remove(itemKey);
                   _showFullHistory.remove(itemKey);
                 } else {
                   _expandedItems.add(itemKey);
                 }
               });
            },
            child: Container(
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: headerBg,
                borderRadius: BorderRadius.vertical(top: Radius.circular(11), bottom: isExpanded ? Radius.zero : Radius.circular(11)),
              ),
              child: Row(
                children: [
                  Expanded(child: Text('Item : ${item['uniqueID']}', style: const TextStyle(fontWeight: FontWeight.bold))),
                  Text(isExpanded ? 'Hide Details' : 'Show Details', style: TextStyle(fontSize: 12, color: Colors.blue.shade700)),
                  Icon(isExpanded ? Icons.keyboard_arrow_up : Icons.keyboard_arrow_down, color: Colors.blue.shade700),
                ],
              ),
            ),
          ),
          if (isExpanded) _buildExpandedCardContent(item, itemKey),
        ],
      ),
    );
  }

  Widget _buildExpandedCardContent(Map<String, dynamic> item, String itemKey) {
    final List<dynamic> history = item['history'];
    final latestMovement = history.first as Map<String, dynamic>;
    final bool isHistoryVisible = _showFullHistory.contains(itemKey);

    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(itemKey);
                  else _showFullHistory.add(itemKey);
                });
              },
              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),
                  ],
                ),
              ),
            ),
          
          if (isHistoryVisible)
            Padding(
              padding: const EdgeInsets.only(top: 12.0),
              child: Column(
                children: history.skip(1).map((m) => Padding(
                  padding: const EdgeInsets.only(bottom: 12.0),
                  child: _buildMovementDetailCard(m as Map<String, dynamic>),
                )).toList(),
              ),
            ),
        ],
      ),
    );
  }

  // --- Shared Logic from ItemMovementItemUserScreen ---

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

    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'] ?? '';

    String statusHeading = 'Assign';
    Color statusHeadingColor = Colors.blue;

    if (toOther == 'Return') {
      statusHeading = 'Return';
      statusHeadingColor = Colors.orange;
    } else if (toOther == 'On Delivery') {
      statusHeading = 'Receive';
      statusHeadingColor = Colors.blue;
    } else if (isToStation) {
      statusHeading = 'Change';
      statusHeadingColor = Colors.green;
    } else {
       statusHeading = 'Assign';
       statusHeadingColor = Colors.cyan; 
    }

    String completionStatus = 'Incomplete';
    Color completionColor = Colors.red;

    if (isMovementComplete && latestStatus != 'Ready To Deploy') {
      completionStatus = 'Complete';
      completionColor = Colors.green;
    } 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: [
          Row(
            children: [
              Expanded(
                flex: 2,
                child: Text(statusHeading, style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: statusHeadingColor)),
              ),
               Expanded(
                 flex: 3,
                 child: Column(
                   crossAxisAlignment: CrossAxisAlignment.end,
                   children: [
                     Text(completionStatus, style: TextStyle(color: completionColor, fontWeight: FontWeight.bold, fontSize: 14)),
                     const SizedBox(height: 8),
                     InkWell(
                        onTap: () => setState(() => isInnerExpanded ? _expandedMovements.remove(movementId) : _expandedMovements.add(movementId)),
                        borderRadius: BorderRadius.circular(6),
                        child: Container(
                          padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
                          decoration: BoxDecoration(borderRadius: BorderRadius.circular(6), border: Border.all(color: Colors.blue.shade700.withOpacity(0.7))),
                          child: Text(isInnerExpanded ? 'Hide Details' : 'Show Details', style: TextStyle(color: Colors.blue.shade700, fontSize: 12, fontWeight: FontWeight.bold)),
                        ),
                      ),
                   ],
                 ),
               )
            ],
          ),
          const SizedBox(height: 8),
          _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),

          if (isInnerExpanded) ...[
             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')),
               ],
             ),
          ]
        ],
      ),
    );
  }

  Widget _buildMovementFlow(Map<String, dynamic> movement) {
    IconData startIcon = Icons.warehouse;
    bool isToStation = movement['toStation'] != null;
    String toOther = movement['toOther'] ?? '';

    if (isToStation) startIcon = Icons.location_on;
    else if (toOther != 'On Delivery') startIcon = Icons.person;
    else startIcon = Icons.warehouse;

    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: [
              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),
              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) => Column(children: [Icon(icon, size: 28, color: Colors.blueGrey), const SizedBox(height: 4), Text(label, style: const TextStyle(fontWeight: FontWeight.bold))]);
  
  Widget _kvGrid(String l1, String? v1, String l2, String? v2) => Row(children: [Expanded(child: _kv(l1, v1)), Expanded(child: _kv(l2, v2))]);
  
  Widget _kv(String label, String? value) => 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) => 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 _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),
    );
  }

  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 == 'Item') Navigator.pushReplacementNamed(context, '/item_movement_item_user');
            setState(() => _selectedDropdownValue = newValue!);
          },
        ),
      ),
    );
  }

  Widget _buildSearchBar() {
    return TextField(
      controller: _searchController,
      decoration: InputDecoration(
        hintText: 'Search Station',
        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),
      ),
    );
  }

  String _formatDate(String? dateStr) {
    if (dateStr == null || dateStr.isEmpty) return '';
    try {
       final date = DateTime.parse(dateStr);
       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;
    }
  }
}
