import 'package:flutter/material.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:inventory_system/services/product_service.dart';
import 'package:inventory_system/screens/admin/product/product_form.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';

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

  @override
  State<ProductScreen> createState() => _ProductScreenState();
}

class _ProductScreenState extends State<ProductScreen> {
  int _selectedIndex = 0;
  final ProductService _productService = ProductService();
  late Future<List<dynamic>> _productsFuture;

  String _selectedFilter = 'All';
  final List<String> _filters = ['All', 'Asset', 'Disposable', 'Part'];

  List<dynamic> _allProducts = [];
  List<dynamic> _filteredProducts = [];
  final TextEditingController _searchController = TextEditingController();

  int? _expandedIndex;

  @override
  void initState() {
    super.initState();
    _productsFuture = _fetchProducts();
    _searchController.addListener(_applyFilters);
  }

  Future<List<dynamic>> _fetchProducts() async {
    try {
      final products = await _productService.fetchProducts();

      // This sort function now uses the correct key 'productName'
      products.sort((a, b) {
        final nameA = a['productName'] as String? ?? '';
        final nameB = b['productName'] as String? ?? '';
        return nameA.toLowerCase().compareTo(nameB.toLowerCase());
      });

      if (mounted) {
        setState(() {
          _allProducts = products;
          _applyFilters(); // This will use the new sorted list
        });
      }
      return products;
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('Failed to load products: $e'), backgroundColor: Colors.red),
        );
      }
      rethrow;
    }
  }

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

  void _applyFilters() {
    final query = _searchController.text.toLowerCase();
    setState(() {
      _filteredProducts = _allProducts.where((product) {
        final name = product['productName'].toString().toLowerCase();
        final model = product['modelNo'].toString().toLowerCase();
        final category = (product['category'] ?? '').toString().toLowerCase();

        final matchesSearch = name.contains(query) || model.contains(query);
        final matchesFilter = _selectedFilter == 'All' || category == _selectedFilter.toLowerCase();
        return matchesSearch && matchesFilter;
      }).toList();
      _expandedIndex = null;
    });
  }

  void _handleDelete(int productId, String productName) async {
    try {
      await _productService.deleteProduct(productId);
      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('Product deleted successfully'), backgroundColor: Colors.green),
      );
      _fetchProducts();
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('Failed to delete product: $e'), backgroundColor: Colors.red),
        );
      }
    }
  }

  void _confirmDelete(int productId, String productName) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
        title: const Text('Delete Product'),
        content: Text('Are you sure you want to delete $productName?'),
        actions: [
          TextButton(onPressed: () => Navigator.pop(context), child: const Text('Cancel')),
          TextButton(
            onPressed: () {
              Navigator.pop(context);
              _handleDelete(productId, productName);
            },
            child: const Text('Delete', style: TextStyle(color: Colors.red)),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF5F5F7),
      appBar: const TitleBar(title: 'Product'),
      drawer: const NavBar(isAdmin: true, selectedScreen: AppScreen.product),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            Row(
              children: [
                ElevatedButton.icon(
                  onPressed: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(builder: (context) => const ProductFormScreen()),
                    ).then((success) {
                      if (success == true) _fetchProducts();
                    });
                  },
                  icon: const Icon(Icons.add, size: 18),
                  label: const Text('Add Product'),
                  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: 12),
                Expanded(
                  child: TextField(
                    controller: _searchController,
                    decoration: InputDecoration(
                      hintText: 'Search',
                      hintStyle: TextStyle(color: Colors.grey.shade400),
                      prefixIcon: const Icon(Icons.search),
                      filled: true,
                      fillColor: Colors.white,
                      border: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: BorderSide.none),
                    ),
                  ),
                ),
              ],
            ),
            const SizedBox(height: 16),
            SizedBox(
              height: 36,
              child: ListView.separated(
                scrollDirection: Axis.horizontal,
                itemCount: _filters.length,
                separatorBuilder: (context, index) => const SizedBox(width: 8),
                itemBuilder: (context, index) {
                  final filter = _filters[index];
                  final isSelected = _selectedFilter == filter;
                  return ChoiceChip(
                    label: Text(filter),
                    selected: isSelected,
                    onSelected: (selected) {
                      if (selected) {
                        setState(() {
                          _selectedFilter = filter;
                          _applyFilters();
                        });
                      }
                    },
                    backgroundColor: Colors.white,
                    selectedColor: Colors.purple.shade100,
                    labelStyle: TextStyle(color: isSelected ? Colors.purple.shade900 : Colors.black54, fontWeight: FontWeight.bold),
                    shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(18), side: BorderSide(color: isSelected ? Colors.purple.shade100 : Colors.grey.shade300)),
                  );
                },
              ),
            ),
            const SizedBox(height: 16),
            Expanded(
              child: RefreshIndicator(
                onRefresh: _fetchProducts,
                child: FutureBuilder<List<dynamic>>(
                  future: _productsFuture,
                  builder: (context, snapshot) {
                    if (snapshot.connectionState == ConnectionState.waiting && _allProducts.isEmpty) {
                      return const Center(child: CircularProgressIndicator());
                    }
                    if (snapshot.hasError && _allProducts.isEmpty) {
                      return Center(child: Text('Error: ${snapshot.error}'));
                    }
                    if (_filteredProducts.isEmpty) {
                      return const Center(child: Text('No products found.'));
                    }

                    return ListView.builder(
                      itemCount: _filteredProducts.length,
                      itemBuilder: (context, index) {
                        final product = _filteredProducts[index];
                        final isExpanded = _expandedIndex == index;

                        return Padding(
                          padding: const EdgeInsets.only(bottom: 12),
                          child: Slidable(
                            key: Key(product['productId'].toString()),
                            endActionPane: ActionPane(
                              motion: const ScrollMotion(),
                              extentRatio: 0.45,
                              children: [
                                SlidableAction(
                                  onPressed: (context) {
                                    Navigator.push(
                                      context,
                                      MaterialPageRoute(builder: (context) => ProductFormScreen(product: product)),
                                    ).then((success) {
                                      if (success == true) _fetchProducts();
                                    });
                                  },
                                  backgroundColor: Colors.blue,
                                  foregroundColor: Colors.white,
                                  label: 'Edit',
                                  icon: Icons.edit,
                                ),
                                SlidableAction(
                                  onPressed: (context) => _confirmDelete(product['productId'], product['productName']),
                                  backgroundColor: Colors.red,
                                  foregroundColor: Colors.white,
                                  label: 'Delete',
                                  icon: Icons.delete,
                                  borderRadius: const BorderRadius.horizontal(right: Radius.circular(16)),
                                ),
                              ],
                            ),
                            child: Container(
                              decoration: BoxDecoration(
                                color: Colors.white,
                                borderRadius: BorderRadius.circular(16),
                                border: Border.all(color: Colors.grey.shade300, width: 1),
                              ),
                              child: Column(
                                children: [
                                  Padding(
                                    padding: const EdgeInsets.all(16),
                                    child: Row(
                                      children: [
                                        Builder(
                                          builder: (context) {
                                            // 1. Get the relative image path from the API response
                                            final String? imagePath = product['imageProduct'];

                                            // 2. Construct the full URL
                                            // We get the base URL from your environment variables
                                            final String baseUrl = 'https://dev9.pstw.com.my';
                                            final String fullImageUrl = (imagePath != null && imagePath.isNotEmpty) ? baseUrl + imagePath : '';

                                            return Container(
                                              width: 80,
                                              height: 80,
                                              clipBehavior: Clip.antiAlias, // Ensures the image respects the border radius
                                              decoration: BoxDecoration(
                                                color: Colors.grey.shade200,
                                                borderRadius: BorderRadius.circular(12),
                                                border: Border.all(color: Colors.grey.shade300),
                                              ),
                                              // 3. Conditionally display the image or a placeholder
                                              child: (fullImageUrl.isNotEmpty)
                                              // If a valid URL exists, show the network image
                                                  ? Image.network(
                                                fullImageUrl,
                                                fit: BoxFit.cover, // Ensures the image fills the container
                                                // Shows a loading spinner while the image is fetching
                                                loadingBuilder: (context, child, loadingProgress) {
                                                  if (loadingProgress == null) return child;
                                                  return const Center(
                                                    child: SizedBox(
                                                      width: 20,
                                                      height: 20,
                                                      child: CircularProgressIndicator(strokeWidth: 2),
                                                    ),
                                                  );
                                                },
                                                // Shows an error icon if the image fails to load
                                                errorBuilder: (context, error, stackTrace) {
                                                  // Log the error for debugging
                                                  debugPrint('Failed to load image: $fullImageUrl, Error: $error');
                                                  return const Icon(Icons.broken_image, color: Colors.grey, size: 40);
                                                },
                                              )
                                              // If no URL, show a placeholder icon
                                                  : const Icon(Icons.image_not_supported, color: Colors.grey, size: 40),
                                            );
                                          },
                                        ),
                                        const SizedBox(width: 16),
                                        Expanded(
                                          child: Column(
                                            crossAxisAlignment: CrossAxisAlignment.start,
                                            children: [
                                              Text(product['productName'] ?? 'N/A', style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w600)),
                                              const SizedBox(height: 4),
                                              Text(product['productShortName'] ?? 'N/A', style: TextStyle(fontSize: 13, color: Colors.grey.shade600, fontStyle: FontStyle.italic)),
                                            ],
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                  InkWell(
                                    onTap: () => setState(() => _expandedIndex = isExpanded ? null : index),
                                    child: Container(
                                      padding: const EdgeInsets.symmetric(vertical: 12),
                                      decoration: BoxDecoration(
                                        border: Border(top: BorderSide(color: Colors.grey.shade200)),
                                      ),
                                      child: Row(
                                        mainAxisAlignment: MainAxisAlignment.center,
                                        children: [
                                          Text(isExpanded ? 'Less Details' : 'More Details', style: TextStyle(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
                                        ? Container(
                                            padding: const EdgeInsets.all(16),
                                            decoration: BoxDecoration(
                                              color: Colors.grey.shade50,
                                              border: Border(top: BorderSide(color: Colors.grey.shade200)),
                                            ),
                                            child: GridView(
                                              gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                                                crossAxisCount: 2,
                                                crossAxisSpacing: 16,
                                                mainAxisSpacing: 12,
                                                childAspectRatio: 2.5,
                                              ),
                                              shrinkWrap: true,
                                              physics: const NeverScrollableScrollPhysics(),
                                              children: [
                                                _buildDetailItem('Model No', product['modelNo'] ?? 'N/A'),
                                                _buildDetailItem('Manufacturer', product['manufacturer']?['manufacturerName'] ?? 'N/A'),
                                                _buildDetailItem('Category', product['category'] ?? 'N/A'),
                                                _buildDetailItem('Quantity', product['quantityProduct']?.toString() ?? '0'),
                                              ],
                                            ),
                                          )
                                        : const SizedBox.shrink(),
                                  ),
                                ],
                              ),
                            ),
                          ),
                        );
                      },
                    );
                  },
                ),
              ),
            ),
          ],
        ),
      ),
      bottomNavigationBar: BottomNavBar(
        selectedIndex: _selectedIndex,
        onItemTapped: (index) {
          if (index == 0) {
            Navigator.pop(context);
          } else {
            setState(() {
              _selectedIndex = index;
            });
          }
        },
      ),
    );
  }

  Widget _buildDetailItem(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: 2),
        Text(value, style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w600, color: Colors.black87)),
      ],
    );
  }
}
