import 'package:flutter/material.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:inventory_system/screens/bottom_nav_bar.dart';
import 'package:inventory_system/screens/nav_bar.dart';
import 'package:inventory_system/screens/title_bar.dart';
import 'package:inventory_system/screens/user/product_request/product_request_user_form.dart';
import 'package:inventory_system/services/product_request_service.dart';
import 'package:inventory_system/services/api_service.dart';

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

  @override
  State<ProductRequestUserScreen> createState() =>
      _ProductRequestUserScreenState();
}

class _ProductRequestUserScreenState extends State<ProductRequestUserScreen> {
  int _selectedIndex = 0;
  String _selectedFilter = 'All';
  final List<String> _filters = ['All', 'Requested', 'Approve', 'Rejected'];

  final ProductRequestService _productRequestService = ProductRequestService();
  List<Map<String, dynamic>> _allProducts = [];
  List<Map<String, dynamic>> _filteredProducts = [];
  bool _isLoading = true;
  String? _errorMessage;

  final TextEditingController _searchController = TextEditingController();
  int? _expandedIndex;

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

  Future<void> _fetchInitialData() async {
    setState(() {
      _isLoading = true;
      _errorMessage = null;
    });
    try {
      final requests = await _productRequestService.fetchProductRequests();
      
      // Sort by requestDate descending (latest first)
      requests.sort((a, b) {
        final dateA = DateTime.tryParse(a['requestDate'] ?? '') ?? DateTime(0);
        final dateB = DateTime.tryParse(b['requestDate'] ?? '') ?? DateTime(0);
        return dateB.compareTo(dateA);
      });

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

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

  void _applyFilters() {
    final q = _searchController.text.toLowerCase();
    setState(() {
      _filteredProducts = _allProducts.where((p) {
        final name = (p['productName'] ?? '').toString().toLowerCase();
        final status = (p['status'] ?? '').toString();
        final matchesSearch = q.isEmpty || name.contains(q);
        
        bool matchesFilter = false;
        if (_selectedFilter == 'All') {
          matchesFilter = true;
        } else if (_selectedFilter == 'Requested') {
          matchesFilter = status == 'Requested';
        } else if (_selectedFilter == 'Approve') {
          // Approve tab shows Approved or Complete, but NOT Rejected
          matchesFilter = (status == 'Approved' || status == 'Complete') && status != 'Rejected';
        } else if (_selectedFilter == 'Rejected') {
          matchesFilter = status == 'Rejected';
        }
            
        return matchesSearch && matchesFilter;
      }).toList();
      _expandedIndex = null;
    });
  }

  Future<void> _deleteRequest(int index) async {
    final prod = _filteredProducts[index];
    final requestId = prod['requestID'];

    if (requestId == null) return;

    final confirmed = await showDialog<bool>(
      context: context,
      builder: (ctx) => AlertDialog(
        title: const Text('Delete Request'),
        content: Text('Delete "${prod['productName']}"?'),
        actions: [
          TextButton(
              onPressed: () => Navigator.pop(ctx, false),
              child: const Text('Cancel')),
          TextButton(
            onPressed: () => Navigator.pop(ctx, true),
            child: const Text('Delete', style: TextStyle(color: Colors.red)),
          ),
        ],
      ),
    );

    if (confirmed == true) {
      try {
        await _productRequestService.deleteRequest(requestId); 
        _fetchInitialData(); 
      } catch (e) {
        if(mounted) {
             ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('Failed to delete: $e')));
        }
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF5F5F7),
      appBar: const TitleBar(title: 'Product Request'),
      drawer: const NavBar(isAdmin: false, selectedScreen: AppScreen.productRequestUser),
      body: _isLoading
          ? const Center(child: CircularProgressIndicator())
          : _errorMessage != null
              ? Center(child: Text(_errorMessage!))
              : Padding(
                  padding: const EdgeInsets.all(16.0),
                  child: Column(
                    children: [
                      _buildSearchBarAndFilters(),
                      const SizedBox(height: 16),
                      Expanded(
                        child: _filteredProducts.isEmpty
                            ? _buildEmptyState()
                            : RefreshIndicator(
                                onRefresh: _fetchInitialData,
                                child: ListView.builder(
                                  itemCount: _filteredProducts.length,
                                  itemBuilder: (context, index) {
                                    return _buildRequestCard(_filteredProducts[index], index);
                                  },
                                ),
                              ),
                      ),
                    ],
                  ),
                ),
      bottomNavigationBar: BottomNavBar(
        selectedIndex: _selectedIndex,
        // isAdmin: false,
        onItemTapped: (index) {
          setState(() {
            _selectedIndex = index;
          });
        },
      ),
    );
  }

