import 'package:animated_splash_screen/animated_splash_screen.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:helpers/helpers/misc_build/build_media.dart';
import 'package:rluv/features/account/account_create_screen.dart';
import 'package:rluv/features/budget/screens/budget_overview.dart';
import 'package:rluv/features/notes/screens/notes_screen.dart';
import 'package:rluv/features/settings/screens/settings_screen.dart';
import 'package:rluv/global/store.dart';
import 'package:rluv/global/styles.dart';
import 'package:rluv/global/utils.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'global/api.dart';
import 'global/widgets/ui_button.dart';

void main() async {
  runApp(const ProviderScope(child: MyApp()));
}

class MyApp extends ConsumerStatefulWidget {
  const MyApp({super.key});

  @override
  ConsumerState<MyApp> createState() => _MyAppState();
}

class _MyAppState extends ConsumerState<MyApp> {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      scaffoldMessengerKey: ref.read(scaffoldMessengerKeyProvider),
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: AnimatedSplashScreen.withScreenFunction(
        curve: Curves.easeInOutCubic,
        splashTransition: SplashTransition.scaleTransition,
        splashIconSize: 200,
        splash: Image.asset('assets/splash_icon.png'),
        backgroundColor: Styles.purpleNurple,
        duration: 1,
        screenFunction: () async {
          final prefs = await SharedPreferences.getInstance();
          ref.read(prefsProvider.notifier).state = prefs;
          Widget nextScreen = const AccountCreateScreen();
          if (ref.read(tokenProvider) != null) {
            nextScreen = const Home();
          }
          return nextScreen;
        },
      ),
    );
  }
}

class Home extends ConsumerStatefulWidget {
  const Home({super.key});

  @override
  ConsumerState<Home> createState() => _HomeState();
}

class _HomeState extends ConsumerState<Home> {
  Map<String, dynamic> initData = {};
  final drawerColors = Styles.curatedColors;
  @override
  void initState() {
    setDevicePortraitOrientation();
    if (!ref.read(loadingStateProvider)) {
      ref.read(dashboardProvider.notifier).fetchDashboard();
    }
    WidgetsBinding.instance.addPostFrameCallback(
      (_) {
        ref.read(currentHomePageProvider.notifier).state =
            const BudgetOverviewScreen(initialData: {});
      },
    );
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    if (ref.watch(tokenProvider) == null) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        Navigator.pushAndRemoveUntil(
          context,
          MaterialPageRoute(builder: (ctx) => const AccountCreateScreen()),
          (r) => false,
        );
      });
    }
    if (ref.watch(currentHomePageProvider).toString() ==
        "BudgetOverviewScreen") {
      initData = {};
    }
    return Scaffold(
      key: ref.read(_scaffoldKeyProvider),
      resizeToAvoidBottomInset: false,
      drawer: Drawer(
        backgroundColor: Styles.purpleNurple,
        child: SafeArea(
          child: Column(
            children: [
              SizedBox(height: BuildMedia(context).height * 0.15),
              UiButton(
                text: 'Budget',
                color: drawerColors[4],
                onPressed: () {
                  if (ref.read(currentHomePageProvider).toString() !=
                      "BudgetOverviewScreen") {
                    ref.read(currentHomePageProvider.notifier).state =
                        BudgetOverviewScreen(initialData: initData);
                  }
                  toggleDrawer();
                },
              ),
              UiButton(
                text: 'Notes',
                color: drawerColors[5],
                onPressed: () {
                  if (ref.read(currentHomePageProvider).toString() !=
                      "SharedNotesScreen") {
                    ref.read(currentHomePageProvider.notifier).state =
                        SharedNotesScreen(initialData: initData);
                  }
                  toggleDrawer();
                },
              ),
              const Spacer(),
              UiButton(
                text: 'Settings',
                color: drawerColors[0],
                onPressed: () {
                  if (ref.read(currentHomePageProvider).toString() !=
                      "SettingsScreen") {
                    ref.read(currentHomePageProvider.notifier).state =
                        const SettingsScreen();
                  }
                  toggleDrawer();
                },
              ),
              const SizedBox(height: 24),
            ],
          ),
        ),
      ),
      appBar: AppBar(
        backgroundColor: Styles.purpleNurple,
        title: Text(
          ref.watch(appBarTitleProvider),
        ),
      ),
      body: ref.watch(currentHomePageProvider),
    );
  }

  toggleDrawer() async {
    final key = ref.read(_scaffoldKeyProvider);
    if (key.currentState != null && key.currentState!.isDrawerOpen) {
      key.currentState!.openEndDrawer();
    } else if (key.currentState != null) {
      key.currentState!.openDrawer();
    }
  }
}

final _scaffoldKeyProvider = Provider<GlobalKey<ScaffoldState>>(
  (ref) => GlobalKey<ScaffoldState>(),
);

final currentHomePageProvider = StateProvider<Widget>(
  (ref) => Container(),
);

final appBarTitleProvider = Provider<String>(
  (ref) {
    final currentPageName = ref.watch(currentHomePageProvider).toString();
    switch (currentPageName) {
      case 'BudgetOverviewScreen':
        return 'Budget';
      case 'SharedNotesScreen':
        return 'Notes';
      default:
        return '';
    }
  },
);

final scaffoldMessengerKeyProvider =
    Provider<GlobalKey<ScaffoldMessengerState>>(
        (ref) => GlobalKey<ScaffoldMessengerState>());
