import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:mypoint_flutter_app/features/splash/splash_screen_viewmodel.dart';
import 'package:mypoint_flutter_app/shared/widgets/alert/custom_alert_dialog.dart';
import 'package:mypoint_flutter_app/core/services/web/web_helper.dart';
import '../../shared/widgets/base_view/base_screen.dart';
import '../../shared/widgets/base_view/basic_state.dart';
import 'models/check_update_response_model.dart';
import '../../core/theme/base_color.dart';
import '../../shared/widgets/alert/data_alert_model.dart';

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

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

class _SplashScreenState extends BaseState<SplashScreen> with BasicState {
  final SplashScreenViewModel _viewModel = Get.put(SplashScreenViewModel());
  Future<void>? _webSplashCacheFuture;
  bool _webLoaderNotified = false;

  @override
  void initState() {
    super.initState();
    _viewModel.checkUpdateResponse = (data) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        final updateData = (data?.updateRequest ?? []).firstOrNull;
        if (updateData == null) {
          _viewModel.makeDataFollowInitApp();
          return;
        }
        if (updateData.status == UpdateStatus.none) {
          _viewModel.makeDataFollowInitApp();
        } else {
          _showSuggestUpdateAlert(updateData);
        }
      });
    };
    _viewModel.checkUpdateApp();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    if (kIsWeb && _webSplashCacheFuture == null) {
      _webSplashCacheFuture = precacheImage(
        const AssetImage('assets/images/splash_screen.webp'),
        context,
      ).catchError((error, stackTrace) {
        debugPrint('Failed to precache splash background: $error');
        debugPrintStack(stackTrace: stackTrace);
      }).whenComplete(() {
        if (!mounted) return;
        WidgetsBinding.instance.addPostFrameCallback((_) {
          _notifyWebLoaderReady();
        });
      });
    }
  }

  void _notifyWebLoaderReady() {
    if (!kIsWeb || _webLoaderNotified || !mounted) return;
    _webLoaderNotified = true;
    webNotifySplashScreenReady();
  }

  @override
  Widget createBody() {
    final path = kIsWeb ? "assets/images/splash_screen.webp" : "assets/images/splash_screen.png";
    return Scaffold(
      backgroundColor: Colors.blue,
      body: Stack(
        children: [
          Image.asset(
            path,
            width: double.infinity,
            height: double.infinity,
            fit: BoxFit.cover,
          ),
          Center(
              child: kIsWeb ? SizedBox.shrink() : CircularProgressIndicator()
          )
        ],
      ),
    );
  }

  void _showSuggestUpdateAlert(CheckUpdateResponseModel data) {
    final buttons = data.status == UpdateStatus.force
        ? [AlertButton(
              text: "Cập nhật ngay",
              onPressed: () {
                _viewModel.openLink();
              },
              bgColor: BaseColor.primary500,
              textColor: Colors.white,
            ),]
        : [AlertButton(
              text: "Cập nhật",
              onPressed: () {
                _viewModel.openLink();
              },
              bgColor: BaseColor.primary500,
              textColor: Colors.white,
            ),
            AlertButton(
              text: "Để sau",
              onPressed: () {
                Get.back();
                _viewModel.makeDataFollowInitApp();
              },
              bgColor: Colors.white,
              textColor: BaseColor.primary500,
            ),];
    final model = DataAlertModel(
      localHeaderImage: "assets/images/ic_pipi_03.png",
      title: data.updateTitle ?? "Cập nhật phiên bản mới",
      description: data.updateMessage ?? "Cập nhật phiên bản mới",
      buttons: buttons,
    );
    showAlert(data: model, showCloseButton: false, direction: ButtonsDirection.row);
  }
}
