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/product_request_service.dart'; // Import ProductRequestService
import 'package:inventory_system/services/session_manager.dart'; // Import SessionManager
import 'package:inventory_system/services/api_service.dart'; // Import ApiService

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

  @override
  State<InvMasterToInvMasterScreen> createState() => _InvMasterToInvMasterScreenState();
}

class _InvMasterToInvMasterScreenState extends State<InvMasterToInvMasterScreen>
    with SingleTickerProviderStateMixin {
  final ProductRequestService _productRequestService = ProductRequestService(); // Service instance
  List<Map<String, dynamic>> _requests = []; // To store fetched requests
  bool _isLoading = true;
  String? _errorMessage;
  int? _currentUserId;
  List<dynamic> _currentUserRoles = [];
  int? _currentUserStore;

  int _selectedIndex = 0;
  late TabController _tabController;

  // Dropdown state
  String _selectedDropdownValue = 'Inventory Master → Inventory Master';
  final List<String> _dropdownOptions = const [
    'Technician → Inventory Master',
    'Inventory Master → Inventory Master',
  ];

  // Expanded state per card
  int? _expandedIndex;
  Key _tabViewKey = UniqueKey();

  // Search controllers
  final TextEditingController _allSearchController = TextEditingController();
  final TextEditingController _outgoingSearchController = TextEditingController();
  final TextEditingController _incomingSearchController = TextEditingController();
  final TextEditingController _completeSearchController = TextEditingController();

  // Filtered lists
  late List<Map<String, dynamic>> _allFiltered;
  late List<Map<String, dynamic>> _outgoingFiltered;
  late List<Map<String, dynamic>> _incomingFiltered;
  late List<Map<String, dynamic>> _completeFiltered;

  @override
  void initState() {
    super.initState();
    _fetchInitialData();

    _allSearchController.addListener(_applyFilters);
    _outgoingSearchController.addListener(_applyFilters);
    _incomingSearchController.addListener(_applyFilters);
    _completeSearchController.addListener(_applyFilters);

    _tabController = TabController(length: 4, 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 allRequests = await _productRequestService.fetchProductRequests();
      final currentUser = SessionManager.instance.currentUser;

      if (currentUser == null) {
        setState(() {
          _errorMessage = 'Could not retrieve user session. Please log out and log back in.';
          _isLoading = false;
        });
        return;
      }

      _currentUserId = currentUser['id'];
      _currentUserRoles = currentUser['role'] as List<dynamic>? ?? [];
      _currentUserStore = currentUser['store'];

      List<Map<String, dynamic>> userRequests;
      if (_currentUserRoles.contains("Super Admin") || _currentUserRoles.contains("System Admin")) {
        userRequests = allRequests;
      } else if (_currentUserRoles.contains("Inventory Master")) {
        if (_currentUserStore == null) {
          userRequests = allRequests;
        } else {
          userRequests = allRequests.where((r) {
            final assignStore = r['assignStoreItem'];
            final fromStore = r['fromStoreItem'];
            return (assignStore != null && assignStore.toString() == _currentUserStore.toString()) ||
                   (fromStore != null && fromStore.toString() == _currentUserStore.toString());
          }).toList();
        }
      } else {
        userRequests = allRequests.where((r) {
          return r['userId'].toString() == _currentUserId.toString();
        }).toList();
      }

      setState(() {
        _requests = userRequests;
        _applyFilters();
        _isLoading = false;
      });
    } catch (e) {
      if (!mounted) return;
      setState(() {
        _errorMessage = 'Failed to load data: $e';
        _isLoading = false;
      });
    }
  }

  @override
  void dispose() {
    _allSearchController.removeListener(_applyFilters);
    _outgoingSearchController.removeListener(_applyFilters);
    _incomingSearchController.removeListener(_applyFilters);
    _completeSearchController.removeListener(_applyFilters);

    _allSearchController.dispose();
    _outgoingSearchController.dispose();
    _incomingSearchController.dispose();
    _completeSearchController.dispose();

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

  bool _matchesQuery(Map<String, dynamic> m, String q) {
    if (q.isEmpty) return true;
    final keys = [
      'productName', 'requestID', 'status', 'productCategory', 'userName',
      'stationName', 'remarkMasterInv', 'remarkUser', 'requestDate','approvalDate'
    ];
    for (final k in keys) {
      final v = m[k]?.toString().toLowerCase();
      if (v != null && v.contains(q)) return true;
    }
    return false;
  }

  bool _isMasterRequest(Map<String, dynamic> m) {
    final val = m['assignStoreItem'];
    return val != null && val != 0;
  }

  void _applyFilters() {
    final allQuery = _allSearchController.text.toLowerCase();
    final outgoingQuery = _outgoingSearchController.text.toLowerCase();
    final incomingQuery = _incomingSearchController.text.toLowerCase();
    final completeQuery = _completeSearchController.text.toLowerCase();

    setState(() {
      // Filter each list based on its own search controller.
      _outgoingFiltered = _requests.where((item) {
        return item['status'] == 'Requested' &&
            item['userId'].toString() == _currentUserId.toString() &&
            _isMasterRequest(item) &&
            _matchesQuery(item, outgoingQuery);
      }).toList();

      _incomingFiltered = _requests.where((item) {
        return item['status'] == 'Requested' &&
            item['fromStoreItem'].toString() == _currentUserStore.toString() &&
            _isMasterRequest(item) &&
            _matchesQuery(item, incomingQuery);
      }).toList();

      _completeFiltered = _requests.where((item) {
        return item['status'] != 'Requested' &&
            _isMasterRequest(item) &&
            _matchesQuery(item, completeQuery);
      }).toList();

      // For "All", combine the already filtered lists from the other tabs.
      final combined = <Map<String, dynamic>>[
        ..._outgoingFiltered,
        ..._incomingFiltered,
        ..._completeFiltered,
      ];

      // Remove duplicates using requestID
      final uniqueIds = <dynamic>{};
      final uniqueItems = combined.where((item) {
        final isNew = uniqueIds.add(item['requestID']);
        return isNew;
      }).toList();
      
      // Then, apply the "All" tab's own search filter.
      _allFiltered = uniqueItems.where((item) => _matchesQuery(item, allQuery)).toList();

      _expandedIndex = null;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF5F5F7),
      appBar: TitleBar(
        title: 'Product Request',
        actions: [
          Padding(
            padding: const EdgeInsets.only(right: 8),
            child: ConstrainedBox(
              constraints: const BoxConstraints(maxWidth: 120),
              child: PopupMenuButton<String>(
                tooltip: 'Switch section',
                onSelected: (newValue) {
                  if (newValue == 'Technician → Inventory Master') {
                    Navigator.pushReplacementNamed(context, '/product_request_t_to_im');
                  } else if (newValue == 'Inventory Master → Inventory Master') {
                    // stay
                  }
                  setState(() {
                    _selectedDropdownValue = newValue;
                  });
                },
                itemBuilder: (context) => _dropdownOptions
                    .map((v) => PopupMenuItem<String>(value: v, child: Text(v)))
                    .toList(),
                child: Container(
                  padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                  decoration: BoxDecoration(
                    color: Colors.grey.shade200,
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Text(
                        _selectedDropdownValue.startsWith('Technician') ? 'Tech → IM' : 'IM → IM',
                        style: const TextStyle(fontSize: 12, color: Colors.black87),
                        overflow: TextOverflow.ellipsis,
                      ),
                      const SizedBox(width: 4),
                      const Icon(Icons.keyboard_arrow_down, size: 18, color: Colors.black87),
                    ],
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
      drawer: const NavBar(isAdmin: true, selectedScreen: AppScreen.productRequest),
      body: Column(
        children: [
          Container(
            color: Colors.white,
            child: TabBar(
              controller: _tabController,
              onTap: (_) {
                setState(() {
                  _expandedIndex = null;
                  _tabViewKey = UniqueKey();
                });
              },
              labelColor: Colors.purple.shade800,
              unselectedLabelColor: Colors.grey.shade600,
              indicatorColor: Colors.purple.shade800,
              indicatorWeight: 3,
              tabs: const [
                Tab(text: 'All'),
                Tab(text: 'Outgoing'),
                Tab(text: 'Incoming'),
                Tab(text: 'Complete'),
              ],
            ),
          ),
          Expanded(
            child: _isLoading
                ? const Center(child: CircularProgressIndicator())
                : _errorMessage != null
                    ? Center(child: Text(_errorMessage!))
                    : TabBarView(
                        controller: _tabController,
                        key: _tabViewKey,
                        children: [
                          _buildTabPage(
                              controller: _allSearchController,
                              items: _allFiltered,
                              tabKey: 'all'),
                          _buildTabPage(
                              controller: _outgoingSearchController,
                              items: _outgoingFiltered,
                              tabKey: 'outgoing'),
                          _buildTabPage(
                              controller: _incomingSearchController,
                              items: _incomingFiltered,
                              tabKey: 'incoming'),
                          _buildTabPage(
                              controller: _completeSearchController,
                              items: _completeFiltered,
                              tabKey: 'complete'),
                        ],
                      ),
          ),
        ],
      ),
      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 tabKey,
  }) {
    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: Column(
        children: [
          Row(
            children: [
              ElevatedButton.icon(
                onPressed: () {
                  Navigator.pushNamed(context, '/product_request_form').then((_) => _fetchInitialData());
                },
                icon: const Icon(Icons.add, size: 18),
                label: const Text('Add Request'),
                style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.purple.shade100,
                  foregroundColor: Colors.black87,
                  padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
                ),
              ),
              const SizedBox(width: 16),
              Expanded(
                child: TextField(
                  controller: controller,
                  onChanged: (_) => _applyFilters(),
                  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();
                            },
                          )
                        : null,
                    filled: true,
                    fillColor: Colors.white,
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(12),
                      borderSide: BorderSide.none,
                    ),
                  ),
                ),
              ),
            ],
          ),
          const SizedBox(height: 16),
          Expanded(
            child: ListView.builder(
              itemCount: items.length,
              itemBuilder: (context, index) =>
                  _buildRequestCard(items[index], index, tabKey),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildRequestCard(Map<String, dynamic> item, int index, String tabKey) {
    final isExpanded = _expandedIndex == index;
    final String imageUrl = item['productImage'] ?? '';

    String status = _getStatus(item);
    Color color = _getStatusColor(status);

    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: [
                  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,
                                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['productId']?.toString() ?? '-',
                        style: const TextStyle(
                            fontFamily: 'monospace', fontSize: 12),
                      ),
                    ],
                  ),
                  const SizedBox(width: 16),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Row(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Expanded(
                              child: Text(
                                item['productName'] ?? '-',
                                style: const TextStyle(
                                    fontSize: 16,
                                    fontWeight: FontWeight.bold),
                              ),
                            ),
                            Container(
                              padding: const EdgeInsets.symmetric(
                                  horizontal: 10, vertical: 4),
                              decoration: BoxDecoration(
                                color: color.withOpacity(0.2),
                                borderRadius: BorderRadius.circular(8),
                                border: Border.all(color: color),
                              ),
                              child: Text(
                                status,
                                style: TextStyle(
                                  fontWeight: FontWeight.w700,
                                  color: color,
                                ),
                              ),
                            ),
                          ],
                        ),
                        const SizedBox(height: 4),
                        Text('ID: ${item['requestID'] ?? '-'}',
                            style: TextStyle(color: Colors.grey.shade600)),
                        const SizedBox(height: 2),
                        Text(item['requestDate'] ?? '-',
                            style: TextStyle(color: Colors.grey.shade600)),
                      ],
                    ),
                  ),
                ],
              ),
            ),
            Container(
              padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 12),
              decoration: BoxDecoration(
                border: Border(top: BorderSide(color: Colors.grey.shade200)),
              ),
              child: Row(
                children: [
                  Expanded(
                    child: Center(
                      child: InkWell(
                        onTap: () {
                          setState(() {
                            _expandedIndex = isExpanded ? null : index;
                          });
                        },
                        child: Row(
                          mainAxisSize: MainAxisSize.min,
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Text(
                              isExpanded ? 'Less Details' : 'More Details',
                              style: TextStyle(
                                fontSize: 14,
                                fontWeight: FontWeight.w600,
                                color: Colors.blue.shade600,
                              ),
                            ),
                            const SizedBox(width: 4),
                            Icon(
                              isExpanded
                                  ? Icons.keyboard_arrow_up
                                  : Icons.keyboard_arrow_down,
                              color: Colors.blue.shade600,
                              size: 20,
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
            AnimatedSize(
              duration: const Duration(milliseconds: 300),
              curve: Curves.fastOutSlowIn,
              child: isExpanded
                  ? _buildDetailsSection(item)
                  : const SizedBox.shrink(),
            ),
          ],
        ),
      ),
    );
  }

  String _getStatus(Map<String, dynamic> item) {
    if (item['status'] == 'Requested') {
      final bool isIncoming = item['fromStoreItem'] == _currentUserStore;
      if (isIncoming) {
        return 'Incoming';
      }
      final bool isOutgoing = item['userId'] == _currentUserId;
      if (isOutgoing) {
        return 'Outgoing';
      }
    }
    return item['status'] ?? 'N/A';
  }

  Color _getStatusColor(String status) {
    switch (status) {
      case 'Outgoing':
        return Colors.blue.shade400;
      case 'Incoming':
        return Colors.orange.shade400;
      case 'Approved':
      case 'Complete':
        return Colors.green.shade500;
      case 'Rejected':
        return Colors.red.shade400;
      case 'Requested':
        return Colors.purple.shade400;
      default:
        return Colors.grey.shade400;
    }
  }

  Widget _buildDetailsSection(Map<String, dynamic> item) {
    final tiles = <Widget>[
      _detailTile('Requested by User', item['userName'] ?? 'N/A'),
      _detailTile('Requested by Station', item['stationName'] ?? 'N/A'),
      _detailTile('Product Category', item['productCategory'] ?? 'N/A'),
      _detailTile('Request Quantity', item['requestQuantity']?.toString() ?? 'N/A'),
      _detailTile('Inventory Master Remark', item['remarkMasterInv'] ?? 'N/A'),
      _detailTile('User Remark', item['remarkUser'] ?? 'N/A'),
      _buildDocumentTile(item['document']),
      _detailTile('Request Date', item['requestDate'] ?? 'N/A'),
      if (item['approvalDate'] != null)
        _detailTile('Approval Date', item['approvalDate']),
      if (item['rejectedDate'] != null)
        _detailTile('Rejected Date', item['rejectedDate'])
    ];

    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 spacing = 16.0;
          final tileWidth = (constraints.maxWidth - (spacing * 2)) / 3; // 3 columns
          return Wrap(
            spacing: spacing,
            runSpacing: 12,
            children: tiles.map((w) => SizedBox(width: tileWidth, child: w)).toList(),
          );
        },
      ),
    );
  }

  Widget _detailTile(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,
        ),
      ],
    );
  }

  void _showDocument(String docPath) {
    showDialog(
      context: context,
      builder: (ctx) => Dialog(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            AppBar(
              title: const Text('Document'),
              leading: IconButton(
                icon: const Icon(Icons.close),
                onPressed: () => Navigator.pop(ctx),
              ),
              elevation: 0,
              backgroundColor: Colors.transparent,
              foregroundColor: Colors.black,
            ),
            InteractiveViewer(
              child: Image.network(
                ApiService.baseUrl + docPath,
                fit: BoxFit.contain,
                errorBuilder: (ctx, err, stack) => const Padding(
                  padding: EdgeInsets.all(20.0),
                  child: Column(
                    children: [
                      Icon(Icons.broken_image, size: 50, color: Colors.grey),
                      Text('Failed to load image'),
                    ],
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildDocumentTile(String? docPath) {
    final hasDoc = docPath != null && docPath.isNotEmpty;
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          'Document/Picture',
          style: TextStyle(
            fontSize: 12,
            color: Colors.grey.shade600,
            fontWeight: FontWeight.w500,
          ),
        ),
        const SizedBox(height: 4),
        hasDoc
            ? InkWell(
                onTap: () => _showDocument(docPath),
                child: Text(
                  'Show',
                  style: TextStyle(
                    fontSize: 14,
                    fontWeight: FontWeight.w600,
                    color: Colors.blue.shade700,
                    decoration: TextDecoration.underline,
                  ),
                ),
              )
            : const Text(
                'No Document',
                style: TextStyle(
                  fontSize: 14,
                  fontWeight: FontWeight.w600,
                  color: Colors.black87,
                ),
              ),
      ],
    );
  }
}

