
import 'package:flutter/material.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:get/get.dart';
import 'package:mighty_school/common/widget/custom_contaner.dart';
import 'package:mighty_school/common/widget/custom_image.dart';
import 'package:mighty_school/common/widget/no_data_found.dart';
import 'package:mighty_school/feature/cms_management/cms_settings/controller/frontend_settings_controller.dart';
import 'package:mighty_school/feature/landing_page/domain/models/gallery_model.dart';
import 'package:mighty_school/feature/landing_page/logic/landing_page_controller.dart';
import 'package:mighty_school/helper/responsive_helper.dart';
import 'package:mighty_school/util/app_constants.dart';
import 'package:mighty_school/util/dimensions.dart';
import 'package:mighty_school/util/styles.dart';

class GalleryWidget extends StatelessWidget {
  const GalleryWidget({super.key});

  @override
  Widget build(BuildContext context) {
    final isDesktop = ResponsiveHelper.isDesktop(context);
    return GetBuilder<LandingPageController>(
        initState: (val) {
          if(Get.find<LandingPageController>().galleryModel == null) {
            Get.find<LandingPageController>().getGalleryData();
          }
        },

        builder: (galleryController) {
          GalleryModel ? galleryModel = galleryController.galleryModel;

          return (galleryModel != null && galleryModel.data != null )? (galleryModel.data?.academicImages != null && galleryModel.data!.academicImages!.isNotEmpty)?
          Center(
            child: SizedBox(width: Dimensions.webMaxWidth,
              child: Padding(padding: const EdgeInsets.all(Dimensions.paddingSizeDefault),
                child: Column(mainAxisSize: MainAxisSize.min,
                  children: [
                    Text("gallery".tr, style: textMedium.copyWith(color: Theme.of(context).primaryColor, fontSize: isDesktop?20: Dimensions.paddingSizeDefault)),
                    Text(" ${"explore_life".tr} ${Get.find<FrontendSettingsController>().settingModel?.data?.siteTitle??''}",
                        style: textBold.copyWith(fontSize: isDesktop? 50 : Dimensions.fontSizeExtraLarge, color: Theme.of(context).colorScheme.primary),
                        textAlign: TextAlign.center),
                    Container(height: 3, width: 60, decoration: BoxDecoration(color: Theme.of(context).primaryColor, borderRadius: BorderRadius.circular(50)),),
                    const SizedBox(height: 40),

                    MasonryGridView.count(
                      itemCount: galleryModel.data?.academicImages?.length?? 0,
                      shrinkWrap: true,
                      physics: const NeverScrollableScrollPhysics(),
                      crossAxisCount: MediaQuery.sizeOf(context).width >= 1000 ? 4 : 2,
                      mainAxisSpacing: 10,
                      crossAxisSpacing: 10,
                      itemBuilder: (context, index) {
                        final imageUrl = "${AppConstants.baseUrl}/storage/academic_images/${galleryModel.data?.academicImages?[index].image}";
                        return _GalleryImageTile(imageUrl: imageUrl, index: index,
                          images: galleryModel.data!.academicImages!.map((e) => "${AppConstants.baseUrl}/storage/academic_images/${e.image}").toList(),
                        );
                      },
                    ),
                  ],
                ),
              ),
            ),
          ): const Center(child: NoDataFound()): const Center(child: CircularProgressIndicator());
        }
    );
  }
}

class _GalleryImageTile extends StatefulWidget {
  final String imageUrl;
  final List<String> images;
  final int index;
  const _GalleryImageTile({required this.imageUrl, required this.images, required this.index});

  @override
  State<_GalleryImageTile> createState() => _GalleryImageTileState();
}

class _GalleryImageTileState extends State<_GalleryImageTile> {
  double? _aspect;

  @override
  void initState() {
    super.initState();
    _resolveImageAspect();
  }

  void _resolveImageAspect() {
    final ImageStream stream = Image.network(widget.imageUrl).image.resolve(const ImageConfiguration());
    ImageStreamListener? listener;
    listener = ImageStreamListener((ImageInfo info, bool syncCall) {
      final w = info.image.width.toDouble();
      final h = info.image.height.toDouble();
      if (mounted) {
        setState(() => _aspect = (h > 0 ? w / h : 1));
      }
      stream.removeListener(listener!);
    }, onError: (Object error, StackTrace? stackTrace) {
      if (mounted) {
        setState(() => _aspect = 1);
      }
      stream.removeListener(listener!);
    });
    stream.addListener(listener);
  }

  void _openDialog() {
    final ctx = Get.context!;
    showGeneralDialog(
      context: ctx,
      barrierDismissible: true,
      barrierLabel: 'Close',
      barrierColor: Colors.black54,
      transitionDuration: const Duration(milliseconds: 250),
      pageBuilder: (context, anim, secondaryAnim) {
        return _GalleryFullScreenViewer(images: widget.images, initialIndex: widget.index);
      },
      transitionBuilder: (context, anim, secondaryAnim, child) {
        final curved = CurvedAnimation(parent: anim, curve: Curves.easeOutCubic);
        return Transform.scale(scale: curved.value, child: Opacity(opacity: curved.value, child: child),
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    final aspect = _aspect ?? 1;
    return CustomContainer(onTap: _openDialog,
      horizontalPadding: 0, verticalPadding: 0,
      color: Theme.of(context).highlightColor,
      showShadow: false,
      border: Border.all(color: Theme.of(context).highlightColor.withValues(alpha: .25), width: .25),
      child: ClipRRect(borderRadius: BorderRadius.circular(10),
        child: Hero(tag: widget.imageUrl,
          child: AspectRatio(aspectRatio: aspect,
            child: CustomImage(width: double.infinity, fit: BoxFit.cover, image: widget.imageUrl),
          ),
        ),
      ),
    );
  }
}

class _GalleryFullScreenViewer extends StatefulWidget {
  final List<String> images;
  final int initialIndex;
  const _GalleryFullScreenViewer({
    required this.images,
    required this.initialIndex,
  });

  @override
  State<_GalleryFullScreenViewer> createState() => _GalleryFullScreenViewerState();
}

class _GalleryFullScreenViewerState extends State<_GalleryFullScreenViewer> {
  late final PageController _controller;
  late int _current;

  @override
  void initState() {
    super.initState();
    _current = widget.initialIndex;
    _controller = PageController(initialPage: widget.initialIndex);
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Material(type: MaterialType.transparency,
      child: SafeArea(
        child: Stack(children: [
          PageView.builder(controller: _controller,
            itemCount: widget.images.length,
            onPageChanged: (i) => setState(() => _current = i),
            itemBuilder: (context, i) {
              final url = widget.images[i];
              return Center(
                child: Hero(tag: url,
                  child: InteractiveViewer(maxScale: 4, minScale: 1,
                      child: CustomContainer(borderRadius: 0, showShadow: false,
                          child: CustomImage(fit: BoxFit.contain, image: url))),
                ),
              );
            },
          ),
          Positioned(top: 8, right: 8,
              child: IconButton(icon: Icon(Icons.clear, color: Theme.of(context).hintColor, size: 30),
                  onPressed: () => Navigator.of(context).pop())),
          Positioned(bottom: 16, left: 0, right: 0,
            child: Center(child: Container(
                padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                decoration: BoxDecoration(color: Colors.black54, borderRadius: BorderRadius.circular(20)),
                child: DefaultTextStyle(style: const TextStyle(color: Colors.white, fontSize: 14),
                    child: Text('${_current + 1} / ${widget.images.length}'))),
            ),
          ),
        ],
        ),
      ),
    );
  }
}
