import 'package:badges/badges.dart';
import 'package:echo_app/screens/home_page/widget/carousel_slider.widget.dart';
import 'package:echo_app/screens/home_page/widget/grid_card_list.dart';
import 'package:echo_app/screens/home_page/widget/horizontal_card_list.widget.dart';
import 'package:echo_app/screens/items_list_page/item_list.page.dart';
import 'package:echo_app/screens/my_order/my_order.page.dart';
import 'package:echo_app/screens/offers/widget/action_buttons.dart';
import 'package:echo_app/screens/offers/widget/offer_details.dart';
import 'package:echo_app/screens/offers/widget/offer_divider.dart';
import 'package:echo_app/screens/offers/widget/offer_image.dart';
import 'package:echo_app/screens/offers/widget/offer_input_output.dart';
import 'package:echo_app/screens/offers/widget/offer_title.dart';
import 'package:echo_app/screens/search_Screen/widget/FilterPage.dart';
import 'package:echo_app/screens/tap_page/tap.page.dart';
import 'package:echo_app/services/offers.service.dart';
import 'package:echo_app/shared/core.session.dart';
import 'package:echo_app/widgets/search_bar.dart' as search;
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get_utils/src/extensions/internacionalization.dart';
import 'package:rflutter_alert/rflutter_alert.dart';
import 'package:flutter/material.dart';

import '../../theme/variables.dart';
import '../../widgets/classification_card.widget.dart';
import '../notifications/notification.page.dart';
import '../search_Screen/search_screen.dart';

class HomePage extends StatefulWidget {
  List<dynamic> dataList;

  HomePage(this.dataList);
  static BuildContext? HomeContext;


  void setContext(context){
    HomeContext = context;
  }
  static void ReloadHome(){
    (HomeContext as Element).markNeedsBuild();
  }
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  List bannerImageList = [];
  var categories = [];
  var brands = [];
  var filterCategories = [];
  var filterbrands = [];
  var filterMasterGroupes = [];
  var appearedList = [];
  var masterGroupes = [];
  var homePageData = [];
  bool isLoading = true;
  bool isCat = true;
  bool isBrand = true;
  bool isDiv = true;
  bool isBan = true;
  bool isGroupes = true;
  var locationDesc = '';
  final ScrollController controller = ScrollController();


  initState() {
    EasyLoading.dismiss();
    getHomeData();

    this.appearedList = OffersService.offers;
    super.initState();
  }

  Future<void> getHomeData() async {
    locationDesc = await CoreSession.getLocationName();
    if (!CoreSession.dataFilled) {
      setState(() {
        this.bannerImageList = CoreSession.bannersList;

        CoreSession.dataFilled = true;
      });
    } else {
      setState(() {
        this.categories = CoreSession.categoryList;
        this.filterCategories = this.categories;
        this.brands = CoreSession.brandList;
        this.filterbrands = this.brands;
        this.bannerImageList = CoreSession.bannersList;

        this.masterGroupes = CoreSession.masterGroupes;
        this.filterMasterGroupes = this.masterGroupes;
      });
    }
    setState(() {
      isLoading = false;
    });
  }

  void showAlert(contxt) {
    if (CoreSession.hasDeffirentPricesFromGestUser)
      Alert(
        context: context,
        type: AlertType.info,
        useRootNavigator: true,
        title: "message".tr,
        desc: "differnt-prices".tr,
        buttons: [
          DialogButton(
            color: Colors.white,
            child: Text(
              "ok".tr,
              style: TextStyle(color: Colors.green, fontSize: 20),
            ),
            onPressed: () => {
              CoreSession.hasDeffirentPricesFromGestUser = false,
              Navigator.of(context, rootNavigator: true).pop(),
            },
            width: 120,
          )
        ],
      ).show();
  }

