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

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

  @override
  State<TechnicianToInvMasterScreen> createState() => _TechnicianToInvMasterScreenState();
}

class _TechnicianToInvMasterScreenState extends State<TechnicianToInvMasterScreen>
    with SingleTickerProviderStateMixin {
  final ProductRequestService _productRequestService = ProductRequestService();
  List<Map<String, dynamic>> _requests = [];
  bool _isLoading = true;
  String? _errorMessage;
  int? _currentUserId;
  List<dynamic> _currentUserRoles = [];

  int _selectedIndex = 0;

  late TabController _tabController;

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

  int? _expandedIndex;
  Key _tabViewKey = UniqueKey();

  final TextEditingController _allSearchController = TextEditingController();
  final TextEditingController _pendingSearchController = TextEditingController();
  final TextEditingController _completeSearchController = TextEditingController();
  final TextEditingController _rejectedSearchController = TextEditingController();
  final TextEditingController _remarkController = TextEditingController();

  late List<Map<String, dynamic>> _allFiltered;
  late List<Map<String, dynamic>> _pendingFiltered;
  late List<Map<String, dynamic>> _completeFiltered;
  late List<Map<String, dynamic>> _rejectedFiltered;

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

    _allSearchController.addListener(_applyFilters);
    _pendingSearchController.addListener(_applyFilters);
    _completeSearchController.addListener(_applyFilters);
    _rejectedSearchController.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;
      }

      final currentUserId = currentUser['id'];
      final currentUserRoles = currentUser['role'] as List<dynamic>? ?? [];
      final 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")) {
        userRequests = allRequests;
      } 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);
    _pendingSearchController.removeListener(_applyFilters);
    _completeSearchController.removeListener(_applyFilters);
    _rejectedSearchController.removeListener(_applyFilters);

    _allSearchController.dispose();
    _pendingSearchController.dispose();
    _completeSearchController.dispose();
    _rejectedSearchController.dispose();
    _remarkController.dispose();

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

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

  void _applyFilters() {
    final allQuery = _allSearchController.text.toLowerCase();
    final pendingQuery = _pendingSearchController.text.toLowerCase();
    final completeQuery = _completeSearchController.text.toLowerCase();
    final rejectedQuery = _rejectedSearchController.text.toLowerCase();

    setState(() {
      _allFiltered = _requests.where((m) => _isTechRequest(m) && _matchesQuery(m, allQuery)).toList();
      _pendingFiltered = _requests
          .where((m) => m['status'] == 'Requested' && _isTechRequest(m) && _matchesQuery(m, pendingQuery))
          .toList();
      _completeFiltered = _requests
          .where((m) => m['status'] == 'Approved' && _isTechRequest(m) && _matchesQuery(m, completeQuery))
          .toList();
      _rejectedFiltered = _requests
          .where((m) => m['status'] == 'Rejected' && _isTechRequest(m) && _matchesQuery(m, rejectedQuery))
          .toList();
      _expandedIndex = null;
    });
  }

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

  void _applyAllFilter() {
    final q = _allSearchController.text.toLowerCase();
    setState(() {
      _allFiltered = _requests.where((m) => _isTechRequest(m) && _matchesQuery(m, q)).toList();
      _expandedIndex = null;
    });
  }

  void _applyPendingFilter() {
    final q = _pendingSearchController.text.toLowerCase();
    setState(() {
      _pendingFiltered = _requests
          .where((m) => m['status'] == 'Requested' && _isTechRequest(m) && _matchesQuery(m, q))
          .toList();
      _expandedIndex = null;
    });
  }

  void _applyCompleteFilter() {
    final q = _completeSearchController.text.toLowerCase();
    setState(() {
      _completeFiltered = _requests
          .where((m) => m['status'] == 'Approved' && _isTechRequest(m) && _matchesQuery(m, q))
          .toList();
      _expandedIndex = null;
    });
  }

  void _applyRejectedFilter() {
    final q = _rejectedSearchController.text.toLowerCase();
    setState(() {
      _rejectedFiltered = _requests
          .where((m) => m['status'] == 'Rejected' && _isTechRequest(m) && _matchesQuery(m, q))
          .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 == 'Inventory Master → Inventory Master') {
                    Navigator.pushReplacementNamed(context, '/product_request_im_to_im');
                  } else if (newValue == 'Technician → 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; // collapse on tap change
                  _tabViewKey = UniqueKey();
                });
              },
              labelColor: Colors.purple.shade800,
              unselectedLabelColor: Colors.grey.shade600,
              indicatorColor: Colors.purple.shade800,
              indicatorWeight: 3,
              tabs: const [
                Tab(text: 'All'),
                Tab(text: 'Pending'),
                Tab(text: 'Complete'),
                Tab(text: 'Rejected'),
              ],
            ),
          ),
          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: _pendingSearchController, items: _pendingFiltered, tabKey: 'pending'),
                          _buildTabPage(controller: _completeSearchController, items: _completeFiltered, tabKey: 'complete'),
                          _buildTabPage(controller: _rejectedSearchController, items: _rejectedFiltered, tabKey: 'rejected'),
                        ],
                      ),
          ),
        ],
      ),
      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: [
          TextField(
            controller: controller,
            onChanged: (_) {
              switch (tabKey) {
                case 'all':
                  _applyAllFilter();
                  break;
                case 'pending':
                  _applyPendingFilter();
                  break;
                case 'complete':
                  _applyCompleteFilter();
                  break;
                case 'rejected':
                  _applyRejectedFilter();
                  break;
              }
            },
            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();
                        switch (tabKey) {
                          case 'all':
                            _applyAllFilter();
                            break;
                          case 'pending':
                            _applyPendingFilter();
                            break;
                          case 'complete':
                            _applyCompleteFilter();
                            break;
                          case 'rejected':
                            _applyRejectedFilter();
                            break;
                        }
                      },
                    )
                  : 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),
            ),
          ),
        ],
      ),
    );
  }

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

    Color statusColor(String status) {
      switch (status) {
        case 'Requested':
          return Colors.blue.shade800;
        case 'Approved':
          return Colors.green.shade700;
        case 'Rejected':
          return Colors.red.shade400;
        default:
          return Colors.grey.shade400;
      }
    }

    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: [
                  // Image + Product code under it
                  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),
                  // Main Info
                  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),
                              ),
                            ),
                            // Status badge
                            Container(
                              padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
                              decoration: BoxDecoration(
                                color: statusColor(item['status'] ?? '').withOpacity(0.2),
                                borderRadius: BorderRadius.circular(8),
                                border: Border.all(color: statusColor(item['status'] ?? '')),
                              ),
                              child: Text(
                                item['status'] ?? '-',
                                style: TextStyle(
                                  fontWeight: FontWeight.w700,
                                  color: statusColor(item['status'] ?? ''),
                                ),
                              ),
                            ),
                          ],
                        ),
                        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)),
                      ],
                    ),
                  ),
                ],
              ),
            ),
            // Actions row: More Details + Approve/Reject
            Container(
              padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 12),
              decoration: BoxDecoration(
                border: Border(top: BorderSide(color: Colors.grey.shade200)),
              ),
              child: Row(
                children: [
                  // Center the More Details when NOT pending; keep left-aligned for Pending so approve/reject stay visible
                  Builder(builder: (context) {
                    final isPending = (item['status'] ?? '') == 'Requested';
                    final moreDetailsWidget = InkWell(
                      onTap: () {
                        setState(() {
                          _expandedIndex = isExpanded ? null : index; // only one at a time
                        });
                      },
                      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,
                          ),
                        ],
                      ),
                    );

                    return Expanded(
                      child: isPending
                          ? Align(alignment: Alignment.centerLeft, child: moreDetailsWidget)
                          : Center(child: moreDetailsWidget),
                    );
                  }),
                  // Only add spacing and buttons when Pending
                  if ((item['status'] ?? '') == 'Requested') ...[
                    const SizedBox(width: 8),
                    ElevatedButton(
                      onPressed: () => _showRemarkDialog('Approve', item['requestID']),
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.green.shade200,
                        foregroundColor: Colors.black,
                        elevation: 0,
                        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
                      ),
                      child: const Text('Approve'),
                    ),
                    const SizedBox(width: 8),
                    ElevatedButton(
                      onPressed: () => _showRemarkDialog('Reject', item['requestID']),
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.red.shade200,
                        foregroundColor: Colors.black,
                        elevation: 0,
                        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
                      ),
                      child: const Text('Reject'),
                    ),
                  ],
                ],
              ),
            ),
            AnimatedSize(
              duration: const Duration(milliseconds: 300),
              curve: Curves.fastOutSlowIn,
              child: isExpanded ? _buildDetailsSection(item) : const SizedBox.shrink(),
            ),
          ],
        ),
      ),
    );
  }

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

  void _showRemarkDialog(String action, int requestId) {
    _remarkController.clear();
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('$action Request'),
        content: TextField(
          controller: _remarkController,
          decoration: const InputDecoration(hintText: 'Enter remark (optional)'),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('Cancel'),
          ),
          ElevatedButton(
            onPressed: () async {
              final remark = _remarkController.text;
              Navigator.pop(context);
              try {
                if (action == 'Approve') {
                  await _productRequestService.approveRequest(requestId, remark);
                } else {
                  await _productRequestService.rejectRequest(requestId, remark);
                }
                _fetchInitialData();
              } catch (e) {
                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(content: Text('Failed to $action request: $e')),
                );
              }
            },
            child: Text(action),
          ),
        ],
      ),
    );
  }

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