  Widget _buildSearchBarAndFilters() {
    return Column(
      children: [
        Row(
          children: [
            ElevatedButton.icon(
              onPressed: () => Navigator.push(
                context,
                MaterialPageRoute(
                    builder: (_) => const ProductRequestUserForm()),
              ).then((_) => _fetchInitialData()),
              icon: const Icon(Icons.add, size: 18),
              label: const Text('Add Request'),
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.purple.shade100,
                foregroundColor: Colors.black87,
                elevation: 0,
                padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(12)),
              ),
            ),
            const SizedBox(width: 12),
            Expanded(
              child: TextField(
                controller: _searchController,
                decoration: InputDecoration(
                  hintText: 'Search',
                  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,
                  ),
                  contentPadding: const EdgeInsets.symmetric(horizontal: 16),
                ),
              ),
            ),
          ],
        ),
        const SizedBox(height: 16),
        SizedBox(
          height: 36,
          child: ListView.separated(
            scrollDirection: Axis.horizontal,
            itemCount: _filters.length,
            separatorBuilder: (context, index) => const SizedBox(width: 4),
            itemBuilder: (context, index) {
              final filter = _filters[index];
              final isSelected = _selectedFilter == filter;
              return InkWell(
                onTap: () {
                  setState(() {
                    _selectedFilter = filter;
                    _applyFilters();
                  });
                },
                borderRadius: BorderRadius.circular(18),
                child: Container(
                  padding: const EdgeInsets.symmetric(horizontal: 20),
                  decoration: BoxDecoration(
                    color: isSelected ? Colors.purple.shade100 : Colors.white,
                    borderRadius: BorderRadius.circular(18),
                    border: Border.all(
                      color: isSelected
                          ? Colors.purple.shade100
                          : Colors.grey.shade300,
                    ),
                  ),
                  child: Center(
                    child: Text(
                      filter,
                      style: TextStyle(
                        color: isSelected
                            ? Colors.purple.shade900
                            : Colors.black54,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                ),
              );
            },
          ),
        ),
      ],
    );
  }

  Widget _buildSectionHeader(String title) {
    return Padding(
      padding: const EdgeInsets.only(top: 8.0, bottom: 16.0, left: 4.0),
      child: Text(
        title,
        style: const TextStyle(
            fontSize: 18, fontWeight: FontWeight.bold, color: Colors.black87),
      ),
    );
  }

