import 'package:auto_size_text/auto_size_text.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:keyboard/base/base_view.dart';
import 'package:keyboard/data/bean/character_info.dart';
import 'package:keyboard/resource/string.gen.dart';

import '../../resource/assets.gen.dart';
import '../../utils/styles.dart';
import '../../widget/avatar/avatar_image_widget.dart';
import '../../widget/heart_fill_view.dart';
import '../../widget/pargress_bar.dart';
import 'keyboard_controller.dart';

class KeyBoardView extends BaseView<KeyBoardController> {
  const KeyBoardView({super.key});

  @override
  Widget buildBody(BuildContext context) {
    return Stack(
      children: [
        IgnorePointer(
          child: Assets.images.bgKeyboard.image(width: 360.w, fit: BoxFit.fill),
        ),
        SafeArea(
          child: Stack(
            children: [
              Column(
                children: [
                  Expanded(
                    child: SingleChildScrollView(
                      child: Column(
                        children: [
                          _buildTitle(),
                          _buildAvatarCard(),
                          Container(height: 10.h, color: Colors.transparent),
                          _buildLoveIndexCard(),
                          SizedBox(height: 10.h),
                          Container(
                            padding: EdgeInsets.only(top: 16.h),
                            decoration: BoxDecoration(
                              color: Colors.white,
                              borderRadius: BorderRadius.only(
                                topLeft: Radius.circular(16.r),
                                topRight: Radius.circular(16.r),
                              ),
                            ),
                            child: Column(
                              children: [
                                _buildHitCard(),
                                SizedBox(height: 10.h),
                                _buildKeyboardSettings(),
                                SizedBox(height: 90.h),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                ],
              ),

              Positioned(
                bottom: 0,
                left: 16.w,
                right: 16.w,
                child: _buildBanner(),
              ),
            ],
          ),
        ),
      ],
    );
  }

  // 顶部标题栏
  Widget _buildTitle() {
    return Container(
      padding: EdgeInsets.only(
        top: 12.h,
        left: 16.w,
        right: 16.w,
        bottom: 25.h,
      ),
      color: Colors.transparent,
      child: Row(
        children: [
          Assets.images.iconKeyboardTitle.image(
            width: 110.w,
            height: 26.h,
            fit: BoxFit.cover,
          ),
          const Spacer(),
          GestureDetector(
            onTap: controller.clickVip,
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 6.w, vertical: 6.w),
              decoration: ShapeDecoration(
                color: Colors.white.withAlpha(204),
                shape: RoundedRectangleBorder(
                  side: BorderSide(width: 1, color: Colors.white),
                  borderRadius: BorderRadius.circular(13.r),
                ),
              ),
              child: Row(
                children: [
                  Assets.images.iconKeyboardVipLogo.image(
                    width: 12.w,
                    height: 12.w,
                  ),
                  const SizedBox(width: 2),
                  Text(
                    StringName.keyboardMemberOpen,
                    style: TextStyle(
                      color: Color(0xFFA85600),
                      fontSize: 12,
                      fontWeight: FontWeight.w400,
                    ),
                  ),
                  Icon(
                    Icons.chevron_right,
                    color: Color(0xFFA85600),
                    size: 11.r,
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 用户头像卡片
  Widget _buildAvatarCard() {
    return Obx(() {
      return Container(
        padding: EdgeInsets.symmetric(horizontal: 22.w),
        decoration: BoxDecoration(color: Colors.transparent),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                _buildAvatar(true),

                _buildLovePercentage(),

                _buildAvatar(false),
              ],
            ),
          ],
        ),
      );
    });
  }

  // 爱情指数卡片
  Widget _buildLoveIndexCard() {
    return Stack(
      clipBehavior: Clip.none,
      children: [
        Positioned(
          left: 0,
          right: 0,
          top: -12.h,
          child: Assets.images.iconKeyboardTriangle.image(
            color: Colors.white,
            width: 20.w,
            height: 16.h,
          ),
        ),
        Container(
          margin: EdgeInsets.symmetric(horizontal: 22.w),
          padding: EdgeInsets.symmetric(vertical: 5.h, horizontal: 5.w),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(12.r),
          ),
          child: Row(
            children: [
              Assets.images.iconKeyboardLoveIndex.image(
                width: 72.w,
                height: 23.h,
              ),
              SizedBox(width: 10.w),
              Expanded(
                child: Obx(() {
                  return Container(
                    padding: EdgeInsets.symmetric(
                      horizontal: 10.w,
                      vertical: 8.h,
                    ),
                    decoration: BoxDecoration(
                      color: Color(0xFFFAFAFC),
                      borderRadius: BorderRadius.circular(12.r),
                    ),
                    child: Row(
                      children: [
                        Expanded(
                          child: Column(
                            children: [
                              ProgressBar(
                                title: StringName.keyboardPassion,
                                value: controller.loveIndex.value?.passion,
                                color: Color(0XFFFF637D),
                              ),
                              SizedBox(height: 6.h),
                              ProgressBar(
                                title: StringName.keyboardRapport,
                                value: controller.loveIndex.value?.rapport,
                                color: Color(0XFFCE63FF),
                              ),
                            ],
                          ),
                        ),
                        SizedBox(width: 21.w),
                        Expanded(
                          child: Column(
                            children: [
                              Obx(() {
                                return ProgressBar(
                                  title: StringName.keyboardFetter,
                                  value: controller.loveIndex.value?.fetter,
                                  color: Color(0xFFFFC954),
                                );
                              }),
                              SizedBox(height: 6.h),
                              ProgressBar(
                                title: StringName.keyboardPromise,
                                value: controller.loveIndex.value?.promise,
                                color: Color(0XFF6382FF),
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  );
                }),
              ),
            ],
          ),
        ),
      ],
    );
  }

  // 用户头像
  Widget _buildAvatar(bool isUser) {
    return GestureDetector(
      onTap: () {
        controller.clickAvatar(isUser);
      },
      child: Column(
        children: [
          Stack(
            alignment: Alignment.bottomCenter,
            children: [
              Column(
                children: [
                  Container(
                    width: 98.r,
                    height: 98.r,
                    decoration: ShapeDecoration(
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(50.r),
                      ),
                    ),
                    child: CircleAvatarWidget(
                      imageUrl:
                          isUser
                              ? controller.homeInfo?.imageUrl
                              : controller.homeInfo?.targetImageUrl,
                      placeholderImage:
                          Assets.images.iconKeyboardDefaultAvatar.provider(),
                      borderColor: Colors.white,
                      borderWidth: 2.r,
                      placeholder: (_, __) {
                        return const SizedBox();
                      },
                    ),
                  ),
                  SizedBox(height: 10.h),
                ],
              ),
              Container(
                padding: EdgeInsets.symmetric(horizontal: 10.w, vertical: 4.w),
                constraints: BoxConstraints(maxWidth: 76.w),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(22.r),
                ),
                child:
                    isUser
                        ? AutoSizeText(
                          controller.homeInfo?.name ??
                              StringName.keyboardNoLogin,
                          style: Styles.getTextStyleBlack204W400(14.sp),
                          maxLines: 1,
                          minFontSize: 10,
                          overflow: TextOverflow.clip,
                        )
                        : AutoSizeText(
                          controller.homeInfo?.targetName ??
                              StringName.keyboardAdd,
                          style:
                              controller.homeInfo?.targetName != null
                                  ? Styles.getTextStyleBlack204W400(14.sp)
                                  : TextStyle(
                                    color: const Color(0xFF8651FF),
                                    fontSize: 14.sp,
                                    fontWeight: FontWeight.w400,
                                  ),
                          maxLines: 1,
                          minFontSize: 10,
                          overflow: TextOverflow.ellipsis,
                        ),
              ),
            ],
          ),
          const SizedBox(height: 4),
          // Text(name, style: const TextStyle(fontSize: 12)),
        ],
      ),
    );
  }

  // 爱情百分比
  Widget _buildLovePercentage() {
    return Container(
      decoration: BoxDecoration(shape: BoxShape.circle),
      child: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Container(
              padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 4.h),
              decoration: ShapeDecoration(
                color: Colors.white.withValues(alpha: 153),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(17.r),
                ),
              ),
              child: Row(
                children: [
                  Assets.images.iconKeyboardLoveLogo.image(
                    width: 18.w,
                    height: 18.w,
                  ),
                  Text(
                    controller.homeInfo?.intimacyName ?? "",
                    textAlign: TextAlign.center,
                    style: Styles.getTextStyleBlack153W400(14.sp),
                  ),
                ],
              ),
            ),
            SizedBox(height: 7.h),
            GestureDetector(
              onTap: () {
                controller.clickLovePercentage();
              },
              child: SizedBox(
                width: 88.w,
                height: 72.w,
                child: Stack(
                  children: [
                    // Assets.images.bgKeyboardLove.image(width: 88.w, height: 72.h),
                    HeartFillAnimation(
                      fillProgress:
                          controller.homeInfo?.intimacy != null
                              ? controller.homeInfo!.intimacy! / 100
                              : 0,
                      width: 88.w,
                    ),
                    Positioned.fill(
                      child: Center(
                        child: Obx(
                          () => Text.rich(
                            TextSpan(
                              children: [
                                TextSpan(
                                  text:
                                      controller.homeInfo?.intimacy != null
                                          ? controller.homeInfo?.intimacy
                                              .toString()
                                          : "?",
                                  style: TextStyle(
                                    color: Colors.white,
                                    fontSize: 33.sp,
                                    fontWeight: FontWeight.w700,
                                    shadows: [
                                      Shadow(
                                        offset: Offset(0, 1),
                                        blurRadius: 4.r,
                                        color: const Color(
                                          0xFFFF6BD3,
                                        ).withValues(alpha: 0.63),
                                      ),
                                    ],
                                  ),
                                ),
                                TextSpan(
                                  text: '%',
                                  style: TextStyle(
                                    color: Colors.white,
                                    fontSize: 14.sp,
                                    fontWeight: FontWeight.w700,
                                    shadows: [
                                      Shadow(
                                        offset: Offset(0, 1),
                                        blurRadius: 4.r,
                                        color: const Color(
                                          0xFFFF6BD3,
                                        ).withValues(alpha: 0.63),
                                      ),
                                    ],
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 爆款玩法区域
  Widget _buildHitCard() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Padding(
          padding: EdgeInsets.symmetric(horizontal: 16.r),
          child: Assets.images.iconKeyboardHitPlay.image(
            width: 83.w,
            height: 22.h,
            fit: BoxFit.cover,
          ),
        ),
        const SizedBox(height: 5),
        Padding(
          padding: EdgeInsets.only(left: 12.w, right: 12.w),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Obx(() {
                ImageProvider imageProvider;
                // 已选择为默认键盘，显示启用键盘
                if (!controller.isDefaultKeyboard.value) {
                  imageProvider = Assets.images.bgKeyboardStartUsing.provider();
                } else {
                  // 未选择为默认键盘，显示体验键盘
                  imageProvider = Assets.images.bgKeyboardTryExperience.provider();
                }
                return GestureDetector(
                  onTap: controller.clickEasyReply,
                  child: SizedBox(
                    width: 170.w,
                    height: 155.85.w,
                    child: Image(
                      image: imageProvider,
                      fit: BoxFit.contain,
                    ),
                  ),
                );
              }),

              Column(
                children: [
                  _buildFeatureCard(
                    bg: Assets.images.bgKeyboardIntimacyAnalyze.image(
                      width: 162.w,
                      height: 77.5.w,
                      fit: BoxFit.contain,
                    ),
                    onTap: controller.clickIntimacyAnalyze,
                  ),
                  _buildFeatureCard(
                    bg: Assets.images.bgKeyboardScreenshotReply.image(
                      width: 162.w,
                      height: 77.5.w,
                      fit: BoxFit.contain,
                    ),
                    onTap: controller.clickScreenshotReply,
                  ),
                ],
              ),
            ],
          ),
        ),
      ],
    );
  }

  // 功能卡片
  Widget _buildFeatureCard({required Widget bg, required VoidCallback onTap}) {
    return GestureDetector(onTap: onTap, child: Container(child: bg));
  }

  // 当前键盘人设信息
  Widget _buildKeyboardSettings() {
    return GestureDetector(
      onTap: controller.clickGoKeyboardManage,
      child: Container(
        margin: EdgeInsets.symmetric(horizontal: 16.w),
        padding: EdgeInsets.only(
          left: 11.w,
          right: 11.w,
          top: 15.h,
          bottom: 15.h,
        ),
        decoration: ShapeDecoration(
          color: Colors.white,
          shape: RoundedRectangleBorder(
            side: BorderSide(width: 2, color: const Color(0xFFF5F4F9)),
            borderRadius: BorderRadius.only(
              topLeft: Radius.circular(16.r),
              topRight: Radius.circular(16.r),
              bottomLeft: Radius.circular(16.r),
              bottomRight: Radius.circular(16.r),
            ),
          ),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Assets.images.iconKeyboardCurrentCharacterTitle.image(
                  width: 90.w,
                  height: 20.h,
                  fit: BoxFit.cover,
                ),
                GestureDetector(
                  // onTap: controller.clickGoKeyboardManage,
                  child: Row(
                    children: [
                      Text(
                        StringName.keyboardGoToManage,
                        style: TextStyle(
                          color: Colors.black.withAlpha(102),
                          fontSize: 12.sp,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                      Assets.images.iconKeyboardCurrentGo.image(
                        width: 7.w,
                        height: 7.w,
                      ),
                    ],
                  ),
                ),
              ],
            ),
            const SizedBox(height: 16),
            Obx(() {
              final list = controller.homeInfo?.characterInfos;
              if (list == null) {
                return const Center(child: CircularProgressIndicator());
              }
              final showList = list.take(9).toList();

              return SizedBox(
                height: 32.h * 3 + 8.h * 2, // 三行高度 + 两个间距
                child: GridView.builder(
                  padding: EdgeInsets.zero,
                  physics: const NeverScrollableScrollPhysics(),
                  // 禁止滑动
                  itemCount: showList.length,
                  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: 3, // 每行3个
                    mainAxisSpacing: 8.h,
                    crossAxisSpacing: 8.w,
                    childAspectRatio: 96.w / 32.h, // 控制宽高比
                  ),
                  itemBuilder: (context, index) {
                    return _buildCharacterItem(showList[index]);
                  },
                ),
              );
            }),
          ],
        ),
      ),
    );
  }

  // 人设标签
  Widget _buildCharacterItem(CharacterInfo character) {
    return Container(
      alignment: Alignment.center,
      decoration: ShapeDecoration(
        color: const Color(0xFFF5F4F9),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(31.r),
        ),
      ),
      child: Text(
        '${character.emoji}${character.name}',
        style: Styles.getTextStyleBlack204W400(12.sp),
        maxLines: 1,
        overflow: TextOverflow.fade,
      ),
    );
  }

  // 活动banner
  Widget _buildBanner() {
    return Obx(() {
      if (!controller.isShowBanner.value) {
        return SizedBox(width: 328.w, height: 84.h);
      }
      return GestureDetector(
        onTap: () {
          controller.clickBanner();
        },
        child: SizedBox(
          width: 328.w,
          height: 84.h,
          child: Stack(
            clipBehavior: Clip.none,
            children: [
              Positioned(
                top: 20.h,
                child: Assets.images.iconKeyboardBanner.image(
                  width: 328.w,
                  height: 64.h,
                ),
              ),
              Positioned(
                right: 53.w,
                bottom: 18.h,
                child: Obx(
                  () => Text(
                    controller.formattedTime,
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 12.sp,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ),
              ),
              Positioned(
                right: 6.w,
                top: 0.h,
                child: GestureDetector(
                  onTap: controller.clickCloseBanner,
                  child: Assets.images.iconKeyboardBannerClose.image(
                    width: 14.w,
                    height: 22.h,
                  ),
                ),
              ),
            ],
          ),
        ),
      );
    });
  }

  @override
  Color backgroundColor() {
    return const Color(0xFFF5F5F5);
  }
}
