import 'package:animate_do/animate_do.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../../../library/pagewise/flutter_pagewise.dart';
import '../../app.dart';

class HorizontalScrollableProducts extends StatefulWidget {
  final Map<String, dynamic> param;

  HorizontalScrollableProducts({required this.param});

  @override
  State<HorizontalScrollableProducts> createState() => _HorizontalScrollableProductsState();
}

class _HorizontalScrollableProductsState extends State<HorizontalScrollableProducts> {
  late PagewiseLoadController<ProductModel> pagewiseLoadController;
  bool hasData = true;

  Future<void> initPageWiseController() async {
    pagewiseLoadController = PagewiseLoadController(
      pageFuture: (pageIndex) => _fetchProducts(pageIndex! + 1),
      pageSize: Constants.PAGE_SIZE,
    );
  }

  Future<List<ProductModel>> _fetchProducts(int currPage) async {
    debugPrint('fetchProducts');
    final Map<String, dynamic> apiParams = {
      'locale': await getLocale(),
      'currency': 'TMT',
      'page': currPage,
      'limit': Constants.PAGE_SIZE,
      this.widget.param.keys.first: this.widget.param.values.first,
    };

    final data = await ProductApi.getHomePageProducts(apiParams, this.widget.param['url']);

    setState(() {
      hasData = data.isNotEmpty;
    });

    return data;
  }

  @override
  void initState() {
    super.initState();
    initPageWiseController();
  }

  @override
  Widget build(BuildContext context) {
    return hasData
        ? Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            children: [
              Text(
                widget.param['title'],
                style: AppTheme.homepageTitleTxtStyle,
              ),
              SizedBox(height: 20.h),
              ConstrainedBox(
                constraints: BoxConstraints(maxHeight: 280.h, minHeight: 250.h),
                child: Container(
                  color: Colors.white,
                  child: PagewiseListView<ProductModel>(
                    scrollDirection: Axis.horizontal,
                    shrinkWrap: true,
                    showRetry: false,
                    // pageSize: Constants.PAGE_SIZE,
                    itemBuilder: (_, model, i) => ItemBuilder(model: model),
                    pageLoadController: pagewiseLoadController,
                    // pageFuture: (pageIndex) => pc.fetchProducts(pageIndex!),

                    loadingBuilder: (context) {
                      return Container(
                        // To remove left padding 16
                        padding: EdgeInsets.only(right: 16.w),
                        width: 1.sw,
                        height: 0.15.sh,
                        child: Center(child: CustomLoader()),
                      );
                    },
                    errorBuilder: (_, error) => InkWell(
                      onTap: () async {
                        await _fetchProducts(1);
                        pagewiseLoadController.reset();
                      },
                      child: Container(
                        padding: EdgeInsets.only(right: 16.w),
                        width: 1.sw,
                        height: 0.10.sh,
                        child: Center(
                          child: Material(
                            elevation: 2,
                            color: Colors.white,
                            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(50)),
                            child: Container(
                              padding: const EdgeInsets.all(8),
                              child: Icon(
                                Icons.refresh_sharp,
                                size: 28.sp,
                                color: ThemeColor.mainColor,
                              ),
                            ),
                          ),
                        ),
                      ),
                    ),
                  ),
                ),
              ),
            ],
          )
        : SizedBox.shrink();
  }
}

class ItemBuilder extends StatelessWidget {
  final ProductModel model;
  const ItemBuilder({
    Key? key,
    required this.model,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return FadeInRight(
      child: Container(
        width: context.isTablet ? 180.w : 160.w,
        margin: EdgeInsets.only(right: 16.w),
        child: ProductCard(model: model),
      ),
    );
  }
}
