import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:intl/date_symbol_data_local.dart';
import 'package:intl/intl.dart';
import 'package:prasule/api/recurring_entry.dart';
import 'package:prasule/api/wallet.dart';
import 'package:prasule/api/wallet_manager.dart';
import 'package:prasule/pw/platformbutton.dart';
import 'package:prasule/pw/platformroute.dart';
import 'package:prasule/util/drawer.dart';
import 'package:prasule/util/text_color.dart';
import 'package:prasule/util/utils.dart';
import 'package:prasule/views/create_recur_entry.dart';
import 'package:prasule/views/settings/settings.dart';
import 'package:prasule/views/setup.dart';

/// Used to set up recurring entries
class RecurringEntriesView extends StatefulWidget {
  /// Used to set up recurring entries
  const RecurringEntriesView({super.key});

  @override
  State<RecurringEntriesView> createState() => _RecurringEntriesViewState();
}

class _RecurringEntriesViewState extends State<RecurringEntriesView> {
  Wallet? selectedWallet;
  List<Wallet> wallets = [];

  late String locale;
  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    locale = Localizations.localeOf(context).languageCode;
    initializeDateFormatting(Localizations.localeOf(context).languageCode);
  }

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

  Future<void> loadWallet() async {
    wallets = await WalletManager.listWallets();
    if (wallets.isEmpty && mounted) {
      unawaited(
        Navigator.of(context)
            .pushReplacement(platformRoute((c) => const SetupView())),
      );
      return;
    }
    selectedWallet = wallets.first;
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      drawer: makeDrawer(context, 3),
      appBar: AppBar(
        title: DropdownButton<int>(
          value: (selectedWallet == null)
              ? -1
              : wallets.indexOf(
                  wallets.where((w) => w.name == selectedWallet!.name).first,
                ),
          items: [
            ...wallets.map(
              (e) => DropdownMenuItem(
                value: wallets.indexOf(
                  e,
                ),
                child: Text(e.name),
              ),
            ),
            DropdownMenuItem(
              value: -1,
              child: Text(AppLocalizations.of(context).newWallet),
            ),
          ],
          onChanged: (v) async {
            if (v == null || v == -1) {
              await Navigator.of(context).push(
                platformRoute(
                  (c) => const SetupView(
                    newWallet: true,
                  ),
                ),
              );
              wallets = await WalletManager.listWallets();
              selectedWallet = wallets.last;
              setState(() {});
              return;
            }
            selectedWallet = wallets[v];
            setState(() {});
          },
        ),
        actions: [
          PopupMenuButton(
            itemBuilder: (context) => [
              AppLocalizations.of(context).settings,
              AppLocalizations.of(context).about,
            ].map((e) => PopupMenuItem(value: e, child: Text(e))).toList(),
            onSelected: (value) {
              if (value == AppLocalizations.of(context).settings) {
                Navigator.of(context)
                    .push(
                  platformRoute(
                    (context) => const SettingsView(),
                  ),
                )
                    .then((value) async {
                  selectedWallet =
                      await WalletManager.loadWallet(selectedWallet!.name);
                });
              } else if (value == AppLocalizations.of(context).about) {
                showAbout(context);
              }
            },
          ),
        ],
      ),
      floatingActionButton: FloatingActionButton(
        child: const Icon(Icons.add),
        onPressed: () {
          Navigator.of(context)
              .push(
                platformRoute(
                  (p0) => CreateRecurringEntryView(
                    w: selectedWallet!,
                    locale: locale,
                  ),
                ),
              )
              .then((value) => setState(() {}));
        },
      ),
      body: Center(
        child: SizedBox(
          width: MediaQuery.of(context).size.width * 0.9,
          child: (selectedWallet == null)
              ? const Column(
                  children: [
                    SizedBox(
                      width: 40,
                      height: 40,
                      child: CircularProgressIndicator(),
                    ),
                  ],
                )
              : (selectedWallet!.recurringEntries.isEmpty)
                  ? Column(
                      children: [
                        Text(
                          AppLocalizations.of(context).noEntries,
                          style: const TextStyle(
                            fontSize: 20,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        Text(
                          AppLocalizations.of(context).noEntriesSub,
                        ),
                      ],
                    )
                  : ListView.builder(
                      itemBuilder: (c, i) => Slidable(
                        endActionPane: ActionPane(
                          motion: const ScrollMotion(),
                          extentRatio: 0.3,
                          children: [
                            SlidableAction(
                              backgroundColor:
                                  Theme.of(context).colorScheme.error,
                              foregroundColor:
                                  Theme.of(context).colorScheme.onError,
                              icon: Icons.delete,
                              onPressed: (c) {
                                showDialog<void>(
                                  context: context,
                                  builder: (cx) => AlertDialog.adaptive(
                                    title: Text(
                                      AppLocalizations.of(context).sureDialog,
                                    ),
                                    content: Text(
                                      AppLocalizations.of(context).deleteSure,
                                    ),
                                    actions: [
                                      PlatformButton(
                                        text: AppLocalizations.of(context).yes,
                                        onPressed: () {
                                          selectedWallet!.recurringEntries
                                              .remove(
                                            selectedWallet!.recurringEntries[i],
                                          );
                                          WalletManager.saveWallet(
                                            selectedWallet!,
                                          );
                                          Navigator.of(cx).pop();
                                          setState(() {});
                                        },
                                      ),
                                      PlatformButton(
                                        text: AppLocalizations.of(context).no,
                                        onPressed: () {
                                          Navigator.of(cx).pop();
                                        },
                                      ),
                                    ],
                                  ),
                                );
                              },
                            ),
                          ],
                        ),
                        child: ListTile(
                          onTap: () {
                            Navigator.of(context)
                                .push<RecurringWalletEntry>(
                              MaterialPageRoute(
                                builder: (c) => CreateRecurringEntryView(
                                  w: selectedWallet!,
                                  locale: locale,
                                  editEntry:
                                      selectedWallet!.recurringEntries[i],
                                ),
                              ),
                            )
                                .then(
                              (editedEntry) {
                                if (editedEntry == null) return;
                                selectedWallet!.entries.remove(
                                  selectedWallet!.recurringEntries[i],
                                );
                                selectedWallet!.entries.add(editedEntry);
                                WalletManager.saveWallet(selectedWallet!);
                                setState(() {});
                              },
                            );
                          },
                          leading: Container(
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(16),
                              color: selectedWallet!
                                  .recurringEntries[i].category.color,
                            ),
                            child: Padding(
                              padding: const EdgeInsets.all(8),
                              child: Icon(
                                selectedWallet!
                                    .recurringEntries[i].category.icon,
                                color: selectedWallet!
                                    .recurringEntries[i].category.color
                                    .calculateTextColor(),
                              ),
                            ),
                          ),
                          title: Text(
                            selectedWallet!.recurringEntries[i].data.name,
                          ),
                          subtitle: Text(
                            NumberFormat.currency(
                              symbol: selectedWallet!.currency.symbol,
                            ).format(
                              selectedWallet!.recurringEntries[i].data.amount,
                            ),
                          ),
                        ),
                      ),
                      itemCount: selectedWallet!.recurringEntries.length,
                    ),
        ),
      ),
    );
  }
}
