import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:mypoint_flutter_app/screen/popup_manager/popup_manager_model.dart';
import 'package:mypoint_flutter_app/screen/popup_manager/popup_manager_viewmodel.dart';

/// Logger tuỳ bạn hook vào hệ thống hiện có (Firebase, MoEngage, …)
void logPopupShowing({required String popupId, required String requestId}) {
  // UserFollowLogger(.popup_showing, data: trackingInfo).log()
  // FirebaseAnalyticManager.shared.trackEvent(.popupShowing, info: trackingInfo)
  debugPrint('[Popup] showing: popup_id=$popupId, request_id=$requestId');
}

void logPopupClick({required String popupId}) {
  // FirebaseAnalyticManager.shared.add(event: LogEventFollowInfo(name: .popup, id: popupId))
  debugPrint('[Popup] click: popup_id=$popupId');
}

Future<void> showPopupManagerScreen(
  BuildContext context, {
  required PopupManagerModel modelPopup,
  VoidCallback? onDismissed,
}) async {
  int timeCountDown = int.tryParse(modelPopup.timeCountDown ?? '1000000') ?? 1000000;
  final popupId = modelPopup.id ?? '';
  final requestId = modelPopup.requestId ?? '';
  logPopupShowing(popupId: popupId, requestId: requestId);
  await PopupManagerViewModel.instance.markShownOnce(popupId);
  await showGeneralDialog(
    context: context,
    barrierDismissible: false,
    barrierLabel: 'popup',
    transitionDuration: const Duration(milliseconds: 220),
    pageBuilder: (_, __, ___) {
      return _BasePopupView(
        model: modelPopup,
        initialCountdown: timeCountDown,
        onDismissed: () {
          onDismissed?.call();
        },
      );
    },
    transitionBuilder: (_, anim, __, child) {
      return Transform.scale(scale: 0.96 + (0.04 * anim.value), child: Opacity(opacity: anim.value, child: child));
    },
  );
}

class _BasePopupView extends StatefulWidget {
  final PopupManagerModel model;
  final int initialCountdown;
  final VoidCallback onDismissed;

  const _BasePopupView({required this.model, required this.initialCountdown, required this.onDismissed});

  @override
  State<_BasePopupView> createState() => _BasePopupViewState();
}

class _BasePopupViewState extends State<_BasePopupView> {
  Timer? _timer;
  late int _countdown;
  double? _imageAspectRatio;
  bool _imageLoaded = false;

