import 'package:flutter/material.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';
import '../../core/i18n/app_localizations.dart';
import '../../core/theme/app_colors_extension.dart';

/// 通用 loading 弹窗。
///
/// 深灰色半透明蒙版，居中 loading 动画 + 可自定义文本。
/// 蒙版透明但不可点击穿透。
///
/// 使用方式：
/// ```dart
/// LoadingDialog.show(context, text: '数据加载中...');
/// // ... 异步操作 ...
/// LoadingDialog.hide(context);
/// ```
class LoadingDialog {
  LoadingDialog._();

  /// 显示 loading 弹窗。[text] 默认为 i18n "loading"（加载中…）。
  static void show(BuildContext context, {String? text}) {
    showDialog(
      context: context,
      barrierColor: Colors.transparent,
      barrierDismissible: false,
      builder: (_) => _LoadingContent(text: text),
    );
  }

  /// 关闭 loading 弹窗。即使弹窗已被关闭也不会抛异常。
  static void hide(BuildContext context) {
    Navigator.of(context).maybePop();
  }
}

class _LoadingContent extends StatelessWidget {
  final String? text;
  const _LoadingContent({this.text});

  @override
  Widget build(BuildContext context) {
    final l10n = AppLocalizations.of(context);
    final colors = Theme.of(context).extension<AppColorsExtension>()!;
    return Center(
      child: Container(
        width: 160,
        padding: const EdgeInsets.fromLTRB(16, 24, 16, 20),
        decoration: BoxDecoration(
          color: colors.loadingCard,
          borderRadius: BorderRadius.circular(12),
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            IconTheme(
              data: const IconThemeData(color: Colors.white),
              child: const TDLoading(
                size: TDLoadingSize.large,
                icon: TDLoadingIcon.activity,
              ),
            ),
            const SizedBox(height: 14),
            Text(
              text ?? l10n.get('loading'),
              softWrap: false,
              style: const TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.w500,
                color: Colors.white,
              ),
            ),
          ],
        ),
      ),
    );
  }
}
