import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:flutter_markdown/flutter_markdown.dart';
import '../../../model/response/kr_message_list.dart';
import '../controllers/kr_message_controller.dart';
import 'package:kaer_with_panels/app/widgets/kr_app_text_style.dart';
import 'package:kaer_with_panels/app/localization/app_translations.dart';

class KRMessageView extends GetView<KRMessageController> {
  const KRMessageView({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      extendBodyBehindAppBar: true,
      backgroundColor: Theme.of(context).primaryColor,
      body: Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [
              Color.fromRGBO(23, 151, 255, 0.15), // 渐变开始颜色
              Color.fromRGBO(23, 151, 255, 0.05), // 中间过渡颜色
              // 非渐变色区域
            ],
            stops: [0.0, 0.28], // 调整渐变结束位置
          ),
        ),
        child: Column(
          children: [
            AppBar(
              backgroundColor: Colors.transparent,
              elevation: 0,
              leading: IconButton(
                icon: Icon(
                  Icons.arrow_back_ios,
                  size: 20.r,
                  color: Theme.of(context).textTheme.bodyMedium?.color,
                ),
                onPressed: () => Get.back(),
              ),
              title: Text(
                AppTranslations.kr_message.title,
                style: KrAppTextStyle(
                  color: Theme.of(context).textTheme.bodyMedium?.color,
                  fontSize: 16,
                  fontWeight: FontWeight.w500,
                ),
              ),
              centerTitle: true,
            ),
            Expanded(
              child: Obx(
                () => EasyRefresh(
                  controller: controller.refreshController,
                  onRefresh: controller.kr_onRefresh,
                  onLoad: controller.kr_onLoadMore,
                  header: DeliveryHeader(
                    triggerOffset: 50.0,
                    springRebound: true,
                  ),
                  footer: DeliveryFooter(
                    triggerOffset: 50.0,
                    springRebound: true,
                  ),
                  child: ListView.builder(
                    physics: const AlwaysScrollableScrollPhysics(),
                    padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
                    itemCount: controller.kr_messages.length,
                    itemBuilder: (context, index) {
                      final message = controller.kr_messages[index];
                      return _kr_buildMessageCard(message, context);
                    },
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 构建消息卡片
  Widget _kr_buildMessageCard(KRMessage message, BuildContext context) {
    return Container(
      margin: EdgeInsets.only(bottom: 12.h),
      padding: EdgeInsets.all(16.r),
      decoration: BoxDecoration(
        color: Theme.of(context).cardColor,
        borderRadius: BorderRadius.circular(12.r),
      ),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 图标
          Container(
            width: 40.r,
            height: 40.r,
            decoration: BoxDecoration(
              color:
              //  message.type == KRMessageType.system
                   Colors.blue,
                  // : Colors.orange,
              shape: BoxShape.circle,
            ),
            child: Icon(
              Icons.notifications_outlined,
                  // : Icons.card_giftcard_outlined,
              color: Colors.white,
              size: 24.r,
            ),
          ),
          SizedBox(width: 12.w),
          // 内容
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      // message.type == KRMessageType.system
                           message.title,
                          // : AppTranslations.kr_message.promotion,
                      style: KrAppTextStyle(
                        fontSize: 14,
                        fontWeight: FontWeight.w500,
                        color: Theme.of(context).textTheme.bodyMedium?.color,
                      ),
                    ),
                    Text(
                      message.kr_formattedCreatedAt,
                      style: KrAppTextStyle(
                        fontSize: 12,
                        fontWeight: FontWeight.w400,
                        color: Theme.of(context).textTheme.bodySmall?.color,
                      ),
                    ),
                  ],
                ),
                SizedBox(height: 4.h),
                _kr_buildMessageContent(message.content, context),
              ],
            ),
          ),
        ],
      ),
    );
  }

  // 构建消息内容
  Widget _kr_buildMessageContent(String content, BuildContext context) {
    // 判断内容类型
    final bool kr_isHtml = content.contains('<') && content.contains('>');
    final bool kr_isMarkdown = content.contains('**') || 
                             content.contains('*') || 
                             content.contains('#') || 
                             content.contains('- ') ||
                             content.contains('[');
    
    final textStyle = KrAppTextStyle(
      fontSize: 12,
      fontWeight: FontWeight.w400,
      color: Theme.of(context).textTheme.bodySmall?.color,
    );

    if (kr_isHtml) {
      // 使用 flutter_html 处理 HTML 内容
      return Html(
        data: content,
        style: {
          'body': Style(
            margin: Margins.all(0),
            padding: HtmlPaddings.all(0),
            fontSize: FontSize(12.sp),
            color: Theme.of(context).textTheme.bodySmall?.color,
          ),
          'p': Style(
            margin: Margins.only(bottom: 8.h),
          ),
          'b': Style(
            fontWeight: FontWeight.bold,
          ),
          'i': Style(
            fontStyle: FontStyle.italic,
          ),
          'a': Style(
            color: Colors.blue,
            textDecoration: TextDecoration.underline,
          ),
        },
        shrinkWrap: true,
      );
    } else if (kr_isMarkdown) {
      // 使用 flutter_markdown 处理 Markdown 内容
      return MarkdownBody(
        data: content,
        styleSheet: MarkdownStyleSheet(
          p: TextStyle(
            fontSize: 12.sp,
            color: Theme.of(context).textTheme.bodySmall?.color,
          ),
          strong: TextStyle(
            fontSize: 12.sp,
            fontWeight: FontWeight.bold,
            color: Theme.of(context).textTheme.bodySmall?.color,
          ),
          em: TextStyle(
            fontSize: 12.sp,
            fontStyle: FontStyle.italic,
            color: Theme.of(context).textTheme.bodySmall?.color,
          ),
          a: TextStyle(
            fontSize: 12.sp,
            color: Colors.blue,
            decoration: TextDecoration.underline,
          ),
        ),
      );
    } else {
      // 普通文本
      return Text(
        content,
        maxLines: 3,
        overflow: TextOverflow.ellipsis,
        style: textStyle,
      );
    }
  }
}
