import 'dart:ui';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:initial_folder/models/subcategories_model.dart';
import 'package:initial_folder/providers/categories_provider.dart';
import 'package:initial_folder/screens/home/components/body_comp/course_by_subcategory.dart';
import 'package:initial_folder/size_config.dart';
import 'package:initial_folder/theme.dart';
import 'package:initial_folder/widgets/custom_navigator.dart';
import 'package:provider/provider.dart';

class Categories extends StatefulWidget {
  const Categories({
    Key? key,
    this.scrollable = false,
    required this.selectedCategoryId,
    required this.scrollController,
  }) : super(key: key);
  final bool scrollable;
  final String selectedCategoryId;
  final ScrollController scrollController;

  @override
  State<Categories> createState() => _CategoriesState();
}

class _CategoriesState extends State<Categories> {
  bool _isExpanded = false;
  bool _buttonPressed = false;
  final GlobalKey<_CategoriesState> _categoriesKey =
      GlobalKey<_CategoriesState>();

  @override
  void initState() {
    super.initState();
    widget.scrollController.addListener(_scrollListener);
  }

  @override
  void dispose() {
    widget.scrollController.removeListener(_scrollListener);
    super.dispose();
  }

  void _scrollListener() {
    if (_isExpanded) {
      setState(() {
        _isExpanded = false;
        _buttonPressed = false;
      });
    }
  }

  void toggleExpansion(bool expanded) {
    setState(() {
      _isExpanded = expanded;
      _buttonPressed = expanded;
    });

    if (!expanded) {
      widget.scrollController.animateTo(
        0,
        duration: Duration(milliseconds: 500),
        curve: Curves.easeInOut,
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Consumer<CategoriesProvider>(builder: (context, state, _) {
        if (state.state == ResultState.Loading) {
          return Center(
            child: CircularProgressIndicator(
              color: secondaryColor,
              strokeWidth: 2,
            ),
          );
        } else if (state.state == ResultState.HasData) {
          final List<SubCategoryModel> filteredResult = state.result
              .where((category) => category.id == widget.selectedCategoryId)
              .map((category) => category.subCategories!)
              .expand((element) => element)
              .toList();
          final bool showExpandIcon = filteredResult.length > 3;
          return Container(
            margin: EdgeInsets.symmetric(
                vertical: getProportionateScreenHeight(10)),
            child: Column(
              children: [
                Container(
                  decoration: BoxDecoration(
                    color: Theme.of(context).colorScheme.background,
                    boxShadow: [
                      BoxShadow(
                        color: Theme.of(context).brightness == Brightness.dark
                            ? Colors.grey.withOpacity(0.6)
                            : Colors.black.withOpacity(0.2),
                        spreadRadius: -10,
                        blurRadius: 12,
                        offset: Offset(0, 9),
                      ),
                    ],
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          ...filteredResult
                              .take(_buttonPressed ? 2 : 2)
                              .map<Widget>((subcategory) {
                            return Padding(
                              padding: EdgeInsets.symmetric(
                                  horizontal: getProportionateScreenWidth(17)),
                              child: GestureDetector(
                                onTap: () {
                                  Navigator.push(
                                    context,
                                    CustomNavigator(
                                      child: CourseBySubcategory(
                                        categoryId: widget.selectedCategoryId,
                                        subId: subcategory.subId,
                                        name: subcategory.nameSubCategory,
                                      ),
                                    ),
                                  );
                                },
                                child: Text(
                                  subcategory.nameSubCategory.isNotEmpty
                                      ? subcategory.nameSubCategory.replaceAll('&amp;', '&')
                                      : 'No subcategories available',
                                  style: thirdTextStyle.copyWith(
                                    fontSize: getProportionateScreenWidth(11.5),
                                    fontWeight: FontWeight.w600,
                                  ),
                                ),
                              ),
                            );
                          }).toList(),
                          if (showExpandIcon)
                            IconButton(
                              icon: Transform.rotate(
                                angle: _isExpanded ? pi / 2 : 0,
                                child: Icon(
                                  Icons.arrow_forward_ios,
                                  size: getProportionateScreenWidth(16),
                                ),
                              ),
                              onPressed: () {
                                setState(() {
                                  _isExpanded = !_isExpanded;
                                  _buttonPressed = !_buttonPressed;
                                });
                              },
                            ),
                        ],
                      ),
                      if (_isExpanded)
                        Padding(
                          padding: EdgeInsets.only(
                              top: getProportionateScreenHeight(8)),
                          child: Container(
                            color: Theme.of(context).colorScheme.background,
                            height: 160,
                            child: ListView(
                              shrinkWrap: true,
                              physics: AlwaysScrollableScrollPhysics(),
                              children: filteredResult
                                  .skip(2)
                                  .map<Widget>((subcategory) {
                                return Padding(
                                  padding: EdgeInsets.symmetric(
                                      horizontal:
                                          getProportionateScreenWidth(17)),
                                  child: GestureDetector(
                                    onTap: () {
                                      Navigator.push(
                                        context,
                                        CustomNavigator(
                                          child: CourseBySubcategory(
                                            categoryId:
                                                widget.selectedCategoryId,
                                            subId: subcategory.subId,
                                            name: subcategory.nameSubCategory,
                                          ),
                                        ),
                                      );
                                    },
                                    child: Padding(
                                      padding: EdgeInsets.only(
                                          bottom:
                                              getProportionateScreenHeight(10)),
                                      child: Padding(
                                        padding: EdgeInsets.only(
                                            bottom:
                                                getProportionateScreenHeight(
                                                    9)),
                                        child: Text(
                                          subcategory.nameSubCategory.isNotEmpty
                                              ? subcategory.nameSubCategory.replaceAll('&amp;', '&')
                                              : 'No subcategories available',
                                          style: thirdTextStyle.copyWith(
                                            fontSize:
                                                getProportionateScreenWidth(
                                                    11.5),
                                            fontWeight: FontWeight.w600,
                                          ),
                                        ),
                                      ),
                                    ),
                                  ),
                                );
                              }).toList(),
                            ),
                          ),
                        ),
                    ],
                  ),
                ),
              ],
            ),
            key: _categoriesKey,
          );
        } else if (state.state == ResultState.NoData) {
          return Center(child: Text("No subcategories available"));
        } else if (state.state == ResultState.Error) {
          return Center(child: Text("No internet connections."));
        } else {
          print(state.result.length);
          return Center(child: Text(''));
        }
      }),
    );
  }
}
