import 'dart:developer';

import 'package:didvan/config/design_config.dart';
import 'package:didvan/main.dart';
import 'package:didvan/providers/media.dart';
import 'package:didvan/providers/server_data_provider.dart';
import 'package:didvan/providers/theme_provider.dart';
import 'package:didvan/providers/user_provider.dart';
import 'package:didvan/routes/routes.dart';
import 'package:didvan/services/app_initalizer.dart';
import 'package:didvan/services/network/request.dart';
import 'package:didvan/services/storage/storage.dart';
import 'package:didvan/utils/action_sheet.dart';
import 'package:didvan/views/widgets/didvan/button.dart';
import 'package:didvan/views/widgets/logos/didvan_horizontal_logo.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:provider/provider.dart';
import 'package:universal_html/html.dart' as html;

class Splash extends StatefulWidget {
  const Splash({Key? key}) : super(key: key);

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

class _SplashState extends State<Splash> {
  bool _isGettingThemeData = true;
  bool _errorOccured = false;

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

  @override
  Widget build(BuildContext context) {
    if (_isGettingThemeData) {
      return Container(
        color: Colors.black,
        height: double.infinity,
        width: double.infinity,
      );
    }
    return AnnotatedRegion<SystemUiOverlayStyle>(
      value: DesignConfig.systemUiOverlayStyle.copyWith(
        systemNavigationBarColor: Theme.of(context).colorScheme.background,
      ),
      child: Scaffold(
        body: Container(
          alignment: Alignment.center,
          padding: const EdgeInsets.all(60),
          color: Theme.of(context).colorScheme.background,
          child: Column(
            children: [
              const SizedBox(height: 70),
              const Expanded(
                child: DidvanVerticalLogo(),
              ),
              if (!_errorOccured)
                SpinKitSpinningLines(
                  color: Theme.of(context).colorScheme.primary,
                ),
              if (_errorOccured) const SizedBox(height: 30),
              if (_errorOccured)
                DidvanButton(
                  width: 120,
                  height: 40,
                  title: 'تلاش مجدد',
                  onPressed: () {
                    setState(() {
                      _errorOccured = false;
                    });
                    _initialize();
                  },
                ),
            ],
          ),
        ),
      ),
    );
  }

  Future<void> _initialize() async {
    try {
      ActionSheetUtils.context = navigatorKey.currentContext!;
      if (kIsWeb) {
        html.window.onBeforeUnload.listen((event) {
          StorageService.webStorage
              .removeWhere((key, value) => key == 'image-cache');
        });
      }
      await AppInitializer.setupServices();
      final settingsData = await AppInitializer.initilizeSettings();
      final themeProvider = context.read<ThemeProvider>();
      themeProvider.themeMode = settingsData.themeMode;
      themeProvider.fontFamily = settingsData.fontFamily;
      themeProvider.fontScale = settingsData.fontScale;
      await Future.delayed(
        const Duration(milliseconds: 200),
        () => setState(() {
          _isGettingThemeData = false;
        }),
      );
      final userProvider = context.read<UserProvider>();
      final String? token = await userProvider.setAndGetToken();
      if (token != null) {
        log(token);
        context.read<MediaProvider>().getDownloadsList();
        RequestService.token = token;
        final result = await userProvider.getUserInfo();
        if (!result) {
          StorageService.delete(key: 'token');
          Navigator.of(context).pushNamedAndRemoveUntil(
            Routes.splash,
            (_) => false,
          );
          return;
        }
        await ServerDataProvider.getData();
      }
      Navigator.of(context).pushReplacementNamed(
        token == null ? Routes.authenticaion : Routes.home,
        arguments: token == null ? false : null,
      );
    } catch (e) {
      setState(() {
        _errorOccured = true;
      });
    }
  }
}
