import 'package:adaptix/adaptix.dart';
import 'package:flutter/material.dart';
import 'package:sapaly_shop/models/product_model.dart';
import 'package:sapaly_shop/themes/app_theme.dart';

import '../../widgets/product_card.dart';
import '../../services/requests.dart';
import '../details/details.dart';

class Products extends StatefulWidget {
  const Products({super.key, required this.id});
  final int id;
  @override
  State<Products> createState() => _ProductsState();
}

class _ProductsState extends State<Products> {
  List<ProductModel> products = [];

  Future<void> getProductsByCategory(int id) async {
    try {
      var list = await API().getProductsByCategory(id);
      if (mounted) {
        setState(() {
          products = list;
        });
      }
    } catch (e) {
      debugPrint(e.toString());
    }
  }

  @override
  void initState() {
    getProductsByCategory(widget.id);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return GridView.builder(
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 2,
        childAspectRatio: 4 / (4.5),
        mainAxisSpacing: 15.adaptedPx(),
      ),
      itemCount: products.length,
      itemBuilder: (context, index) {
        return products == null
            ? SizedBox(
                height: 150.adaptedPx(),
                child: const Center(
                  child: CircularProgressIndicator(
                    color: AppTheme.lightPrimaryColor,
                  ),
                ),
              )
            : ProductCard(
                imageUrl: products[index].previewImage?.path ?? '',
                price: '${products[index].offer.first.price}.M',
                discountPrice: '${products[index].offer.first.oldPrice}.M',
                description: products[index].offer.first.name,
                discountPriceValue:
                    products[index].offer.first.discountPriceValue,
                onPressed: () => Navigator.of(context).push(
                  MaterialPageRoute(
                    builder: (context) => Details(
                      id: products[index].id,
                      image: products[index].previewImage?.path ?? '',
                      price: '${products[index].offer.first.price}.M',
                      description: products[index].offer.first.name,
                    ),
                  ),
                ),
              );
      },
    );
  }
}
