import 'dart:async';

import 'package:flutter/material.dart';
import 'package:vitalapp/architecture/network_connectivity.dart';
import 'package:vitalapp/global.dart';
import 'package:vitalapp/pages/help/help_dialog.dart';
import 'package:fis_common/logger/logger.dart';

class HeaderStatusBar extends StatelessWidget {
  const HeaderStatusBar({super.key});

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        _NetStatusWidget(),
        const SizedBox(width: 2),
        IconButton(
          onPressed: () {
            HelpDialog.show();
          },
          icon: const Icon(Icons.help, size: 36, color: Colors.white),
        ),
      ],
    );
  }
}

class _NetStatusWidget extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _NetStatusWidgetState();
}

class _NetStatusWidgetState extends State<_NetStatusWidget> {
  Timer? _waitTimer;
  bool _isOnline = false;

  @override
  void initState() {
    super.initState();
    _isOnline = kIsOnline;
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      netChecker.onlineChangedEvent.addListener(_onlineChanged);
    });
  }

  @override
  void dispose() {
    netChecker.onlineChangedEvent.removeListener(_onlineChanged);
    super.dispose();
  }

  void _onlineChanged(_, e) {
    if (_isOnline == e) {
      return;
    }
    setState(() {
      _isOnline = e;
      if (e) {
        _stopWaitNetRecover();
      } else {
        _waitNetRecover();
      }
    });
  }

  void _waitNetRecover() {
    if (_waitTimer != null) {
      return;
    }

    logger.i("HeaderStatusBar - Wait network start.");
    print("HeaderStatusBar - Wait network start.");
    _waitTimer = Timer(const Duration(milliseconds: 5 * 1000), () {
      setState(() {
        _waitTimer = null;
      });
      logger.i("HeaderStatusBar - Wait network done.");
      print("HeaderStatusBar - Wait network done.");
    });
  }

  void _stopWaitNetRecover() {
    if (_waitTimer != null) {
      _waitTimer?.cancel();
      _waitTimer = null;
      logger.i("HeaderStatusBar - Wait network abort.");
      print("HeaderStatusBar - Wait network abort.");
    }
  }

  @override
  Widget build(BuildContext context) {
    if (_isOnline) {
      return const Tooltip(
        triggerMode: TooltipTriggerMode.tap,
        message: "网络已连接",
        child: Icon(Icons.wifi, size: 36, color: Colors.green),
      );
    } else {
      if (_waitTimer == null) {
        return const Tooltip(
          triggerMode: TooltipTriggerMode.tap,
          message: "网络已断开",
          child: Icon(Icons.wifi_off_outlined, size: 36, color: Colors.red),
        );
      } else {
        return Tooltip(
          triggerMode: TooltipTriggerMode.tap,
          message: "网络等待中",
          child: SizedBox(
            width: 36,
            height: 36,
            child: _NetWaitingWidget(),
          ),
        );
      }
    }
  }
}

class _NetWaitingWidget extends StatefulWidget {
  @override
  State<_NetWaitingWidget> createState() => _NetWaitingWidgetState();
}

class _NetWaitingWidgetState extends State<_NetWaitingWidget> {
  static final _color = Colors.orange.shade200;
  bool _isShow = false;
  Timer? _timer;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      _timer = Timer.periodic(const Duration(milliseconds: 1000), (timer) {
        setState(() {
          _isShow = !_isShow;
        });
      });
    });
  }

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

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Icon(
          Icons.wifi,
          size: 36,
          color: _isShow ? _color : _color.withOpacity(.4),
        ),
        const Center(
          child: Padding(
            padding: EdgeInsets.all(8),
            child: CircularProgressIndicator(
              strokeWidth: 4,
              color: Colors.white,
            ),
          ),
        ),
      ],
    );
  }
}
