import 'dart:core';

import 'package:flutter/material.dart';
import 'package:jiffy/jiffy.dart';
import 'package:provider/provider.dart';

import '../../../../api/holidays/getHolidaysResponse.dart';
import '../../../../model/holidays/holidaysProps.dart';
import '../../../../storage/base/settingsProvider.dart';
import '../../../../widget/centeredLeading.dart';
import '../../../../widget/confirmDialog.dart';
import '../../../../widget/debug/debugTile.dart';
import '../../../../widget/loadingSpinner.dart';
import '../../../../widget/placeholderView.dart';
import '../../../../widget/animatedTime.dart';

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

  @override
  State<Holidays> createState() => _HolidaysState();
}

extension StringExtension on String {
  String capitalize() {
    return "${this[0].toUpperCase()}${substring(1).toLowerCase()}";
  }
}

class _HolidaysState extends State<Holidays> {
  late SettingsProvider settings = Provider.of<SettingsProvider>(context, listen: false);
  late bool showPastEvents = settings.val().holidaysSettings.showPastEvents;

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      Provider.of<HolidaysProps>(context, listen: false).run();
      if(!settings.val().holidaysSettings.dismissedDisclaimer) showDisclaimer();
    });

    super.initState();
  }

  String parseString(String enDate) {
    return Jiffy.parse(enDate).format(pattern: "dd.MM.yyyy");
  }

  void showDisclaimer() {
    showDialog(context: context, builder: (context) {
      return AlertDialog(
        title: const Text("Richtigkeit und Bereitstellung der Daten"),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Text(""
                "Sämtliche Datumsangaben sind ohne Gewähr.\n"
                "Ich übernehme weder Verantwortung für die Richtigkeit der Daten noch hafte ich für wirtschaftliche Schäden die aus der Verwendung dieser Daten entstehen können.\n\n"
                "Die Daten stammen von https://ferien-api.de/"),
            const SizedBox(height: 30),
            ListTile(
              title: const Text("Diese Meldung nicht mehr anzeigen"),
              trailing: Checkbox(
                value: settings.val().holidaysSettings.dismissedDisclaimer,
                onChanged: (value) => settings.val(write: true).holidaysSettings.dismissedDisclaimer = value!,
              ),
            )
          ],
        ),
        actions: [
          TextButton(child: const Text("ferien-api.de besuchen"), onPressed: () => ConfirmDialog.openBrowser(context, "https://ferien-api.de/")),
          TextButton(child: const Text("Okay"), onPressed: () => Navigator.of(context).pop()),
        ],
      );
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Schulferien in Hessen"),
        actions: [
          IconButton(
            icon: const Icon(Icons.warning_amber_outlined),
            onPressed: () => showDisclaimer(),
          ),
          PopupMenuButton<bool>(
            initialValue: settings.val().holidaysSettings.showPastEvents,
            icon: const Icon(Icons.manage_history_outlined),
            itemBuilder: (context) {
              return [true, false].map((e) => PopupMenuItem<bool>(
                  value: e,
                  enabled: e != showPastEvents,
                  child: Row(
                    children: [
                      Icon(e ? Icons.history_outlined : Icons.history_toggle_off_outlined, color: Theme.of(context).colorScheme.onSurface),
                      const SizedBox(width: 15),
                      Text(e ? "Alle anzeigen" : "Nur zukünftige anzeigen")
                    ],
                  )
              )).toList();
            },
            onSelected: (e) {
              setState(() {
                showPastEvents = e;
                settings.val(write: true).holidaysSettings.showPastEvents = e;
              });
            },
          ),
        ],
      ),
      body: Consumer<HolidaysProps>(builder: (context, value, child) {
        if(value.primaryLoading()) return const LoadingSpinner();

        List<GetHolidaysResponseObject> holidays = value.getHolidaysResponse.data;
        if(!showPastEvents) holidays = holidays.where((element) => DateTime.parse(element.end).isAfter(DateTime.now())).toList();

        if(holidays.isEmpty) return const PlaceholderView(icon: Icons.search_off, text: "Es wurden keine Ferieneinträge gefunden!");

        return ListView.builder(
            itemCount: holidays.length,
            itemBuilder: (context, index) {
              GetHolidaysResponseObject holiday = holidays[index];
              String holidayType = holiday.name.split(" ").first.capitalize();
              return ListTile(
                leading: const CenteredLeading(Icon(Icons.calendar_month)),
                title: Text("$holidayType ab ${parseString(holiday.start)}"),
                subtitle: Text("bis ${parseString(holiday.end)}"),
                onTap: () => showDialog(context: context, builder: (context) => SimpleDialog(
                  title: Text("$holidayType ${holiday.year} in Hessen"),
                  children: [
                    ListTile(
                      leading: const CenteredLeading(Icon(Icons.signpost_outlined)),
                      title: Text(holiday.name),
                      subtitle: Text(holiday.slug),
                    ),
                    ListTile(
                      leading: const Icon(Icons.arrow_forward),
                      title: Text("vom ${parseString(holiday.start)}"),
                    ),
                    ListTile(
                      leading: const Icon(Icons.arrow_back),
                      title: Text("bis zum ${parseString(holiday.end)}"),
                    ),
                    Visibility(
                      visible: !DateTime.parse(holiday.start).difference(DateTime.now()).isNegative,
                      replacement: ListTile(
                        leading: const CenteredLeading(Icon(Icons.content_paste_search_outlined)),
                        title: Text(Jiffy.parse(holiday.start).fromNow()),
                      ),
                      child: ListTile(
                        leading: const CenteredLeading(Icon(Icons.timer_outlined)),
                        title: AnimatedTime(callback: () => DateTime.parse(holiday.start).difference(DateTime.now())),
                        subtitle: Text(Jiffy.parse(holiday.start).fromNow()),
                      ),
                    ),
                    DebugTile(context).jsonData(holiday.toJson()),
                  ],
                )),
                trailing: const Icon(Icons.arrow_right),
              );
            },
          );
        },
      )
    );
  }
}