  @override
  void activate() {
    print('object');
  }
  void onClickApply(_currentRange){
    CoreSession.currentRange = _currentRange;
    setState(() {

    });
  }
  @override
  Widget build(BuildContext context) {
    TextEditingController _searchCtrl = TextEditingController();
    this.widget.setContext(context);
    if (CoreSession.hasDeffirentPricesFromGestUser) {
      Future.delayed(Duration.zero, () => showAlert(context));
    }

    onEnterSearch() {
      Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => ItemListPage([], 0, _searchCtrl.text),
        ),
      );
    }
    
    Size size = MediaQuery.of(context).size;
    readMore(int index) {
      var offer = appearedList[index];
      Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => OfferDetails(offer),
        ),
      );
    }
    return Scaffold(
      body: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          Container(
            color: Colors.white,
            child: Column(
              children: [
                SizedBox(
                  height: 10,
                ),
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 30),
                  child: Row(
                    children: [
                      ClipRRect(
                        borderRadius: BorderRadius.circular(80.0),
                        child: Image.network(
                          'https://img0cf.b8cdn.com/images/logo/55/2116055_logo_1657097539_n.png',
                          height: 60.0,
                          width: 60.0,
                        ),
                      ),
                      SizedBox(width: 20,),
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text("Welcome, ",style:  TextStyle(color: Colors.grey, fontSize: Variables.headline2FontSize),),
                          Text(CoreSession.currentOperator['name'],style: TextStyle(color: Colors.black, fontSize: Variables.headline1FontSize),),
                        ],
                      ),
                      Text(
                        locationDesc,
                        style: TextStyle(
                            fontWeight: FontWeight.bold,
                            fontSize: Variables.headline2FontSize,
                            color: Colors.white),
                      ),
                      Spacer(),

                      CoreSession.newNotificationCount > 0 ?
                        IconButton(
                            onPressed: () {
                              Navigator.push(
                                context,
                                MaterialPageRoute(
                                    builder: (context) => NotificationPage()),
                              );
                            },
                            icon: Image.asset(
                                'assets/imgs/more_icons/notification.png',
                                color: Variables.color_primary,
                                height: 33,
                                width: 30))
                      :     IconButton(
                          onPressed: () {
                            Navigator.push(
                              context,
                              MaterialPageRoute(
                                  builder: (context) => NotificationPage()),
                            );
                          },
                          icon: Image.asset(
                              'assets/imgs/more_icons/notification.png',
                              color: Variables.color_primary,
                              height: 33,
                              width: 30)),
                      IconButton(
                          onPressed: () {
                            Navigator.push(
                              context,
                              MaterialPageRoute(
                                  builder: (context) => MyOrderPage()),
                            );
                          },
                          icon: Image.asset(
                              'assets/imgs/default/cart.png',
                              color: Variables.color_primary,
                              height: 33,
                              width: 30)),
                    ],
                  ),
                ),
                SizedBox(height: 10),
                // PreferredSize(
                //   preferredSize: Size(50, 50),
                //   child: Padding(
                //     padding: const EdgeInsets.all(8.0),
                //     child: GestureDetector(
                //         onTap: () {
                //           Navigator.push(
                //             context,
                //             MaterialPageRoute(
                //               builder: (context) =>
                //                   SearchPage(CoreSession.homePageData[0]),
                //             ),
                //           );
                //         },
                //         child: search.Search_Bar.CustomSearchBar(
                //             _searchCtrl, onEnterSearch, false)),
                //   ),
                // ),
                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Container(
                    decoration: BoxDecoration(
                      color: Colors.white,
                      border: Border.all(
                        color: Colors.blue, // Outline color
                        width: 2.0,         // Outline width
                      ),
                      borderRadius: BorderRadius.circular(12.0), // Rounded corners
                    ),
                    child: Row(
                      children: [
                        IconButton(
                            onPressed: () {
                              // CoreSession.currentRange = RangeValues(0,5000);
                              // Navigator.push(
                              //   context,
                              //   MaterialPageRoute(
                              //     builder: (context) =>
                              //         SearchPage(CoreSession.homePageData[0]),
                              //   ),
                              // );
                            },
                            icon: Image.asset(
                                'assets/imgs/more_icons/search.png',
                                color: Variables.color_primary,
                                height: 25,
                                width: 25)),
                        Expanded(child: search.Search_Bar.CustomSearchBar(_searchCtrl, onEnterSearch , true)),

                        IconButton(
                          icon: Image.asset(
                              'assets/imgs/more_icons/fillter.png',
                              color: Variables.color_primary,
                              height: 25,
                              width: 25), onPressed: () {
                          showModalBottomSheet(
                              elevation: 10,
                              isScrollControlled: true,
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(10.0),
                              ),
                              context: context,
                              builder: (BuildContext context) {
                                return FractionallySizedBox(
                                    heightFactor: 0.8,
                                    child: Container(child:FilterPage(this.onClickApply,CoreSession.currentRange)));}
                          );
                        },
                        ),
                        SizedBox(width: 20,)

                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
          Expanded(
            child: SingleChildScrollView(
              controller: controller,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.start,
                children: [

                  Container(
                    height:150,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Expanded(
                          child: ListView.builder(
                            scrollDirection: Axis.horizontal,
                            shrinkWrap: true,
                            itemBuilder: (ctx, index) {
                              return
                                Container(
                                  width: size.width * 0.8,
                                  child: Card(
                                    // shape: BeveledRectangleBorder(
                                    //   borderRadius: BorderRadius.circular(5),
                                    // ),
                                    child: Stack(
                                      children: <Widget>[
                                        Container(
                                          height:120,
                                          child: OfferImage(
                                              appearedList[index]),
                                        ),
                                        PositionedDirectional(
                                          start: 1,
                                          bottom: 1,
                                          child: Container(
                                            color: Colors.white54,
                                            child: Column(
                                              children: <Widget>[
                                                OfferTitle(appearedList[index]
                                                ['promotionName']),
                                                OfferDivider(),
                                                if (appearedList[index]
                                                ['showReadMoreOption'] ?? false)
                                                  ActionButtons(index, readMore)
                                              ],
                                            ),
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                );
                            },
                            itemCount: appearedList.length,
                          ),
                        ),
                      ],
                    ),
                  ),
                  for (var item in this.widget.dataList)
                    if (item["dataList"].length > 0 && item['sectionTypeId'] == 1)
                      Container(
                        height: 50,
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Expanded(
                              child: ListView.builder(
                                shrinkWrap: true,
                                scrollDirection: Axis.horizontal,
                                // padding: const EdgeInsets.all(10.0),
                                itemCount: item["dataList"].length,
                                itemBuilder: (ctx, index) {
                                  return ChoiceChip(
                                    selectedColor: Variables.color_primary,
                                    backgroundColor:  Color(0xFFE4E8EC),
                                    label: Text(item["dataList"][index]['name'] ,
                                      style: TextStyle(
                                      color: item["dataList"][index]['selected'] ? Colors.white : Variables.color_primary, // Text color based on selection
                                      fontSize: 14
                                    ),),
                                    selected: item["dataList"][index]['selected'],
                                    onSelected: (bool selected) {
                                      setState(() {
                                        item["dataList"][index]['selected'] = selected;
                                      });
                                    },
                                  );
                                  return ClassificationCardWidget(
                                      item["dataList"][index]['id'],
                                      item['sectionTypeId'],
                                      item["dataList"][index]['name'],
                                      false, (itemIndex) {
                                    CoreSession.currentRange = RangeValues(0,5000);
                                    CoreSession.homePageData.firstWhere((e) =>
                                            e['sectionTypeId'] ==
                                            item['sectionTypeId'])['dataList']
                                        [itemIndex]['selected'] = true;
                                    Navigator.push(
                                      context,
                                      MaterialPageRoute(
                                        builder: (context) => SearchPage(item),
                                      ),
                                    );
                                  }, index);
                                },
                              ),
                            ),
                          ],
                        ),
                      ),
                  Row(
                    children: [
                      Padding(padding: const EdgeInsets.all(3.0)),
                      Text(
                        'popular'.tr,
                        style: TextStyle(
                            color: Variables.color_primary,
                            fontFamily: 'Poppins',
                            fontWeight: FontWeight.bold,
                            fontSize: 10.0),
                      ),
                    ],
                  ),
                  GridCardList(CoreSession.homePageData[0], _searchCtrl.text,
                      RangeValues(0.0, 5000.0), false, controller)
                ],
              ),
            ),
          ),
          Container(height: 20)
        ],
      ),
    );
  }
}