  Widget _buildEmptyState() {
    return Center(
      child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
        Icon(Icons.search_off, size: 64, color: Colors.grey.shade400),
        const SizedBox(height: 12),
        Text('No requests found',
            style: TextStyle(color: Colors.grey.shade600)),
      ]),
    );
  }

  Widget _buildRequestCard(Map<String, dynamic> product, int index) {
    final isExpanded = _expandedIndex == index;
    final status = product['status'];
    final isApprove = status == 'Approved' || status == 'Complete'; 
    final isRejected = status == 'Rejected';
    final imageUrl = product['productPicture'] ?? product['productImage'];

    Color statusColor;
    if (isApprove) {
      statusColor = Colors.green.shade800;
    } else if (isRejected) {
      statusColor = Colors.red.shade800;
    } else {
      statusColor = Colors.yellow.shade800; // Requested
    }
    Color statusBg = isApprove
        ? Colors.green.shade200
        : (isRejected ? Colors.red.shade200 : Colors.yellow.shade500);

    return Padding(
      padding: const EdgeInsets.only(bottom: 12),
      child: Slidable(
        key: Key(product['requestID'].toString()),
        endActionPane: (status == 'Requested')
            ? ActionPane(
                motion: const BehindMotion(),
                extentRatio: 0.25,
                children: [
                  SlidableAction(
                    onPressed: (_) => _deleteRequest(index),
                    backgroundColor: Colors.red,
                    foregroundColor: Colors.white,
                    icon: Icons.delete,
                    label: 'Delete',
                    borderRadius: const BorderRadius.only(
                      topRight: Radius.circular(16),
                      bottomRight: Radius.circular(16),
                    ),
                  ),
                ],
              )
            : null,
        child: Container(
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(16),
            border: Border.all(color: Colors.grey.shade300),
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              Padding(
                padding: const EdgeInsets.all(16),
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Container(
                      width: 80,
                      height: 80,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(12),
                        color: Colors.grey.shade100,
                        border: Border.all(color: Colors.grey.shade300),
                      ),
                      child: imageUrl != null && imageUrl.toString().isNotEmpty
                          ? ClipRRect(
                              borderRadius: BorderRadius.circular(12),
                              child: Image.network(
                                ApiService.baseUrl + imageUrl,
                                fit: BoxFit.cover,
                                errorBuilder: (ctx, err, stack) => const Icon(
                                    Icons.broken_image,
                                    color: Colors.grey),
                              ),
                            )
                          : const Icon(Icons.image, color: Colors.grey),
                    ),
                    const SizedBox(width: 16),
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Row(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Expanded(
                                child: Text(product['productName'] ?? 'Unknown',
                                    style: const TextStyle(
                                        fontSize: 16,
                                        fontWeight: FontWeight.bold)),
                              ),
                              Container(
                                padding: const EdgeInsets.symmetric(
                                    horizontal: 10, vertical: 4),
                                decoration: BoxDecoration(
                                  color: statusBg,
                                  borderRadius: BorderRadius.circular(8),
                                ),
                                child: Text(
                                  status ?? 'N/A',
                                  style: TextStyle(
                                    fontSize: 12,
                                    fontWeight: FontWeight.bold,
                                    color: statusColor,
                                  ),
                                ),
                              ),
                            ],
                          ),
                          const SizedBox(height: 4),
                          Text('ID: ${product['requestID'] ?? '-'}',
                              style: TextStyle(
                                  fontSize: 13, color: Colors.grey.shade600)),
                          const SizedBox(height: 2),
                          Text(product['requestDate'] ?? '-',
                              style: TextStyle(
                                  fontSize: 13, color: Colors.grey.shade600)),
                        ],
                      ),
                    )
                  ],
                ),
              ),
              InkWell(
                onTap: () =>
                    setState(() => _expandedIndex = isExpanded ? null : index),
                child: Container(
                  padding: const EdgeInsets.symmetric(vertical: 10),
                  decoration: BoxDecoration(
                      border:
                          Border(top: BorderSide(color: Colors.grey.shade200))),
                  child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Text(isExpanded ? 'Less Details' : 'More Details',
                            style: TextStyle(
                                fontSize: 14,
                                fontWeight: FontWeight.w600,
                                color: Colors.blue.shade700)),
                        const SizedBox(width: 6),
                        Icon(
                            isExpanded
                                ? Icons.keyboard_arrow_up
                                : Icons.keyboard_arrow_down,
                            color: Colors.blue.shade700,
                            size: 20)
                      ]),
                ),
              ),
              AnimatedSize(
                duration: const Duration(milliseconds: 150),
                curve: Curves.easeInOut,
                child: isExpanded
                    ? _buildDetailsSection(product, isApprove)
                    : const SizedBox.shrink(),
              ),
            ],
          ),
        ),
      ),
    );
  }

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

  Widget _buildDetailsSection(Map<String, dynamic> product, bool isApprove) {
    final List<Widget> tiles = [];
    final station = product['stationName'] ?? 'Self Assign';
    
    if (isApprove) {
      // Approve layout
      return Container(
        width: double.infinity,
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          color: Colors.grey.shade50,
          border: Border(top: BorderSide(color: Colors.grey.shade200)),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Expanded(
                    child: _detailTile(
                        'Product Category', product['productCategory'] ?? '-')),
                const SizedBox(width: 16),
                Expanded(
                    child: _detailTile('Request Quantity',
                        product['requestQuantity']?.toString() ?? '-')),
                const SizedBox(width: 16),
                Expanded(
                    child: _detailTile('Station Deploy', station)),
              ],
            ),
            const SizedBox(height: 12),
            Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Expanded(
                    child: _buildDocumentTile(product['document'])),
                const SizedBox(width: 16),
                Expanded(
                    child: _detailTile(
                        'Remark', product['remarkUser'] ?? '-')),
                const SizedBox(width: 16),
                Expanded(
                    child: _detailTile(
                        'Remark (Master)', product['remarkMasterInv'] ?? '-')),
              ],
            ),
            const SizedBox(height: 12),
            Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Expanded(
                    child: _detailTile(
                        'Approval Date', product['approvalDate'] ?? '-')),
              ],
            ),
          ],
        ),
      );
    } else {
      // Requested layout
      tiles.addAll([
        _detailTile('Product Category', product['productCategory'] ?? '-'),
        _detailTile('Request Quantity', product['requestQuantity']?.toString() ?? '-'),
        _detailTile('Station Deploy', station),
        _buildDocumentTile(product['document']),
        _detailTile('Remark', product['remarkUser'] ?? '-'),
      ]);

      return Container(
        width: double.infinity,
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          color: Colors.grey.shade50,
          border: Border(top: BorderSide(color: Colors.grey.shade200)),
        ),
        child: LayoutBuilder(
          builder: (context, constraints) {
            final maxW = constraints.maxWidth;
            final int columns = 3;
            const double spacing = 16;
            final double tileW = (maxW - spacing * (columns - 1)) / columns;
            // rough estimate for aspect ratio
            final double childAspectRatio = 2.5;

            return GridView(
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: columns,
                crossAxisSpacing: spacing,
                mainAxisSpacing: 12,
                childAspectRatio: childAspectRatio,
              ),
              shrinkWrap: true,
              primary: false,
              physics: const NeverScrollableScrollPhysics(),
              children: tiles,
            );
          },
        ),
      );
    }
  }

  Widget _detailTile(String label, String value) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          label,
          style: TextStyle(
            fontSize: 12,
            color: Colors.grey.shade600,
            fontWeight: FontWeight.w500,
          ),
        ),
        const SizedBox(height: 4),
        Text(
          value,
          style: const TextStyle(
            fontSize: 14,
            fontWeight: FontWeight.w600,
            color: Colors.black87,
          ),
          // overflow: TextOverflow.ellipsis, 
          softWrap: true,
        ),
      ],
    );
  }
}
