import 'dart:async';

import 'package:fis_i18n/i18n.dart';
import 'package:fis_ui/index.dart';
import 'package:fis_ui/interface/interactive_container.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/lab/color/lab_colors.dart';
import 'package:flyinsono/lab/env/env.dart';
import 'package:flyinsono/lab/style/lab_box_decoration.dart';
import 'package:flyinsono/pages/schedule/schedule_notification/schedule_notification_controller.dart';

/// 消息卡片
class FNotificationCard extends FStatelessWidget
    implements FInteractiveContainer {
  String get pageName => 'FNotificationCard';
  const FNotificationCard(
      {super.key, required this.notification, required this.onClose});
  final ApplicationNotification notification;
  final VoidCallback onClose;
  @override
  FWidget build(BuildContext context) {
    return FContainer(
      decoration: kIsLab
          ? LabBoxDecoration.base
          : BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(8),
              boxShadow: [
                BoxShadow(
                  color: Colors.black12,
                  blurRadius: 4,
                  spreadRadius: 2,
                ),
              ],
            ),
      margin: const EdgeInsets.symmetric(horizontal: 20, vertical: 8),
      width: double.infinity,
      child: FColumn(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildNotificationHeader(),
          FContainer(
            padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 8),
            child: _buildTitleByType(),
          ),
          ..._buildInfoContents(notification.infoItems),
          if (notification.callback != null) _budilDetailButton(),
          const FSizedBox(height: 12),
        ],
      ),
    );
  }

  FWidget _buildNotificationHeader() {
    return FContainer(
      decoration: const BoxDecoration(
        border: Border(
          bottom: BorderSide(
            color: Colors.black12,
            width: 1,
          ),
        ),
      ),
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
      child: FRow(
        children: [
          _buildIconByType(notification.type),
          const FSizedBox(width: 8),
          FText(
            notification.title,
            style: TextStyle(
              color: kIsLab ? LabColors.base900 : null,
            ),
          ),
          FExpanded(child: FContainer()),
          FInkWell(
            onTap: () {
              onClose();
            },
            child: FIcon(
              Icons.close,
              color: kIsLab ? LabColors.base900 : null,
            ),
          ),
        ],
      ),
    );
  }

  FWidget _buildTitleByType() {
    if (notification.type == NotificationType.countdown) {
      return _CountdownText(
        countdownTime: notification.countdownMinutes!,
        startTime: notification.countdownFinishTime!,
        endText: notification.countdownFinishText!,
        displayText: notification.infoTitle,
      );
    } else {
      return FText(
        notification.infoTitle,
        style: TextStyle(
          color: kIsLab ? LabColors.base900 : Color.fromARGB(255, 30, 30, 30),
          fontSize: 16,
          fontWeight: FontWeight.w600,
        ),
      );
    }
  }

  FWidget _buildIconByType(NotificationType type) {
    switch (type) {
      case NotificationType.notification:
        return const FIcon(
          Icons.info_outline,
          color: Colors.blue,
        );
      case NotificationType.warning:
        return const FIcon(
          Icons.warning_amber_outlined,
          color: Colors.orange,
        );
      case NotificationType.error:
        return const FIcon(
          Icons.error_outline,
          color: Colors.red,
        );
      case NotificationType.success:
        return const FIcon(
          Icons.check_circle_outline,
          color: Colors.green,
        );
      case NotificationType.countdown:
        return const FIcon(
          Icons.alarm,
          color: Colors.orange,
        );
    }
  }

  List<FWidget> _buildInfoContents(List<NotificationInfoItem> infoContents) {
    return infoContents
        .map(
          (e) => FContainer(
            margin: const EdgeInsets.only(bottom: 8),
            padding: const EdgeInsets.symmetric(horizontal: 20),
            child: FRow(
              children: [
                FExpanded(
                  flex: 1,
                  child: FText(
                    e.title,
                    style: const TextStyle(
                      color: Color.fromARGB(255, 40, 40, 40),
                      fontSize: 14,
                    ),
                  ),
                ),
                FExpanded(
                  /// TODO:[Gavin] 多语言-UI-整合
                  flex: i18nBook.isCurrentChinese ? 3 : 1,
                  child: FText(
                    e.content,
                    style: const TextStyle(
                      color: Color.fromARGB(255, 63, 63, 63),
                      fontSize: 14,
                    ),
                  ),
                ),
              ],
            ),
          ),
        )
        .toList();
  }

  FWidget _budilDetailButton() {
    return FContainer(
      padding: const EdgeInsets.symmetric(vertical: 5),
      child: FAlign(
        alignment: Alignment.center,
        child: FElevatedButton(
          child: FText(notification.callbackButtonText ??
              i18nBook.notification.detail.t),
          onPressed: () {
            onClose();
            notification.callback!();
          },
          businessParent: this,
          name: 'detail',
        ),
      ),
    );
  }
}

/// 有状态的倒计时文字
class _CountdownText extends FStatefulWidget {
  _CountdownText(
      {Key? key,
      required this.countdownTime,
      required this.startTime,
      required this.displayText,
      required this.endText})
      : super(key: key);

  /// 倒计时的分钟数
  final int countdownTime;

  /// 显示的文字，其中使用 “###” 用作占位，来替换时间
  final String displayText;

  /// 倒计时结束后的显示文字
  final String endText;

  /// 开始时间
  final DateTime startTime;
  @override
  _CountdownTextState createState() => _CountdownTextState();
}

class _CountdownTextState extends FState<_CountdownText> {
  /// displayText 中的 ### 替换为 countdownTime，每过一分钟更新一次
  late Timer _timer;
  late int _countdownTime;
  late String _displayText;
  @override
  void initState() {
    super.initState();
    _countdownTime = widget.countdownTime;
    _displayText =
        widget.displayText.replaceAll('###', _formatMinToHour(_countdownTime));
    _timer = Timer.periodic(const Duration(seconds: 10), (timer) {
      _countdownTime = _calculateTimeDiff(widget.startTime);
      if (_countdownTime > 1) {
        setState(() {
          _displayText = widget.displayText
              .replaceAll('###', _formatMinToHour(_countdownTime));
        });
      } else {
        setState(() {
          _displayText = widget.endText;
        });
        _timer.cancel();
      }
    });
  }

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

  @override
  FWidget build(BuildContext context) {
    return FText(
      _displayText,
      style: const TextStyle(
        color: Color.fromARGB(255, 30, 30, 30),
        fontSize: 16,
        fontWeight: FontWeight.w600,
      ),
    );
  }

  ///  获取倒计时的文字
  String _formatMinToHour(int countdownTime) {
    /// 如果分钟数超过 60，在前面显示小时数
    if (countdownTime > 60) {
      final int hour = countdownTime ~/ 60;
      final int minute = countdownTime % 60;
      return '$hour${i18nBook.calendar.hour4Duration.t}$minute${i18nBook.calendar.minute4Duration.t}';
    } else {
      return '$countdownTime${i18nBook.calendar.minute4Duration.t}';
    }
  }

  /// 计算时间差分钟数
  int _calculateTimeDiff(DateTime startTime) {
    final int diff = startTime.difference(DateTime.now()).inMinutes;
    return diff;
  }
}