  @override
  void initState() {
    super.initState();
    _countdown = widget.initialCountdown;
    _startTimer();
  }

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }

  void _startTimer() {
    _timer = Timer.periodic(const Duration(seconds: 1), (t) {
      if (!mounted) return;
      if (_countdown > 0) {
        setState(() => _countdown -= 1);
      } else {
        _dismiss();
      }
    });
  }

  void _dismiss() {
    _timer?.cancel();
    widget.onDismissed();
    if (mounted) Navigator.of(context).pop();
  }

  void _onContentTap() {
    logPopupClick(popupId: widget.model.id ?? '');
    debugPrint(
      'Popup clicked: ${widget.model.directional?.clickActionType ?? ''} - ${widget.model.directional?.clickActionParam ?? ''}',
    );
    _timer?.cancel();
    _dismiss();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      widget.model.directional?.begin();
    });
  }

  @override
  Widget build(BuildContext context) {
    final model = widget.model;
    final title = (model.popupTitleTemplate ?? '').trim();
    final body = (model.popupBodyTemplate ?? '').trim();
    final hasTitle = title.isNotEmpty;
    final hasBody = body.isNotEmpty;
    final media = MediaQuery.of(context);
    final screenW = media.size.width;
    final maxPopupHeight = media.size.height - 200;
    final imageCornerRadius = 12.0; // ảnh trên cùng vẫn bo 12
    final subHeaderRadius = (hasBody && !hasTitle) ? 12.0 : 0.0;

    return Material(
      color: Colors.black54,
      child: Center(
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 20),
          child: LayoutBuilder(
            builder: (context, constraints) {
              double imageHeight = 0;
              if (_imageAspectRatio != null && _imageAspectRatio! > 0) {
                // image.size.height*(screenW - 40)/image.size.width
                imageHeight = (screenW - 40) / _imageAspectRatio!;
              }

              final content = Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Align(
                    alignment: Alignment.topRight,
                    child: IconButton(icon: const Icon(Icons.close, color: Colors.white), onPressed: _dismiss),
                  ),
                  ConstrainedBox(
                    constraints: BoxConstraints(maxHeight: maxPopupHeight, minWidth: double.infinity),
                    child: GestureDetector(
                      onTap: _onContentTap,
                      child: ClipRRect(
                        borderRadius: BorderRadius.circular(12),
                        child: Material(
                          color: Colors.white,
                          child: SingleChildScrollView(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.stretch,
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                // Ảnh
                                _buildImage(
                                  url: model.imageURL,
                                  heightHint: imageHeight > 0 ? imageHeight : null,
                                  cornerRadius: imageCornerRadius,
                                ),
                                // Header
                                if (hasTitle)
                                  Padding(
                                    padding: const EdgeInsets.fromLTRB(16, 16, 16, 0),
                                    child: Text(
                                      title,
                                      style: const TextStyle(fontSize: 18, fontWeight: FontWeight.w700),
                                    ),
                                  ),
                                // SubHeader
                                if (hasBody)
                                  Container(
                                    decoration: BoxDecoration(
                                      color: const Color(0xFFF6F7F9),
                                      borderRadius: BorderRadius.vertical(bottom: Radius.circular(subHeaderRadius)),
                                    ),
                                    padding: const EdgeInsets.fromLTRB(16, 10, 16, 16),
                                    child: Text(body, style: const TextStyle(fontSize: 15, height: 1.4)),
                                  ),
                                // Dòng trạng thái đếm ngược (tuỳ chọn)
                                Padding(
                                  padding: const EdgeInsets.fromLTRB(16, 10, 16, 16),
                                  child: Text(
                                    _countdown > 0 ? '$_countdown seconds dismiss popup' : 'Closing…',
                                    style: TextStyle(fontSize: 12, color: Colors.grey.shade600),
                                    textAlign: TextAlign.right,
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ),
                      ),
                    ),
                  ),
                ],
              );
              return content;
            },
          ),
        ),
      ),
    );
  }

  Widget _buildImage({required String? url, double? heightHint, required double cornerRadius}) {
    final imageUrl = (url ?? '').trim();
    if (imageUrl.isEmpty) {
      return Container(
        height: 160,
        color: const Color(0xFFE9ECF1),
        alignment: Alignment.center,
        child: const Icon(Icons.image, size: 48, color: Colors.grey),
      );
    }

    return ClipRRect(
      borderRadius: BorderRadius.vertical(top: Radius.circular(cornerRadius)),
      child: _NetworkImageWithInfo(
        imageUrl: imageUrl,
        heightHint: heightHint,
        onResolved: (width, height) {
          if (!_imageLoaded && width > 0 && height > 0) {
            setState(() {
              _imageLoaded = true;
              _imageAspectRatio = width / height; // width/height
            });
          }
        },
      ),
    );
  }
}

/// Image.network nhưng lấy được kích thước ảnh thật để tính tỉ lệ
class _NetworkImageWithInfo extends StatefulWidget {
  final String imageUrl;
  final double? heightHint;
  final void Function(int width, int height) onResolved;
  const _NetworkImageWithInfo({required this.imageUrl, required this.onResolved, this.heightHint});

  @override
  State<_NetworkImageWithInfo> createState() => _NetworkImageWithInfoState();
}

class _NetworkImageWithInfoState extends State<_NetworkImageWithInfo> {
  ImageStream? _stream;
  ImageInfo? _info;

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

  @override
  void didUpdateWidget(covariant _NetworkImageWithInfo oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.imageUrl != widget.imageUrl) _resolve();
  }

  void _resolve() {
    _stream?.removeListener(ImageStreamListener(_handleImage));
    final provider = NetworkImage(widget.imageUrl);
    final stream = provider.resolve(createLocalImageConfiguration(context));
    _stream = stream;
    stream.addListener(ImageStreamListener(_handleImage));
  }

  void _handleImage(ImageInfo info, bool _) {
    _info = info;
    widget.onResolved(info.image.width, info.image.height);
    setState(() {});
  }

  @override
  void dispose() {
    _stream?.removeListener(ImageStreamListener(_handleImage));
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (_info == null && widget.heightHint == null) {
      return AspectRatio(aspectRatio: 16 / 9, child: Container(color: const Color(0xFFE9ECF1)));
    }
    final height = widget.heightHint;
    return Image.network(widget.imageUrl, height: height, width: double.infinity, fit: BoxFit.cover);
  }
}
