import 'package:flutter/material.dart';
import 'package:inventory_system/services/item_movement_service.dart';
import 'package:inventory_system/services/station_service.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:collection/collection.dart';
// import 'package:inventory_system/services/session_manager.dart'; // No longer needed for client-side filtering
import 'package:intl/intl.dart';

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

  @override
  State<ItemMovementStationScreen> createState() => _ItemMovementStationScreenState();
}

class _ItemMovementStationScreenState extends State<ItemMovementStationScreen> {
  // Services
  final ItemMovementService _itemMovementService = ItemMovementService();
  final StationService _stationService = StationService();

  // State
  bool _isLoading = true;
  String? _errorMessage;
  List<Map<String, dynamic>> _stationsData = [];
  List<Map<String, dynamic>> _filteredStations = [];

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

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

  Future<void> _fetchInitialData() async {
    setState(() {
      _isLoading = true;
      _errorMessage = null;
    });
    try {
      // ItemMovementService now handles role-based filtering, so we directly get the relevant movements
      final movements = (await _itemMovementService.fetchItemMovements()).cast<Map<String, dynamic>>();
      if (!mounted) return;

      // Group movements by item to find the latest status
      final groupedByItem = groupBy(movements, (Map<String, dynamic> m) => m['uniqueID']);

      final latestMovements = groupedByItem.values.map((itemMovements) {
        itemMovements.sort((a, b) {
          final dateA = DateTime.tryParse(a['date'] ?? '');
          final dateB = DateTime.tryParse(b['date'] ?? '');
          if (dateA == null && dateB == null) return 0;
          if (dateA == null) return 1;
          if (dateB == null) return -1;
          return dateB.compareTo(dateA);
        });
        return itemMovements.first;
      }).toList();

      // Group the relevant items by their current station
      final groupedByStation = groupBy(latestMovements, (Map<String, dynamic> m) => m['toStationName'] ?? 'Unassigned');

      List<Map<String, dynamic>> processedStations = groupedByStation.entries.map((entry) {
        // Sort items within each station by date
        final List<Map<String, dynamic>> itemsInStation = entry.value.map((m) {
          return {
            'code': m['uniqueID'] ?? 'N/A',
            'description': m['productName'] ?? 'N/A',
            'date': m['date'] ?? 'N/A',
          };
        }).toList();

        itemsInStation.sort((a, b) {
          final dateA = DateTime.tryParse(a['date'] ?? '') ?? DateTime(0);
          final dateB = DateTime.tryParse(b['date'] ?? '') ?? DateTime(0);
          return dateB.compareTo(dateA); // Descending order
        });

        return {
          'stationName': entry.key,
          'id': entry.key, // Use name as unique ID for state
          'items': itemsInStation,
        };
      }).toList();

      // Sort stations themselves by the date of the latest item within each station (descending)
      processedStations.sort((a, b) {
        final latestItemA = (a['items'] as List<dynamic>).first;
        final latestItemB = (b['items'] as List<dynamic>).first;
        final dateA = DateTime.tryParse(latestItemA['date'] ?? '') ?? DateTime(0);
        final dateB = DateTime.tryParse(latestItemB['date'] ?? '') ?? DateTime(0);
        return dateB.compareTo(dateA);
      });

      setState(() {
        _stationsData = processedStations;
        _filteredStations = List.of(_stationsData);
        _isLoading = false;
      });
    } catch (e) {
      if (!mounted) return;
      setState(() {
        _errorMessage = 'Failed to load data: $e';
        _isLoading = false;
      });
      debugPrint('Error fetching initial data for ItemMovementStationScreen: $e');
    }
  }

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

  void _applyFilter() {
    final query = _searchController.text.trim().toLowerCase();
    setState(() {
      _filteredStations = _stationsData
          .where((station) => (station['stationName'] as String).toLowerCase().contains(query))
          .toList();
      _expandedIndex = null;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF5F5F7),
      appBar: TitleBar(
        title: 'Item Movement',
        actions: [_buildDropdown()],
      ),
      drawer: const NavBar(isAdmin: true, selectedScreen: AppScreen.itemMovement),
      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: 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.'))
                              : ListView.builder(
                                  itemCount: _filteredStations.length,
                                  itemBuilder: (context, index) {
                                    final station = _filteredStations[index];
                                    final isExpanded = _expandedIndex == index;
                                    return _buildStationCard(station, index, isExpanded);
                                  },
                                ),
                        ),
                      ],
                    ),
                  ),
                ),
      bottomNavigationBar: BottomNavBar(
        selectedIndex: _selectedIndex,
        onItemTapped: (index) {
          if (index == 0) Navigator.pop(context);
          else if (index == 1) Navigator.pushNamed(context, '/scan');
          else setState(() => _selectedIndex = index);
        },
      ),
    );
  }

  Widget _buildStationCard(Map<String, dynamic> station, int index, bool isExpanded) {
    final headerBg = isExpanded ? Colors.blue.shade50 : Colors.white;
    final headerBorder = isExpanded ? Colors.blue.shade200 : Colors.grey.shade300;

    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(() {
                _expandedIndex = isExpanded ? null : index;
              });
            },
            child: Container(
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: headerBg,
                borderRadius: isExpanded
                    ? const BorderRadius.vertical(top: Radius.circular(11))
                    : BorderRadius.circular(11),
              ),
              child: Row(
                children: [
                  const Icon(Icons.location_on_outlined, color: Colors.black54),
                  const SizedBox(width: 12),
                  Expanded(
                    child: Text(
                      station['stationName']!,
                      style: const TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                  Text(
                    isExpanded ? 'Hide' : 'Show',
                    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 ? _buildExpandedTable(station) : const SizedBox.shrink(),
          ),
        ],
      ),
    );
  }

  Widget _buildExpandedTable(Map<String, dynamic> station) {
    final List<dynamic> items = station['items'];

    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(8),
      decoration: BoxDecoration(
        border: Border(top: BorderSide(color: Colors.grey.shade300)),
      ),
      child: DataTable(
        columnSpacing: 20,
        headingRowHeight: 40,
        dataRowMinHeight: 48,
        dataRowMaxHeight: 56,
        headingTextStyle: const TextStyle(
          fontWeight: FontWeight.bold,
          color: Colors.black87,
        ),
        columns: const [
          DataColumn(label: Text('Code')),
          DataColumn(label: Text('Description')),
          DataColumn(label: Text('Date')),
        ],
        rows: items.map((item) {
          final dateString = item['date'] as String?;
          final formattedDate = dateString != null && dateString.isNotEmpty
              ? DateFormat('yyyy-MM-dd').format(DateTime.parse(dateString))
              : 'N/A';
          return DataRow(
            cells: [
              DataCell(Text(item['code']!)),
              DataCell(Text(item['description']!)),
              DataCell(Text(formattedDate)),
            ],
          );
        }).toList(),
      ),
    );
  }

  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');
            }
            if (newValue == 'Item') {
              Navigator.pushReplacementNamed(context, '/item_movement_item');
            }
          },
        ),
      ),
    );
  }

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