import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:niogu_app/core/constants/app_asset.dart';
import 'package:niogu_app/core/constants/app_color.dart';
import 'package:niogu_app/core/constants/app_font_size.dart';
import 'package:niogu_app/core/database/app_database.dart';
import 'package:niogu_app/core/database/database_holder.dart';
import 'package:niogu_app/core/providers/app_provider.dart';
import 'package:niogu_app/core/router/app_route.dart';
import 'package:niogu_app/core/system/system_setting.dart';
import 'package:sizer/sizer.dart';

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

  @override
  ConsumerState<SplashScreen> createState() => _SplashScreenState();
}

class _SplashScreenState extends ConsumerState<SplashScreen>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<double> _fadeAnimation;
  late Animation<Offset> _slideAnimation;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    _controller = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 2),
    );

    _fadeAnimation = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(CurvedAnimation(parent: _controller, curve: Curves.easeIn));

    _slideAnimation = Tween<Offset>(
      begin: const Offset(0, 0.5),
      end: Offset.zero,
    ).animate(CurvedAnimation(parent: _controller, curve: Curves.easeOutQuart));

    _controller.forward();

    WidgetsBinding.instance.addPostFrameCallback((_) {
      _initDatabase();

      _setCurrentOutlet();

      _setCurrentUser();

      if (!mounted) return;

      Future.delayed(const Duration(seconds: 4), () {
        context.goNamed(AppRoute.homeScreen);
      });
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    _controller.dispose();
    super.dispose();
  }

  Future<void> _initDatabase() async {
    final tenantCode = await SystemSetting.getTenantCode();

    if (tenantCode != null) {
      final appDatabase = AppDatabase();

      await setDatabase(appDatabase);

      await appDatabase.customSelect("SELECT 1").getSingle();

      ref.invalidate(appDatabaseProvider);

      final syncService = ref.read(syncServiceProvider);

      syncService.stopWatching();

      await syncService.startWatching();
    }
  }

  Future<void> _setCurrentOutlet() async {
    final currentOutletId = await SystemSetting.getCurrentOutletId();

    final currentOutletName = await SystemSetting.getCurrentOutletName();

    ref.read(currentOutletIdProvider.notifier).state = currentOutletId;

    ref.read(currentOutletNameProvider.notifier).state = currentOutletName;
  }

  Future<void> _setCurrentUser() async {
    final currentUserId = await SystemSetting.getCurrentUserId();

    final currentUserName = await SystemSetting.getCurrentUserName();

    final currentUserEmail = await SystemSetting.getCurrentUserEmail();

    final currentUserRole = await SystemSetting.getCurrentUserRole();

    final outletIdByOwner = await SystemSetting.getOutletIdByOwner();

    final isLoggedIn = await SystemSetting.isLoggedIn();

    ref.read(currentUserIdProvider.notifier).state = currentUserId;

    ref.read(currentUserNameProvider.notifier).state = currentUserName;

    ref.read(currentUserEmailProvider.notifier).state = currentUserEmail;

    ref.read(currentUserRoleProvider.notifier).state = currentUserRole;

    ref.read(outletIdByOwnerProvider.notifier).state = outletIdByOwner;

    ref.read(currentStatusLoginProvider.notifier).state = isLoggedIn;
  }

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        final bool isTablet = 100.w >= 600;
        return SafeArea(
          top: false,
          bottom: true,
          right: false,
          left: false,
          child: Scaffold(
            backgroundColor: Colors.white,
            body: Stack(
              children: [
                Center(
                  child: FadeTransition(
                    opacity: _fadeAnimation,
                    child: SlideTransition(
                      position: _slideAnimation,
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Image.asset(
                            AppAsset.LOGO_UPDATE,
                            height: 30.w,
                            width: 30.w,
                            fit: BoxFit.contain,
                          ),

                          SizedBox(height: 3.h),

                          Text(
                            "niogu",
                            style: TextStyle(
                              fontSize: AppFontSize.extraLarge.sp,
                              fontWeight: FontWeight.w900,
                              color: AppColor.primaryColor,
                              letterSpacing: -1.0,
                              height: 1.0,
                            ),
                          ),

                          SizedBox(height: 3.h),

                          Text(
                            "Cara Mudah Berniaga",
                            style: TextStyle(
                              fontSize: AppFontSize.large.sp,
                              color: Colors.grey[500],
                              letterSpacing: 2.0,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                ),

                Positioned(
                  bottom: 5.h,
                  left: 0,
                  right: 0,
                  child: FadeTransition(
                    opacity: _fadeAnimation,
                    child: Column(
                      children: [
                        Text(
                          "Powered By",
                          style: TextStyle(
                            fontSize: isTablet
                                ? AppFontSize.medium.sp
                                : AppFontSize.small.sp,
                            color: Colors.grey[500],
                          ),
                        ),
                        SizedBox(height: 0.5.h),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Icon(
                              Icons.bolt_rounded,
                              size: isTablet ? 6.w : 4.w,
                              color: AppColor.primaryColor,
                            ),
                            SizedBox(width: 1.w),
                            Text(
                              "PT. Niaga Nusantara",
                              style: TextStyle(
                                fontSize: isTablet
                                    ? AppFontSize.medium.sp
                                    : AppFontSize.small.sp,
                                fontWeight: FontWeight.bold,
                                color: Colors.black87,
                              ),
                            ),
                          ],
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }
}
