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/detail_widget.dart';
import 'package:provider/provider.dart';
import 'package:Emma_home/main.dart';

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

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

class _HomePage extends State<HomePage> {
  late Future<void> _fetchDataFuture;
  bool isScrollable = false;
  void toggleExpanded() {
    setState(() {
      isScrollable = !isScrollable;
    });
  }

  @override
  void initState() {
    super.initState();
    _fetchDataFuture = Categories.instance.updateCategoryAmount('Ingolstadt');
  }

//fetchGroupedEvents
  Future<List<Map<String, dynamic>>> fetchGroupedEvents(String category) async {
    try {
      final response = await supabase
          .rpc('get_events_grouped_by_date', params: {'cat_id': category});
      // Cast auf die gewünschte Struktur
      return (response as List)
          .map((entry) => {
                'start_date': entry['start_date'], // Das Gruppierungsdatum
                'events': (entry['events'] as List)
                    .cast<Map<String, dynamic>>() // Event-Details
              })
          .toList();
    } catch (e) {
      throw Exception('Failed to fetch data: $e');
    }
  }

  Future<List<Map<String, dynamic>>> fetchEvents(String category) async {
    try {
      //final today = DateTime.now().toUtc().toString().split(' ')[0];
      final response = await supabase
          .from("events")
          //.innerJoin('event_category', 'events.id = event_category.event_id')
          .select(
              'id,name,description,detail,subheader,main_category_id,location(name),time!inner(*),event_category!inner(event_id)')
          .eq('event_category.category_id', category);
      //.gte('time.start_date', DateTime.now().toIso8601String().split('T')[0]) // Beginn des heutigen Tages
      //.lt('time.start_date', DateTime.now().add(Duration(days: 1)).toIso8601String().split('T')[0]); // Morgen;
      //select('id, name, cities(id, name)')
      //find all events mit Ort und zusatzinfos die die Kathegorie haben welche ausgewählt wurde am heutigen Tag dann kommender Tag usw.
      //final test = response[0]['time'][0]['start_date'];
      return (response as List).cast<Map<String, dynamic>>();
    } catch (e) {
      throw Exception('Failed to fetch data: $e');
    }
  }

  Future<List<Map<String, dynamic>>> fetchEventsToday(String category) async {
    try {
      final today = DateTime.now().toUtc().toString().split(' ')[0];
      final response = await supabase
          .from("events")
          //.innerJoin('event_category', 'events.id = event_category.event_id')
          .select(
              'id,name,description,detail,subheader,main_category_id,location(name),time!inner(*),event_category!inner(event_id)')
          .eq('event_category.category_id', category) //;
          .eq('time.start_date', today);
      //.gte('time.start_date', DateTime.now().toIso8601String().split('T')[0]) // Beginn des heutigen Tages
      //.lt('time.start_date', DateTime.now().add(Duration(days: 1)).toIso8601String().split('T')[0]); // Morgen;
      //select('id, name, cities(id, name)')
      //find all events mit Ort und zusatzinfos die die Kathegorie haben welche ausgewählt wurde am heutigen Tag dann kommender Tag usw.
      //final test = response[0]['time'][0]['start_date'];
      return (response as List).cast<Map<String, dynamic>>();
    } catch (e) {
      throw Exception('Failed to fetch data: $e');
    }
  }

  Future<List<Map<String, dynamic>>> fetchEventsTomorrow(
      String category) async {
    try {
      final today = DateTime.now().toUtc().toString().split(' ')[0];
      final response = await supabase
          .from("events")
          //.innerJoin('event_category', 'events.id = event_category.event_id')
          .select(
              'id,name,description,detail,subheader,location(name),time!inner(*),event_category!inner(event_id)')
          .eq('event_category.category_id', category) //;
          .eq('time.start_date', today);
      //.gte('time.start_date', DateTime.now().toIso8601String().split('T')[0]) // Beginn des heutigen Tages
      //.lt('time.start_date', DateTime.now().add(Duration(days: 1)).toIso8601String().split('T')[0]); // Morgen;
      //select('id, name, cities(id, name)')
      //find all events mit Ort und zusatzinfos die die Kathegorie haben welche ausgewählt wurde am heutigen Tag dann kommender Tag usw.
      //final test = response[0]['time'][0]['start_date'];
      return (response as List).cast<Map<String, dynamic>>();
    } catch (e) {
      throw Exception('Failed to fetch data: $e');
    }
  }

  @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 = 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);
                      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: 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();
    }
  }
}
