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:timeline_tile/timeline_tile.dart';
import 'package:inventory_system/services/api_service.dart'; // Import ApiService for Image.network base URL


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

  @override
  State<ItemMovementItemScreen> createState() => _ItemMovementItemScreenState();
}

class _ItemMovementItemScreenState extends State<ItemMovementItemScreen> {
  // Services
  final ItemMovementService _itemMovementService = ItemMovementService();
  final StationService _stationService = StationService();
  // final UserService _userService = UserService(); // No longer used for data fetching

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

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

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

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

  Future<void> _fetchInitialData() async {
    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 uniqueID
      final grouped = groupBy(movements, (Map<String, dynamic> m) => m['uniqueID']);

      List<Map<String, dynamic>> processedGroupedMovements = grouped.entries.map((entry) {
        final history = entry.value;
        // Sort history by date within each group (latest first)
        history.sort((a, b) {
          final dateA = DateTime.tryParse(a['sendDate'] ?? a['date'] ?? '');
          final dateB = DateTime.tryParse(b['sendDate'] ?? b['date'] ?? '');
          if (dateA == null && dateB == null) return 0;
          if (dateA == null) return 1;
          if (dateB == null) return -1;
          return dateB.compareTo(dateA);
        });

        return {
          'pid': entry.key,
          'history': history,
        };
      }).toList();

      // Sort the grouped movements themselves by the latest movement's date
      processedGroupedMovements.sort((a, b) {
        final latestA = (a['history'] as List<dynamic>).first;
        final latestB = (b['history'] as List<dynamic>).first;
        final dateA = DateTime.tryParse(latestA['sendDate'] ?? latestA['date'] ?? '') ?? DateTime(0);
        final dateB = DateTime.tryParse(latestB['sendDate'] ?? latestB['date'] ?? '') ?? DateTime(0);
        return dateB.compareTo(dateA); // Descending order
      });

      setState(() {
        _groupedMovements = processedGroupedMovements;
        _filteredMovements = List.of(_groupedMovements);
        _isLoading = false;
      });
    } catch (e) {
      if (!mounted) return;
      setState(() {
        _errorMessage = 'Failed to load data: $e';
        _isLoading = false;
      });
      debugPrint('Error fetching initial data for ItemMovementItemScreen: $e');
    }
  }

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

  void _applyFilter() {
    final query = _searchController.text.trim().toLowerCase();
    setState(() {
      _filteredMovements = _groupedMovements
          .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: 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: _filteredMovements.isEmpty
                              ? const Center(child: Text('No items found.'))
                              : ListView.builder(
                                  itemCount: _filteredMovements.length,
                                  itemBuilder: (context, index) {
                                    final item = _filteredMovements[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) 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 ? _buildHistoryTimeline(history) : const SizedBox.shrink(),
          ),
        ],
      ),
    );
  }

  Widget _buildHistoryTimeline(List<dynamic> history) {
    return Padding(
      padding: const EdgeInsets.only(top: 16.0),
      child: Column(
        children: List.generate(history.length, (index) {
          final event = history[index] as Map<String, dynamic>;
          return TimelineTile(
            alignment: TimelineAlign.manual,
            lineXY: 0.1,
            isFirst: index == 0,
            isLast: index == history.length - 1,
            beforeLineStyle: const LineStyle(color: Colors.blue, thickness: 2),
            indicatorStyle: IndicatorStyle(
              width: 20,
              color: Colors.blue,
              indicator: Container(
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  color: Colors.white,
                  border: Border.all(color: Colors.blue, width: 2),
                ),
                child: index == 0 ? null : const Center(child: CircleAvatar(radius: 5, backgroundColor: Colors.blue)),
              ),
            ),
            endChild: Container(
              constraints: const BoxConstraints(minHeight: 80),
              margin: const EdgeInsets.only(left: 16, bottom: 16, right: 8),
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(8),
                border: Border.all(color: Colors.grey.shade200),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    event['date'] ?? 'N/A',
                    style: TextStyle(color: Colors.grey.shade600, fontSize: 12),
                  ),
                  const SizedBox(height: 6),
                  Text(
                    'Status: ${event['latestStatus'] ?? 'N/A'}',
                    style: const TextStyle(fontWeight: FontWeight.w600, color: Colors.black87),
                  ),
                ],
              ),
            ),
          );
        }),
      ),
    );
  }

  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 == 'Station') {
              Navigator.pushReplacementNamed(context, '/item_movement_station');
            }
          },
        ),
      ),
    );
  }

  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 : $pid',
                      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 statusColor = _statusColor(movement['action'] ?? '');
    final movementId = movement['id'].toString();
    final bool isInnerExpanded = _expandedMovements.contains(movementId);

    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(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Expanded(
                child: Text(
                  movement['action'] ?? '-',
                  style: TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                    color: statusColor,
                  ),
                ),
              ),
              _chip(movement['latestStatus'] ?? 'N/A', Colors.green.shade700),
              const SizedBox(width: 8),
              _outlinedButton(
                isInnerExpanded ? 'Hide Details' : 'Show Details',
                Colors.blue.shade700,
                onTap: () {
                  setState(() {
                    if (isInnerExpanded) {
                      _expandedMovements.remove(movementId);
                    } else {
                      _expandedMovements.add(movementId);
                    }
                  });
                },
              ),
            ],
          ),
          const SizedBox(height: 12),
          _kvGrid('Send Date', movement['action'] == 'Register' ? movement['date'] : movement['sendDate'], 'Receive Date', movement['receiveDate']),
          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(),
          ),
        ],
      ),
    );
  }

  Widget _buildMovementFlow(Map<String, dynamic> movement) {
    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(Icons.person, 'Start'),
              Column(
                children: [
                  const Icon(Icons.arrow_forward, size: 20, color: Colors.black54),
                  const SizedBox(height: 4),
                  Text(
                    movement['latestStatus'] ?? '',
                    style: const TextStyle(fontSize: 12, fontWeight: FontWeight.w600),
                  ),
                ],
              ),
              _flowStep(Icons.factory, 'End'),
            ],
          ),
          const SizedBox(height: 8),
          const Divider(),
          const SizedBox(height: 8),
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Expanded(
                child: Column(
                  children: [
                    _kvFlow('Last User:', movement['lastUserName']),
                    _kvFlow('Station:', movement['lastStationName']),
                    _kvFlow('Store:', movement['lastStoreName']),
                  ],
                ),
              ),
              const SizedBox(width: 16),
              Expanded(
                child: Column(
                  children: [
                    _kvFlow('From User:', movement['toUserName']),
                    _kvFlow('Station:', movement['toStationName']),
                    _kvFlow('Store:', movement['toStoreName']),
                  ],
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Color _statusColor(String status) {
    switch (status.toLowerCase()) {
      case 'stock out': return const Color(0xFFD32F2F);
      case 'stock in': return const Color(0xFF1976D2);
      case 'assign': return const Color(0xFF2E7D32);
      default: return Colors.grey.shade800;
    }
  }

  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 _chip(String text, Color color) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
      decoration: BoxDecoration(
        color: color.withOpacity(0.1),
        borderRadius: BorderRadius.circular(6),
      ),
      child: Text(
        text,
        style: TextStyle(color: color, fontSize: 12, fontWeight: FontWeight.bold),
      ),
    );
  }

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