import 'dart:ui';

import 'package:background_downloader/background_downloader.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:just_audio/just_audio.dart';
import 'package:tone_snap/components/base_scrollbar.dart';
import 'package:tone_snap/components/full_width_track_shape.dart';
import 'package:tone_snap/components/my_marquee_text.dart';
import 'package:tone_snap/components/network_image_widget.dart';
import 'package:tone_snap/data/enum/play_mode.dart';
import 'package:tone_snap/data/storage/love_songs_box.dart';
import 'package:tone_snap/data/storage/offline_box.dart';
import 'package:tone_snap/generated/assets.dart';
import 'package:tone_snap/modules/sideb/controllers/music_player_controller.dart';
import 'package:tone_snap/modules/sideb/play_page/play_page_controller.dart';
import 'package:tone_snap/modules/sideb/widgets/music_appbar.dart';
import 'package:tone_snap/res/themes/app_colors.dart';
import 'package:tone_snap/utils/date_util.dart';
import 'package:tone_snap/utils/obj_util.dart';

class PlayPageView extends StatelessWidget {
  PlayPageView({super.key});

  final controller = Get.find<PlayPageController>();
  final musicPlayerController = MusicPlayerController.to;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: [
          _buildPageBgImg(),
          Column(
            children: [
              _buildHeader(),
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 20).w,
                child: Column(
                  children: [
                    SizedBox(height: 12.h),
                    _buildCover(),
                    SizedBox(height: 36.h),
                    _buildMusicName(),
                    SizedBox(height: 12.h),
                    _processBar(context),
                    SizedBox(height: 24.h),
                  ],
                ),
              ),
              const Spacer(),
              _buildPlayControlButtons(context),
              SizedBox(height: 67.h),
            ],
          ),
        ],
      ),
    );
  }

  /// 页面背景图
  Widget _buildPageBgImg() {
    return ImageFiltered(
      imageFilter: ImageFilter.blur(sigmaX: 50.0, sigmaY: 50.0),
      child: Stack(
        children: [
          Obx(() {
            return NetworkImageWidget(
              url: musicPlayerController.getMusicModel()?.value.coverUrl,
              width: 1.sw,
              height: 1.sh,
              noPlaceholder: true,
            );
          }),
          Container(
            width: 1.sw,
            height: 1.sh,
            color: const Color(0xB3000000),
          ),
        ],
      ),
    );
  }

  /// 头部
  Widget _buildHeader() {
    return const MusicAppbar(
      isDownBack: true,
      isBackBorder: true,
      // actionOnTap: (){},
      // titleWidget: Row(
      //   mainAxisAlignment: MainAxisAlignment.center,
      //   children: [
      //     _buildMenuText('SONG', true),
      //     Container(
      //       width: 1.w,
      //       height: 14.h,
      //       color: const Color(0x73FFFFFF),
      //     ),
      //     _buildMenuText('LYRICS', false),
      //   ],
      // ),
      // action: Image.asset(
      //   Assets.sideBCrossCircle,
      //   width: 24.w,
      //   height: 24.w,
      // ),
    );
  }

  /// 播放页/歌词页
  // Widget _buildMenuText(String label, bool selected) {
  //   return InkWell(
  //     onTap: (){},
  //     child: Padding(
  //       padding: EdgeInsets.symmetric(horizontal: 15.5.w, vertical: 8.h),
  //       child: Text(
  //         label,
  //         style: TextStyle(
  //           color: Color(selected ? 0xD9FFFFFF : 0x73FFFFFF),
  //           fontSize: 15.sp,
  //         ),
  //       ),
  //     ),
  //   );
  // }

  /// 封面
  Widget _buildCover() {
    return Obx(() {
      return NetworkImageWidget(
        url: musicPlayerController.getMusicModel()?.value.coverUrl,
        width: 1.sw,
        height: 330.h,
        radius: 16.r,
        placeholderWidth: 100.w,
        placeholderHeight: 100.w,
      );
    });
  }

  /// 歌名/作者信息、收藏、下载
  Widget _buildMusicName() {
    return Row(
      children: [
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Obx(() {
                return MyMarqueeText(
                  text: ObjUtil.getStr(musicPlayerController.getMusicModel()?.value.title),
                  textStyle: TextStyle(
                    color: const Color(0xD9FFFFFF),
                    fontSize: 22.sp,
                  ),
                );
              }),
              SizedBox(height: 6.h),
              Obx(() {
                return MyMarqueeText(
                  text: ObjUtil.getStr(musicPlayerController.getMusicModel()?.value.subtitle),
                  textStyle: TextStyle(
                    color: const Color(0x99EEEEEE),
                    fontSize: 12.sp,
                  ),
                );
              }),
            ],
          ),
        ),
        SizedBox(width: 10.w),
        Obx(() {
          return Visibility(
            visible: musicPlayerController.getMusicModel() != null,
            child: ClipOval(
              child: Material(
                color: Colors.transparent,
                child: InkWell(
                  onTap: controller.onTapLove,
                  child: Padding(
                    padding: const EdgeInsets.all(6).w,
                    child: Obx(() {
                      return Image.asset(
                        LoveSongsBox().checkLove(musicPlayerController.getMusicModel()?.value.videoId) ? Assets.sideBLoveSolid : Assets.sideBLove,
                        width: 24.w,
                        height: 24.w,
                      );
                    }),
                  ),
                ),
              ),
            ),
          );
        }),
        SizedBox(width: 8.w),
        Obx(() {
          return Visibility(
            visible: musicPlayerController.getMusicModel() != null,
            child: ClipOval(
              child: Material(
                color: Colors.transparent,
                child: InkWell(
                  onTap: controller.onTapDownload,
                  child: Padding(
                    padding: const EdgeInsets.all(6).w,
                    child: SizedBox(
                      width: 24.w,
                      height: 24.w,
                      child: Obx(() {
                        if (OfflineBox().checkDownloaded(musicPlayerController.getMusicModel()?.value.videoId)
                        || musicPlayerController.getMusicModel()?.value.taskStatus == TaskStatus.complete) {
                          return Image.asset(Assets.sideBDownloaded);
                        } else {
                          if (musicPlayerController.getMusicModel()?.value.taskStatus == TaskStatus.enqueued) {
                            return CircularProgressIndicator(
                              color: seedColor,
                              strokeWidth: 2.w,
                            );
                          } else if (musicPlayerController.getMusicModel()?.value.taskStatus == TaskStatus.running) {
                            return CircularProgressIndicator(
                              value: musicPlayerController.getMusicModel()?.value.progress,
                              backgroundColor: seedColor.withOpacity(0.2),
                              valueColor:
                              const AlwaysStoppedAnimation<Color>(seedColor),
                              strokeWidth: 2.w,
                            );
                          } else {
                            return Image.asset(Assets.sideBNotDownload1);
                          }
                        }
                      }),
                    ),
                  ),
                ),
              ),
            ),
          );
        }),
      ],
    );
  }

  /// 进度条
  Widget _processBar(BuildContext context) {
    return Column(
      children: [
        SliderTheme(
          data: SliderTheme.of(context).copyWith(
            activeTrackColor: seedColor,
            inactiveTrackColor: const Color(0x4DFFFFFF),
            secondaryActiveTrackColor: seedColor.withOpacity(0.3),
            trackHeight: 4.h,
            thumbColor: Colors.white,
            thumbShape: RoundSliderThumbShape(
              disabledThumbRadius: 8.w,
              enabledThumbRadius: 8.w,
            ),
            trackShape: FullWidthTrackShape(),
            overlayShape: RoundSliderOverlayShape(overlayRadius: 10.w), // 扩大覆盖层半径
          ),
          child: Obx(() {
            return Slider(
              value: musicPlayerController.positionDuration.value.inSeconds.toDouble(),
              secondaryTrackValue: musicPlayerController.bufferedDuration.value.inSeconds.toDouble(),
              min: 0,
              max: musicPlayerController.totalDuration.value.inSeconds.toDouble(),
              onChanged: (value) => musicPlayerController.seekToPosition(value),
              onChangeStart: (value) => musicPlayerController.seekStartEnd(0),
              onChangeEnd: (value) => musicPlayerController.seekStartEnd(1),
            );
          }),
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Flexible(
              child: Obx(() {
                return Text(
                  DateUtil.playDuration(musicPlayerController.positionDuration.value),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    color: const Color(0xD9FFFFFF),
                    fontSize: 12.sp,
                    fontWeight: FontWeight.w500,
                  ),
                );
              }),
            ),
            Flexible(
              child: Obx(() {
                return Text(
                  DateUtil.playDuration(musicPlayerController.totalDuration.value),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    color: const Color(0x99FFFFFF),
                    fontSize: 12.sp,
                    fontWeight: FontWeight.w500,
                  ),
                );
              }),
            ),
          ],
        ),
      ],
    );
  }

  /// 播放控制按钮
  Widget _buildPlayControlButtons(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 10).w,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          ClipOval(
            child: Material(
              color: Colors.transparent,
              child: InkWell(
                onTap: musicPlayerController.switchPlayMode,
                child: Obx(() {
                  var playModeAssets = Assets.sideBListLoop;
                  if (musicPlayerController.playMode.value == PlayMode.listLoop) {
                    playModeAssets = Assets.sideBListLoop;
                  } else if (musicPlayerController.playMode.value == PlayMode.random) {
                    playModeAssets = Assets.sideBShufflePlayback;
                  } else if (musicPlayerController.playMode.value == PlayMode.singleCycle) {
                    playModeAssets = Assets.sideBSingleCycle;
                  }
                  return Padding(
                    padding: const EdgeInsets.all(10).w,
                    child: Image.asset(
                      playModeAssets,
                      width: 24.w,
                      height: 24.w,
                    ),
                  );
                }),
              ),
            ),
          ),
          ClipOval(
            child: Material(
              color: Colors.transparent,
              child: InkWell(
                onTap: musicPlayerController.previousTrack,
                child: Padding(
                  padding: const EdgeInsets.all(10).w,
                  child: Image.asset(
                    Assets.sideBPreviousTrack,
                    width: 20.w,
                    height: 20.w,
                    color: Colors.white,
                  ),
                ),
              ),
            ),
          ),
          ClipOval(
            child: Material(
              color: Colors.white,
              child: Obx(() {
                return InkWell(
                  onTap: musicPlayerController.processingState.value == ProcessingState.ready
                      || musicPlayerController.processingState.value == ProcessingState.completed
                      ? musicPlayerController.playPause : null,
                  child: SizedBox(
                    width: 66.w,
                    height: 66.w,
                    child: FittedBox(
                      fit: BoxFit.none,
                      child: Visibility(
                        visible: musicPlayerController.processingState.value == ProcessingState.buffering
                            || musicPlayerController.processingState.value == ProcessingState.ready
                            || musicPlayerController.processingState.value == ProcessingState.completed,
                        replacement: Center(
                          child: SizedBox(
                            width: 20.w,
                            height: 20.w,
                            child: const CircularProgressIndicator(
                              color: seedColor,
                              strokeWidth: 3,
                            ),
                          ),
                        ),
                        child: Image.asset(
                          musicPlayerController.isPlaying.value ? Assets.sideBPausePlay : Assets.sideBStartPlay,
                          width: 26.w,
                          height: 26.w,
                        ),
                      ),
                    ),
                  ),
                );
              }),
            ),
          ),
          ClipOval(
            child: Material(
              color: Colors.transparent,
              child: InkWell(
                onTap: musicPlayerController.nextTrack,
                child: Padding(
                  padding: const EdgeInsets.all(10).w,
                  child: Image.asset(
                    Assets.sideBNextTrack,
                    width: 20.w,
                    height: 20.w,
                    color: Colors.white,
                  ),
                ),
              ),
            ),
          ),
          ClipOval(
            child: Material(
              color: Colors.transparent,
              child: InkWell(
                onTap: () => _openPlayList(context),
                child: Padding(
                  padding: const EdgeInsets.all(10).w,
                  child: Image.asset(
                    Assets.sideBPlayList,
                    width: 24.w,
                    height: 24.w,
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  void _openPlayList(BuildContext context) {
    Get.bottomSheet(
      isScrollControlled: true,
      Container(
        width: 1.sw,
        height: 0.6.sh,
        padding: EdgeInsets.only(bottom: MediaQuery.of(context).padding.bottom),
        decoration: BoxDecoration(
          color: const Color(0xFF1A1A1A),
          borderRadius: BorderRadius.only(topLeft: Radius.circular(18.r), topRight: Radius.circular(18.r)),
        ),
        child: Column(
          children: [
            SizedBox(
              width: double.infinity,
              height: 30.h,
              child: FittedBox(
                fit: BoxFit.none,
                child: Image.asset(
                  Assets.sideBBottomSheetIndicator,
                  width: 29.w,
                  height: 4.w,
                ),
              ),
            ),
            Expanded(
              child: BaseScrollbar(
                child: Obx(() {
                  return ListView.builder(
                    itemCount: musicPlayerController.playlist.length,
                    itemBuilder: (context, index) {
                      return _buildPlayListItem(index);
                    },
                  );
                }),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildPlayListItem(int index) {
    final musicModel = musicPlayerController.playlist[index].value;
    return Material(
      color: Colors.transparent,
      child: InkWell(
        onTap: () => controller.switchMusic(musicModel),
        child: Padding(
          padding: const EdgeInsets.symmetric(vertical: 8).h,
          child: Row(
            children: [
              SizedBox(width: 18.w),
              NetworkImageWidget(
                url: musicModel.coverUrl,
                width: 60.w,
                height: 60.w,
                radius: 10.r,
              ),
              SizedBox(width: 12.w),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Obx(() {
                      return Visibility(
                        visible: musicPlayerController.getMusicModel()?.value.videoId == musicModel.videoId,
                        replacement: Text(
                          ObjUtil.getStr(musicModel.title),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                            color: musicPlayerController.getMusicModel()?.value.videoId == musicModel.videoId
                                ? seedColor
                                : const Color(0xD9FFFFFF),
                            fontSize: 14.sp,
                          ),
                        ),
                        child: MyMarqueeText(
                          text: ObjUtil.getStr(musicModel.title),
                          textStyle: TextStyle(
                            color: musicPlayerController.getMusicModel()?.value.videoId == musicModel.videoId
                                ? seedColor
                                : const Color(0xD9FFFFFF),
                            fontSize: 14.sp,
                          ),
                        ),
                      );
                    }),
                    SizedBox(height: 8.h),
                    Obx(() {
                      return Visibility(
                        visible: musicPlayerController.getMusicModel()?.value.videoId == musicModel.videoId,
                        replacement: Text(
                          ObjUtil.getStr(musicModel.subtitle),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                            color: musicPlayerController.getMusicModel()?.value.videoId == musicModel.videoId
                                ? seedColor
                                : const Color(0x99FFFFFF),
                            fontSize: 12.sp,
                          ),
                        ),
                        child: MyMarqueeText(
                          text: ObjUtil.getStr(musicModel.subtitle),
                          textStyle: TextStyle(
                            color: musicPlayerController.getMusicModel()?.value.videoId == musicModel.videoId
                                ? seedColor
                                : const Color(0x99FFFFFF),
                            fontSize: 12.sp,
                          ),
                        ),
                      );
                    }),
                  ],
                ),
              ),
              Obx(() {
                return Visibility(
                  visible: musicPlayerController.getMusicModel()?.value.videoId != musicModel.videoId,
                  child: ClipOval(
                    child: Material(
                      color: Colors.transparent,
                      child: InkWell(
                        onTap: () => controller.deleteMusic(index, musicModel),
                        child: Padding(
                          padding: const EdgeInsets.all(6).w,
                          child: Image.asset(
                            Assets.sideBPlayListDelete,
                            width: 24.w,
                            height: 24.w,
                          ),
                        ),
                      ),
                    ),
                  ),
                );
              }),
              Obx(() {
                return SizedBox(width: musicPlayerController.getMusicModel()?.value.videoId != musicModel.videoId ? 12.w : 16.w);
              }),
            ],
          ),
        ),
      ),
    );
  }
}
