import 'dart:async';

import 'package:easy_localization/easy_localization.dart' hide tr;
import 'package:flutter/material.dart';

import 'package:userfront/i18n.dart';
import '../services/web_window.dart';
import 'locale_storage.dart';
import 'locale_utils.dart';

class LocaleGate extends StatefulWidget {
  const LocaleGate({super.key, required this.localeCode, required this.child});

  final String localeCode;
  final Widget child;

  @override
  State<LocaleGate> createState() => _LocaleGateState();
}

class _LocaleGateState extends State<LocaleGate> {
  bool _syncScheduled = false;

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _scheduleLocaleSync();
  }

  @override
  void didUpdateWidget(LocaleGate oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.localeCode != widget.localeCode) {
      _scheduleLocaleSync();
    }
  }

  void _scheduleLocaleSync() {
    if (_syncScheduled) {
      return;
    }
    _syncScheduled = true;
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _syncScheduled = false;
      if (!mounted) {
        return;
      }
      unawaited(_applyLocale());
    });
  }

  Future<void> _applyLocale() async {
    if (!mounted) {
      return;
    }
    final normalized = normalizeLocaleCode(widget.localeCode);
    LocaleStorage.write(normalized);
    final localization = EasyLocalization.of(context);
    if (localization == null) {
      return;
    }
    if (localization.currentLocale?.languageCode == normalized) {
      webWindow.setTitle(tr('ui.userfront.app_title'));
      return;
    }
    await localization.setLocale(Locale(normalized));
    if (!mounted) {
      return;
    }
    webWindow.setTitle(tr('ui.userfront.app_title'));
  }

  @override
  Widget build(BuildContext context) => widget.child;
}
