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:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:flutter_swiper_view/flutter_swiper_view.dart';
import 'package:get/get.dart';
import 'package:photo_view/photo_view.dart';
import 'package:wallpaperx/common/components/image_network_widget.dart';
import 'package:wallpaperx/common/components/navigation_bar/search_appbar.dart';
import 'package:wallpaperx/common/components/refresh/base_easyrefresh.dart';
import 'package:wallpaperx/common/components/view_state_widget.dart';
import 'package:wallpaperx/entity/image_model.dart';
import 'package:wallpaperx/generated/assets.dart';
import 'package:wallpaperx/page/discover/discover_controller.dart';
import 'package:wallpaperx/res/themes/app_sizes.dart';
import 'package:wallpaperx/res/values/strings.dart';

class DiscoverView extends GetView<DiscoverController> {
  const DiscoverView({super.key});

  @override
  Widget build(BuildContext context) {
    Get.put(DiscoverController());
    return Scaffold(
      resizeToAvoidBottomInset: false,
      body: PageView(
        scrollDirection: Axis.vertical,
        children: [
          _buildPhotoView(context),
          _buildMasonryGridView(context),
        ],
      ),
    );
  }

  Widget _buildPhotoView(context) {
    return Stack(
      children: [
        GetBuilder<DiscoverController>(
          id: 'discover_background',
          builder: (logic) {
            return Container(
              clipBehavior: Clip.hardEdge,
              width: double.infinity,
              height: double.infinity,
              decoration: const BoxDecoration(
                color: Colors.black87,
              ),
              child: ImageFiltered(
                imageFilter: ImageFilter.blur(
                  sigmaX: 50,
                  sigmaY: 50,
                  tileMode: TileMode.decal,
                ),
                child: controller.banners.isEmpty
                    ? Image.asset(
                        Assets.imagesHomeBackground,
                      )
                    : PhotoView(
                        enableRotation: false,
                        imageProvider: CachedNetworkImageProvider(controller
                            .banners[controller.index.value].imageUrl),
                        initialScale: PhotoViewComputedScale.covered,
                        minScale: PhotoViewComputedScale.contained * 0.5,
                        maxScale: PhotoViewComputedScale.covered * 3,
                        loadingBuilder: (context, event) =>
                            loadingViewV1(color: Colors.white),
                        errorBuilder: (BuildContext context, Object error,
                                StackTrace? stackTrace) =>
                            errorView,
                      ),
              ),
            );
          },
        ),
        Container(
          height: double.infinity,
          width: double.infinity,
          padding: EdgeInsets.only(top: MediaQuery.of(context).padding.top).w,
          child: Column(
            children: [
              SearchAppbar(
                onTapToSearch: controller.onTapToSearch,
                onTapToCategory: controller.homeController.openDrawer,
              ),
              20.verticalSpace,
              Obx(() {
                return Expanded(
                  child: Swiper(
                    loop: true,
                    autoplay: true,
                    scale: .9,
                    viewportFraction: .85,
                    itemCount: controller.banners.length,
                    itemBuilder: (context, index) {
                      return GestureDetector(
                        onTap: () => controller.onTapSwiperItem(index),
                        child: ImageNetworkWidget(
                          url: controller.banners[index].imageUrl,
                          radius: 30.r,
                        ),
                      );
                    },
                    onIndexChanged: controller.onIndexChanged,
                  ),
                );
              }),
              20.verticalSpace,
              Image.asset(
                width: 24.w,
                Assets.imagesDiscoverUp,
              ),
              SizedBox(height: MediaQuery.of(context).padding.bottom + 70.w)
            ],
          ),
        )
      ],
    );
  }

  Widget _buildMasonryGridView(context) {
    return Container(
      height: double.infinity,
      width: double.infinity,
      padding: EdgeInsets.only(top: MediaQuery.of(context).padding.top).w,
      decoration: const BoxDecoration(
        image: DecorationImage(
          image: AssetImage(Assets.imagesDiscoverBackground),
          fit: BoxFit.cover,
        ),
      ),
      child: Column(
        children: [
          SearchAppbar(
            onTapToSearch: controller.onTapToSearch,
            onTapToCategory: controller.homeController.openDrawer,
            title: appName,
            titleStyle: TextStyle(
              color: Colors.white,
              fontSize: 24.sp,
              fontWeight: FontWeight.w700,
            ),
          ),
          Obx(() {
            return Expanded(
              child: BaseEasyRefresh(
                controller: controller.refreshController,
                onLoad: controller.onLoad,
                viewState: controller.viewState.value,
                height: discoverListHeight,
                child: Scrollbar(
                  controller: controller.scrollController,
                  child: MasonryGridView.count(
                    controller: controller.scrollController,
                    itemCount: controller.images.length,
                    crossAxisCount: 2,
                    mainAxisSpacing: 20.w,
                    crossAxisSpacing: 20.w,
                    padding: const EdgeInsets.fromLTRB(16, 0, 16, 0).w,
                    itemBuilder: (context, index) {
                      ImageModel item = controller.images[index];
                      return GestureDetector(
                        onTap: () => controller.onTapGridItem(index),
                        child: ImageNetworkWidget(
                          url: item.imageUrl,
                          aspectRatio: item.width! / item.height!,
                          radius: 10.r,
                        ),
                      );
                    },
                  ),
                ),
              ),
            );
          }),
        ],
      ),
    );
  }
}
