import 'dart:io';
import 'dart:ui';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:hello_wallpaper/common/components/button/base_textbutton.dart';
import 'package:hello_wallpaper/common/components/navigation_bar/base_appbar.dart';
import 'package:hello_wallpaper/common/components/view_state_widget.dart';
import 'package:hello_wallpaper/generated/assets.dart';
import 'package:hello_wallpaper/modules/wallpaper_det/wallpaper_det_controller.dart';
import 'package:photo_view/photo_view.dart';
import 'package:photo_view/photo_view_gallery.dart';

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

  final controller = Get.find<WallpaperDetController>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      extendBodyBehindAppBar: true,
      extendBody: true,
      appBar: BaseAppBar(
        '',
        backgroundColor: Colors.transparent,
        backWidget: _buildBackWidget(),
      ),
      body: Stack(
        fit: StackFit.expand,
        children: [
          _buildPhotoView(),
          _buildBottomOption(),
        ],
      ),
    );
  }

  /// 返回按钮
  Widget _buildBackWidget() {
    return GestureDetector(
      onTap: controller.showAd,
      child: Padding(
        padding: const EdgeInsets.only(left: 10).w,
        child: ClipOval(
          child: Container(
            width: 26.w,
            height: 26.w,
            color: Colors.white,
            child: FittedBox(
              fit: BoxFit.scaleDown,
              child: Image.asset(
                Assets.imagesIcBack,
                width: 13.w,
                height: 13.w,
                color: const Color(0xFF1A1311),
              ),
            ),
          ),
        ),
      ),
    );
  }

  /// 图片PageView
  Widget _buildPhotoView() {
    return PhotoViewGallery.builder(
      itemCount: controller.wallpaperList.length,
      scrollPhysics: const BouncingScrollPhysics(),
      wantKeepAlive: true,
      gaplessPlayback: true,
      builder: (context, index) {
        return PhotoViewGalleryPageOptions.customChild(
          child: RepaintBoundary(
            key: controller.globalKey[index],
            child: Obx(() {
              return ImageFiltered(
                enabled: controller.blurs[index],
                imageFilter: ImageFilter.blur(sigmaX: 5, sigmaY: 5, tileMode: TileMode.clamp,),
                child: PhotoView(
                  enableRotation: true,
                  imageProvider: CachedNetworkImageProvider('${controller.wallpaperList[index].original}'),
                  initialScale: PhotoViewComputedScale.covered,
                  minScale: PhotoViewComputedScale.contained * 0.5,
                  maxScale: PhotoViewComputedScale.covered * 3,
                  loadingBuilder: (context, event) => loadingView(),
                  errorBuilder: (BuildContext context, Object error, StackTrace? stackTrace) => errorView,
                ),
              );
            }),
          ),
        );
      },
      pageController: controller.pageController,
      onPageChanged: (index) => controller.onPageChanged(index),
    );
  }

  /// 底部选项
  Widget _buildBottomOption() {
    return Positioned(
      bottom: 34.h,
      left: 0,
      right: 0,
      child: Column(
        children: [
          if (Platform.isAndroid) ...[
            _buildSetWallpaper(),
            SizedBox(height: 24.h),
          ],
          Container(
            width: 0.88.sw,
            height: 68.h,
            decoration: BoxDecoration(
              color: Colors.white.withOpacity(0.9),
              borderRadius: BorderRadius.circular(12).r,
            ),
            clipBehavior: Clip.hardEdge,
            child: Row(
              children: [
                _buildOptionItem(Assets.imagesIcFiltered, 'Blur', controller.onTapBlur),
                _buildOptionItem(Assets.imagesIcDownload, 'Download', controller.onTapDownload),
                _buildOptionItem(Assets.imagesIcFavorite, 'Favorite', controller.onTapFavorite),
                // _buildOptionItem(Assets.imagesIcPreview, 'Preview', () {}),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildSetWallpaper() {
    return BaseTextButton(
      width: 159.w,
      height: 44.h,
      label: 'Set wallpaper',
      bgColor: Colors.white.withOpacity(0.9),
      onTap: controller.onTapSetWallpaper,
    );
  }

  Widget _buildOptionItem(String iconName, String option, Function() onTap) {
    return Expanded(
      child: Material(
        color: Colors.transparent,
        child: InkWell(
          onTap: onTap,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Image.asset(iconName, width: 26.w, height: 26.w),
              Text(
                option,
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                  color: const Color(0xFF333333),
                  fontSize: 14.sp,
                  fontWeight: FontWeight.w500,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
