import 'dart:async';

import 'package:flutter/material.dart';
import 'package:openim_common/openim_common.dart';

/// 通话页进出：250ms 自下而上滑入 ease-out，不可打断。
class CallPageHost extends StatefulWidget {
  const CallPageHost({
    Key? key,
    required this.child,
  }) : super(key: key);

  final Widget child;

  @override
  CallPageHostState createState() => CallPageHostState();
}

class CallPageHostState extends State<CallPageHost> with SingleTickerProviderStateMixin {
  late final AnimationController _controller;
  Completer<void>? _dismissing;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      vsync: this,
      duration: Styles.callPageMotion,
    );
    _controller.forward();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _controller.duration = Styles.motionOf(context, Styles.callPageMotion);
  }

  Future<void> dismiss() {
    if (_dismissing != null) return _dismissing!.future;
    _dismissing = Completer<void>();
    final future = _controller.status == AnimationStatus.dismissed
        ? Future<void>.value()
        : _controller.reverse();
    future.whenComplete(() {
      if (_dismissing?.isCompleted == false) {
        _dismissing!.complete();
      }
    });
    return _dismissing!.future;
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SlideTransition(
      position: Tween<Offset>(
        begin: const Offset(0, 1),
        end: Offset.zero,
      ).animate(CurvedAnimation(parent: _controller, curve: Curves.easeOut)),
      child: Material(
        color: Styles.c_callBg,
        child: widget.child,
      ),
    );
  }
}
