import 'package:Emma_home/utils/class.dart';
import 'package:flutter/material.dart';
import 'package:Emma_home/screens/subheader_Datepicker.dart';
//import 'package:learn_project/main.dart';
import 'package:intl/intl.dart';
import 'package:Emma_home/utils/data.dart';
//import 'package:supabase_flutter/supabase_flutter.dart';

class Event_Card_small extends StatelessWidget {
  //final List<Map<String, dynamic>> events;
  final List<Map<String, dynamic>> event_grouped;
  final Color color;
  final MediaQueryData screen_size;
  final Category category;

  const Event_Card_small(
      {super.key,
      required this.event_grouped,
      required this.color,
      required this.screen_size,
      required this.category});

  void toggleExpanded() {}
  /* void initState() {
    super.initState();
    _loadData();
  } */
/*   */

  @override
  Widget build(BuildContext 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(),
    );
    //_loadData();
    var body = CustomScrollView(slivers: [
      SliverSafeArea(
        //minimum: EdgeInsets.zero,
        bottom: false,
        sliver: SliverToBoxAdapter(
          child: Container(
              alignment: Alignment.center,
              child: Column(children: <Widget>[
                Container(height: 10),
                Container(
                  height: 35,
                  padding: const EdgeInsets.all(0),
                  child: TimeButtonSection(
                      onToggle: toggleExpanded), // Dein Button-Bereich
                ),
                Container(
                  height: 10,
                ),
                SizedBox(
                  height: 35,
                  child:
                      MusikHeader(name: category.title, icon: category.iconUrl),
                ),
                //Container(),
              ])),
        ),
      ),

      // Gruppierte Events mit SliverMainAxisGroup
      ...event_grouped.map((group) {
        final String startDate = group['start_date'];
        final List<Map<String, dynamic>> events = group['events'];

        return SliverMainAxisGroup(
          slivers: [
            // Gruppierungs-Header
            SliverToBoxAdapter(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // TODO: muss noch angepasst werden jedes mal wenn ein neuer Tag ist wieder diesen Text anzeigen
                  const SizedBox(height: 10),
                  Padding(
                    padding: const EdgeInsets.only(
                        left: 20.0), // Abstand von 16 Pixeln zum linken Rand
                    child: Text(
                      DateFormat('dd.MM.yyyy').format(DateTime.parse(startDate)),
                      style: const TextStyle(
                        color: Color(0xFF171717),
                        fontSize: 12,
                        fontFamily: 'Inter',
                        fontWeight: FontWeight.w600,
                        height: 0,
                      ),
                    ),
                  ),

                  //Kurze Zwischenbereich zum trennen
                  const SizedBox(height: 4),
                ],
              ),
            ),

            // Liste der Events
            SliverList(
              delegate: SliverChildBuilderDelegate(
                (context, index) {
                  final event = events[index];
                  return EventCard2Section(
                    title: event['name'],
                    description: event['description'],
                    location: event['location_name'] ?? '',
                    start_time: extractTime24h(event['start']),
                    color: event['main_category_id'] != null
                        ? extractColor(event['main_category_id'])
                        : color,
                    //extractColor(events[index]['main_category_id']),
                    // oder ein beliebiger Standardwert
                    screen_size: screen_size,
                  );
                },
                childCount: events.length,
              ),
            ),
          ],
        );
      }),

      SliverToBoxAdapter(
        child: Column(children: [
          const LostEvents(),
          Container(height: 20),
          const Footer(),
        ]),
      ),
    ]);
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: appBar,
      body: body,
    );
  }
}

String extractTime24h(String timestamp) {
  try {
    DateTime dateTime = DateTime.parse(timestamp);
    String hours = dateTime.hour.toString().padLeft(2, '0');
    String minutes = dateTime.minute.toString().padLeft(2, '0');
    return '$hours:$minutes';
  } catch (e) {
    print('Error parsing timestamp: $e');
    return '--:--'; // or some other error indicator
  }
}

//TODO: Color muss anhand der Categorie entschieden werden
// Also herauslesen welche Category das Event hat
// Dann den richtigen Eintrag in Data identifizieren udn die Farbe auswählen
Color extractColor(String categoryID) {
  var singleCategories = Categories.instance;
  final result = singleCategories.categories
      .where((recipe) => recipe.category == categoryID)
      .firstOrNull;
  Color categorieColor = const Color.fromARGB(255, 255, 255, 255);
  if (result != null) {
    categorieColor = result.color;
  }
  return categorieColor;
}
