import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:latlong2/latlong.dart';
import 'package:niogu_ecommerce_v1/core/constant/app_asset.dart';
import 'package:niogu_ecommerce_v1/core/constant/app_font_size.dart';
import 'package:niogu_ecommerce_v1/core/providers/app_provider.dart';
import 'package:niogu_ecommerce_v1/core/router/app_route.dart';
import 'package:niogu_ecommerce_v1/core/system/system_setting.dart';
import 'package:niogu_ecommerce_v1/features/cart/presentation/providers/cart_provider.dart';
import 'package:niogu_ecommerce_v1/features/home/domain/entities/home.dart';
import 'package:niogu_ecommerce_v1/features/home/presentation/providers/home_provider.dart';
import 'package:sizer/sizer.dart';

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

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

class _SplashScreenState extends ConsumerState<SplashScreen> {
  @override
  void initState() {
    super.initState();

    WidgetsBinding.instance.addPostFrameCallback((_) async {
      final currentOutlet = await _setCurrentOutlet();

      _setCustomerInfo();

      _setCartItems();

      if (!mounted) return;

      if (currentOutlet == null) return;

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

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

  Future<MainOutlet?> _setCurrentOutlet() async {
    final mainOutlet = await ref.read(homeRepositoryProvider).fetchMainOutlet();

    if (mainOutlet == null) return null;

    await SystemSetting.switchOutlet(
      outletId: mainOutlet.uuid,
      outletName: mainOutlet.name,
      outletPhone: mainOutlet.phoneNumber,
      outletLocation: mainOutlet.location,
      outletCoordinate: LatLng(
        mainOutlet.latitude ?? 0.0,
        mainOutlet.longitude ?? 0.0,
      ),
    );

    final currentOutletId = await SystemSetting.getCurrentOutletId();

    final currentOutletName = await SystemSetting.getCurrentOutletName();

    final currentOutletPhone = await SystemSetting.getCurrentOutletPhone();

    final currentOutletLocation =
        await SystemSetting.getCurrentOutletLocation();

    final currentOutletCoordinate =
        await SystemSetting.getCurrentOutletCoordinate();

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

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

    ref.read(currentOutletPhoneProvider.notifier).state = currentOutletPhone;

    ref.read(currentOutletLocationProvider.notifier).state =
        currentOutletLocation;

    ref.read(currentOutletCoordinateProvider.notifier).state =
        currentOutletCoordinate;

    return mainOutlet;
  }

  Future<void> _setCustomerInfo() async {
    final customerId = await SystemSetting.getCurrentCustomerId();

    final customerName = await SystemSetting.getCurrentCustomerName();

    final customerEmail = await SystemSetting.getCurrentCustomerEmail();

    final customerPhone = await SystemSetting.getCurrentCustomerPhone();

    final isLoggedIn = await SystemSetting.isLoggedIn();

    ref.read(currentCustomerIdProvider.notifier).state = customerId;

    ref.read(currentCustomerNameProvider.notifier).state = customerName;

    ref.read(currentCustomerEmailProvider.notifier).state = customerEmail;

    ref.read(currentCustomerPhoneProvider.notifier).state = customerPhone;

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

  Future<void> _setCartItems() async {
    final cartItems = await SystemSetting.getCartItemByOutlet();

    ref.read(cartItemControllerProvider.notifier).hydrate(cartItems);
  }

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        return SafeArea(
          top: false,
          bottom: true,
          right: false,
          left: false,
          child: Scaffold(
            backgroundColor: Colors.white,
            body: Stack(
              alignment: Alignment.center,
              children: [
                Center(
                  child: Image.asset(
                    AppAsset.LOGO,
                    fit: BoxFit.cover,
                    height: 45.w,
                    width: 45.w,
                  ),
                ),

                Positioned(
                  bottom: 5.h,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text(
                        "powered by ",
                        style: TextStyle(
                          fontSize: (AppFontSize.small - 2).sp,
                          color: Colors.grey.shade500,
                        ),
                      ),
                      Text(
                        "Niogu",
                        style: TextStyle(
                          fontSize: (AppFontSize.small - 2).sp,
                          fontWeight: FontWeight.bold,
                          color: Colors.grey.shade500,
                          letterSpacing: 1,
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }
}
