import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../api_service.dart';
import '../models/product.dart';

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

  @override
  State<ProductListScreen> createState() => _ProductListScreenState();
}

class _ProductListScreenState extends State<ProductListScreen> {
  final _scrollController = ScrollController();
  final _searchController = TextEditingController();
  
  List<Product> _products = [];
  bool _isLoading = false;
  int _page = 1;
  bool _hasMore = true;
  bool _isGridView = true;
  String _searchQuery = '';

  @override
  void initState() {
    super.initState();
    _fetchProducts();
    _scrollController.addListener(_onScroll);
  }

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

  void _onScroll() {
    if (_scrollController.position.pixels >= _scrollController.position.maxScrollExtent - 200 &&
        !_isLoading &&
        _hasMore) {
      _fetchProducts();
    }
  }

  Future<void> _fetchProducts({bool refresh = false}) async {
    if (_isLoading) return;
    
    setState(() {
      _isLoading = true;
      if (refresh) {
        _page = 1;
        _products.clear();
        _hasMore = true;
      }
    });

    try {
      final newProducts = await Provider.of<ApiService>(context, listen: false)
          .getProducts(page: _page, search: _searchQuery);

      setState(() {
        _products.addAll(newProducts);
        _page++;
        if (newProducts.isEmpty || newProducts.length < 10) { // Assuming page size 10
          _hasMore = false;
        }
      });
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Failed to load products: $e')),
      );
    } finally {
      setState(() => _isLoading = false);
    }
  }

  void _handleSearch(String query) {
    if (_searchQuery == query) return;
    _searchQuery = query;
    _fetchProducts(refresh: true);
  }

  void _deleteProduct(int id) async {
    final confirmed = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('Delete Product'),
        content: const Text('Are you sure you want to delete this product?'),
        actions: [
          TextButton(onPressed: () => Navigator.pop(context, false), child: const Text('Cancel')),
          TextButton(
            onPressed: () => Navigator.pop(context, true), 
            child: const Text('Delete', style: TextStyle(color: Colors.red))
          ),
        ],
      ),
    );

    if (confirmed == true) {
      try {
        await Provider.of<ApiService>(context, listen: false).deleteProduct(id);
        setState(() {
          _products.removeWhere((p) => p.id == id);
        });
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('Product deleted')),
        );
      } catch (e) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('Failed to delete: $e')),
        );
      }
    }
  }

  Widget _buildStockDisplay(Product product) {
    if (product.manageStock) {
        return Container(
            padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
            decoration: BoxDecoration(
                color: (product.stockQuantity ?? 0) > 0 ? Colors.green.withValues(alpha: 0.9) : Colors.red.withValues(alpha: 0.9),
                borderRadius: BorderRadius.circular(12),
            ),
            child: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                    const Icon(Icons.inventory_2, size: 12, color: Colors.white),
                    const SizedBox(width: 4),
                    Text(
                        '${product.stockQuantity ?? 0} (Parent)',
                        style: const TextStyle(fontSize: 10, fontWeight: FontWeight.bold, color: Colors.white),
                    ),
                ],
            ),
        );
    }
    
    if (product.type == ProductType.variable) {
        return FutureBuilder<List<Variation>>(
            future: Provider.of<ApiService>(context, listen: false).fetchVariations(product.id),
            builder: (context, snapshot) {
                if (!snapshot.hasData) {
                    return Container(
                         padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                         color: Colors.transparent,
                         child: const SizedBox(width: 10, height: 10, child: CircularProgressIndicator(strokeWidth: 2)),
                    );
                }
                
                final variations = snapshot.data!;
                int totalStock = 0;
                for (var v in variations) {
                    if (v.manageStock) {
                        totalStock += v.stockQuantity ?? 0;
                    }
                }
                
                return Container(
                    padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                    decoration: BoxDecoration(
                        color: Colors.blue.withValues(alpha: 0.9),
                        borderRadius: BorderRadius.circular(12),
                    ),
                    child: Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                            const Icon(Icons.layers, size: 12, color: Colors.white),
                            const SizedBox(width: 4),
                            Text(
                                '$totalStock (Vars)',
                                style: const TextStyle(fontSize: 10, fontWeight: FontWeight.bold, color: Colors.white),
                            ),
                        ],
                    ),
                );
            },
        );
    }

    return Container(
        padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
        decoration: BoxDecoration(
            color: product.stockStatus == 'instock' 
                ? Colors.green.withValues(alpha: 0.9) 
                : Colors.red.withValues(alpha: 0.9),
            borderRadius: BorderRadius.circular(12),
        ),
        child: Text(
            product.stockStatus == 'instock' ? 'In Stock' : 'Out',
            style: const TextStyle(fontSize: 10, fontWeight: FontWeight.bold, color: Colors.white),
        ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Inventory'),
        actions: [
          IconButton(
            icon: Icon(_isGridView ? Icons.view_list : Icons.grid_view),
            onPressed: () => setState(() => _isGridView = !_isGridView),
          ),
          IconButton(
            icon: const Icon(Icons.logout),
            onPressed: () => Provider.of<ApiService>(context, listen: false).logout(),
          )
        ],
        bottom: PreferredSize(
          preferredSize: const Size.fromHeight(60),
          child: Padding(
            padding: const EdgeInsets.all(8.0),
            child: TextField(
              controller: _searchController,
              onSubmitted: _handleSearch,
              decoration: InputDecoration(
                hintText: 'Search products...',
                prefixIcon: const Icon(Icons.search),
                suffixIcon: IconButton(
                  icon: const Icon(Icons.clear),
                  onPressed: () {
                    _searchController.clear();
                    _handleSearch('');
                  },
                ),
              ),
            ),
          ),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () async {
            await Navigator.pushNamed(context, '/product/new');
            _fetchProducts(refresh: true);
        },
        backgroundColor: Colors.blue,
        child: const Icon(Icons.add),
      ),
      body: RefreshIndicator(
        onRefresh: () => _fetchProducts(refresh: true),
        child: _products.isEmpty && !_isLoading
            ? const Center(child: Text('No products found'))
            : GridView.builder(
                controller: _scrollController,
                padding: const EdgeInsets.all(8),
                gridDelegate: _isGridView 
                    ? const SliverGridDelegateWithMaxCrossAxisExtent(
                        maxCrossAxisExtent: 300,
                        childAspectRatio: 0.75,
                        crossAxisSpacing: 16,
                        mainAxisSpacing: 16,
                    )
                    : const SliverGridDelegateWithMaxCrossAxisExtent(
                        maxCrossAxisExtent: 1000,
                        childAspectRatio: 4, // More wide for list Items
                        crossAxisSpacing: 16,
                        mainAxisSpacing: 8,
                        mainAxisExtent: 90, // Fixed height for list items
                    ),
                itemCount: _products.length + (_hasMore ? 1 : 0),
                itemBuilder: (context, index) {
                  if (index == _products.length) {
                    return const Center(child: CircularProgressIndicator());
                  }
                  final product = _products[index];
                  return _isGridView ? _buildGridItem(product) : _buildListItem(product);
                },
              ),
      ),
    );
  }

  Widget _buildGridItem(Product product) {
    final imageUrl = product.images.isNotEmpty ? product.images[0].src : null;
    return GestureDetector(
      onTap: () async {
        await Navigator.pushNamed(context, '/product/edit', arguments: product);
        _fetchProducts(refresh: true);
      },
      child: Card(
        elevation: 4,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
        color: const Color(0xFF1F2937),
        clipBehavior: Clip.antiAlias,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Expanded(
              flex: 3,
              child: Stack(
                fit: StackFit.expand,
                children: [
                  imageUrl != null
                      ? Image.network(
                          imageUrl,
                          fit: BoxFit.cover,
                          errorBuilder: (context, error, stackTrace) =>
                              const Center(child: Icon(Icons.broken_image, size: 40)),
                        )
                      : const Center(child: Icon(Icons.image, size: 40, color: Colors.grey)),
                  Positioned(
                    top: 8,
                    right: 8,
                    child: _buildStockDisplay(product),
                  ),
                  if (product.type != ProductType.simple)
                    Positioned(
                      top: 8,
                      left: 8,
                      child: Container(
                        padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                        decoration: BoxDecoration(
                          color: Colors.blue.withValues(alpha: 0.9),
                          borderRadius: BorderRadius.circular(12),
                        ),
                        child: Text(
                          product.type.toString().split('.').last.toUpperCase(),
                          style: const TextStyle(
                              fontSize: 9, fontWeight: FontWeight.bold, color: Colors.white),
                        ),
                      ),
                    ),
                ],
              ),
            ),
            Expanded(
              flex: 2,
              child: Padding(
                padding: const EdgeInsets.all(8.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      product.name,
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                      style: const TextStyle(fontWeight: FontWeight.bold),
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text(
                          (() {
                            final p = product.price ?? '0';
                            final val = double.tryParse(p);
                            return val != null ? '\$${val.toStringAsFixed(2)}' : '\$$p';
                          })(),
                          style: const TextStyle(color: Colors.blue, fontWeight: FontWeight.bold),
                        ),
                        InkWell(
                          onTap: () => _deleteProduct(product.id),
                          child: const Icon(Icons.delete_outline, color: Colors.red, size: 20),
                        )
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildListItem(Product product) {
    final imageUrl = product.images.isNotEmpty ? product.images[0].src : null;
    return GestureDetector(
      onTap: () async {
        await Navigator.pushNamed(context, '/product/edit', arguments: product);
        _fetchProducts(refresh: true);
      },
      child: Card(
        margin: const EdgeInsets.only(bottom: 8),
        color: const Color(0xFF1F2937),
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
        child: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Row(
            children: [
              Container(
                width: 60,
                height: 60,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(8),
                  color: Colors.grey[800],
                ),
                clipBehavior: Clip.antiAlias,
                child: imageUrl != null
                    ? Image.network(
                        imageUrl,
                        fit: BoxFit.cover,
                        errorBuilder: (context, error, stackTrace) =>
                            const Icon(Icons.broken_image, size: 30),
                      )
                    : const Icon(Icons.image, size: 30, color: Colors.grey),
              ),
              const SizedBox(width: 12),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      product.name,
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
                    ),
                    const SizedBox(height: 4),
                    Row(
                        children: [
                            if (product.type != ProductType.simple)
                                Container(
                                    padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 2),
                                    margin: const EdgeInsets.only(right: 6),
                                    decoration: BoxDecoration(
                                        color: Colors.blue.withValues(alpha: 0.9),
                                        borderRadius: BorderRadius.circular(4),
                                    ),
                                    child: Text(
                                        product.type.toString().split('.').last.toUpperCase(),
                                        style: const TextStyle(fontSize: 8, fontWeight: FontWeight.bold, color: Colors.white),
                                    ),
                                ),
                             Text(
                                (() {
                                  final p = product.price ?? '0';
                                  final val = double.tryParse(p);
                                  return val != null ? '\$${val.toStringAsFixed(2)}' : '\$$p';
                                })(),
                                style: const TextStyle(color: Colors.blue, fontWeight: FontWeight.bold),
                             ),
                        ]
                    )
                  ],
                ),
              ),
              Column(
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                   _buildStockDisplay(product),
                   const SizedBox(height: 8),
                   InkWell(
                      onTap: () => _deleteProduct(product.id),
                      child: const Icon(Icons.delete_outline, color: Colors.red, size: 20),
                   )
                ],
              )
            ],
          ),
        ),
      ),
    );
  }
}
