import 'package:flutter/material.dart';
import 'package:Emma_home/utils/data.dart';
import 'package:Emma_home/screens/subheader_Datepicker.dart';
import 'package:Emma_home/screens/event_list.dart';
import 'package:flutter_svg/svg.dart';
import 'package:provider/provider.dart';

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

  @override
  _HomePage createState() => _HomePage();
}

class _HomePage extends State<HomePage> with RouteAware {
  late RouteObserver<PageRoute> routeObserver;
  late Future<void> _fetchDataFuture;
  bool isScrollable = false;
  bool _isFirstLoad = true;
  void toggleExpanded() {
    setState(() {
      isScrollable = !isScrollable;
    });
  }

// TODO: Ok nun ist es etwas optimiert. Fühlt sich aber sehr gefaked an.
  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    routeObserver = RouteObserver<PageRoute>();
    routeObserver.subscribe(this, ModalRoute.of(context) as PageRoute);
    if (_isFirstLoad) {
      _isFirstLoad = false;
      return;
    }
    _updateData();
    _isFirstLoad = true;
  }

  @override
  void dispose() {
    routeObserver.unsubscribe(this);
    super.dispose();
  }

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

  _updateData() {
    _fetchDataFuture = Categories.instance.updateCategoryAmount('Ingolstadt');
  }

  Future<void> _refresh() async {
    setState(() {
      // Aktualisiere die Liste (Beispiel: Einfügen neuer Daten)
      _fetchDataFuture = Categories.instance.updateCategoryAmount('Ingolstadt');
    });
  }

  @override
  Widget build(BuildContext context) {
    var size = MediaQuery.of(context).size;
    /*24 is for notification bar on Android*/
    // ScrollController und Status-Variable
    ScrollController scrollController = ScrollController();

    // Verfügbarer Bereich auf dem Bildschirm
    final screenWidth = MediaQuery.of(context).size.width;
    final screenHeight = MediaQuery.of(context).size.height;
    double statusBarHeight = MediaQuery.of(context).padding.top;
    double HeaderHeight = 60;
    double TimeButtonHeight = 35;
    double TimeButtonpadding = 20;
    double FooterHeight = 91;
    double bottomPadding = MediaQuery.of(context).padding.bottom;
    final staticContentheight = statusBarHeight +
        HeaderHeight +
        TimeButtonHeight +
        TimeButtonpadding +
        FooterHeight +
        bottomPadding;
    double amaountOfCategoryLines = 4; //singleCategories.categories.length/2;
    double paddingHeight = 10;
    double shaddowHeight = 10;

    final dynamicContentHeight =
        ((amaountOfCategoryLines + 1) * paddingHeight) +
            (amaountOfCategoryLines * shaddowHeight);
    final resultHeightRemove = staticContentheight + dynamicContentHeight;
    final int itemHeight =
        ((screenHeight - resultHeightRemove) / 4).toInt(); //240-90) / 4;
    final double itemWidth = (size.width - 40) / 2;
    MediaQueryData queryData;
    queryData = MediaQuery.of(context);

    var appBar = AppBar(
      leading: SizedBox(
        height: 60,
        width: 63,
        child: IconButton(
          icon: Image.asset('assets/images/logo.png'),
          onPressed: () {
            // Open drawer or perform action
          },
        ),
      ),
      title: Row(
        children: [
          const SizedBox(
            height: 10, //height of button
            width: 20, //width of button
            child: Icon(Icons.keyboard_arrow_down),
          ),
          const SizedBox(
            //width of button
            width: 10,
          ),
          SizedBox(
            width: 100.0,
            child: TextField(
              controller: TextEditingController(text: "Ingolstadt"),
              decoration: const InputDecoration(
                border: UnderlineInputBorder(),
              ),
            ),
          ),
        ],
      ),
      actions: [
        IconButton(
          icon: const Icon(Icons.search),
          onPressed: () {
            // Perform search action
          },
        ),
        const SizedBox(
          height: 40,
          child: VerticalDivider(
            thickness: 1,
            width: 20,
            color: Colors.black,
          ),
        ),
        SizedBox(
          height: 50, //height of button
          //width of button
          child: IconButton(
            icon: Image.asset('assets/images/Login.png'),
            onPressed: () {},
          ),
        ),
      ],
      bottom: PreferredSize(
        preferredSize: const Size.fromHeight(1.0),
        child: Container(
          color: Colors.black,
          height: 1.0,
        ),
      ),
      flexibleSpace: Container(),
    );
    var body = RefreshIndicator(
        onRefresh: _refresh,
        child: SafeArea(child:
            Consumer<Categories>(builder: (context, singleCategories, child) {
          return SingleChildScrollView(
            physics: isScrollable
                ? const AlwaysScrollableScrollPhysics()
                : const NeverScrollableScrollPhysics(),
            child: Column(
              children: <Widget>[
                //Header Container
                //HeaderSection(),
                Container(height: 14),
                Container(
                  height: 35,
                  padding: const EdgeInsets.all(0),
                  child: TimeButtonSection(
                      onToggle: toggleExpanded), // Dein Button-Bereich
                ),
                GridView.builder(
                  controller: scrollController,
                  physics: const NeverScrollableScrollPhysics(),
                  shrinkWrap:
                      true, // Damit der GridView korrekt in die Column passt
                  //physics: NeverScrollableScrollPhysics(), // Deaktiviert das Scrolling des GridView
                  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: 2, // Anzahl der Spalten im Grid
                    //crossAxisSpacing: 10.0,
                    mainAxisSpacing: 10.0,
                    childAspectRatio: (itemWidth / itemHeight),
                  ),
                  itemCount: singleCategories
                      .categories.length, // Anzahl der Elemente im Grid
                  itemBuilder: (BuildContext context, int index) {
                    return Padding(
                      padding: const EdgeInsets.all(6.0),
                      child: InkWell(
                        onTap: () async {
                          final events = await fetchGroupedEvents(
                              singleCategories.categories[index].category);
                          _isFirstLoad = true;
                          Navigator.push(
                              context,
                              MaterialPageRoute(
                                  builder: (context) => Event_Card_small(
                                        event_grouped: events,
                                        color: singleCategories
                                            .categories[index].color,
                                        screen_size: queryData,
                                        category:
                                            singleCategories.categories[index],
                                      )));
                        },
                        child: SizedBox(
                          width: itemWidth,
                          height: itemHeight.toDouble(),
                          child: Stack(
                            children: [
                              Positioned(
                                left: 0,
                                top: 0,
                                child: Container(
                                  width: itemWidth,
                                  height: itemHeight.toDouble(),
                                  decoration: ShapeDecoration(
                                    image: DecorationImage(
                                      image: AssetImage(singleCategories
                                          .categories[index].imageUrl),
                                      fit: BoxFit.cover,
                                    ),
                                    shape: RoundedRectangleBorder(
                                        borderRadius: BorderRadius.circular(8)),
                                    shadows: [
                                      BoxShadow(
                                        color: singleCategories
                                            .categories[index].color,
                                        blurRadius: 0,
                                        offset: const Offset(0, 10),
                                        spreadRadius: 0,
                                      )
                                    ],
                                  ),
                                ),
                              ),
                              Positioned(
                                left: 16,
                                top: 15,
                                child: Text(
                                  singleCategories.categories[index].amount
                                      .toString(),
                                  style: const TextStyle(
                                    color: Colors.white,
                                    fontSize: 18,
                                    fontFamily: 'Inter',
                                    fontWeight: FontWeight.w500,
                                    height: 0,
                                  ),
                                ),
                              ),
                              Positioned(
                                left: 13,
                                top: singleCategories.categories[index]
                                    .textheight, //86, //TODO Bootom?
                                child: SizedBox(
                                  width: itemWidth -
                                      20, // Set a fixed width or use constraints
                                  child: Wrap(
                                    children: [
                                      Text(
                                        singleCategories
                                            .categories[index].title,
                                        style: const TextStyle(
                                          color: Colors.white,
                                          fontSize: 24,
                                          fontFamily: 'Inter',
                                          fontWeight: FontWeight.w800,
                                          height: 0,
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                              ),
                              Positioned(
                                right: 20,
                                top: 10,
                                child: SizedBox(
                                  width: 32,
                                  height: 32,
                                  child: SvgPicture.asset(
                                    singleCategories.categories[index].iconUrl,
                                    colorFilter: const ColorFilter.mode(
                                        Colors.white, BlendMode.srcIn),
                                  ),
                                  /* Image.asset(
                                singleCategories.categories[index].iconUrl,
                              ), */
                                ),
                              ),
                              Positioned(
                                left: 127,
                                top: 9,
                                child: Container(
                                  width: 31,
                                  height: 31,
                                  clipBehavior: Clip.antiAlias,
                                  decoration: const BoxDecoration(),
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                    );
                  },
                ),
                //Body Container
                Container(
                  height: 20,
                ),
                const Footer(),
              ],
            ),
          );
        })));

    return Scaffold(
      backgroundColor: Colors.white,
      appBar: appBar,
      body: Consumer<Categories>(builder: (context, singleCategories, child) {
        return body;
      }),
    );
    @override
    void dispose() {
      scrollController.dispose();
      super.dispose();
    }
  }
}
