/// Widget: Image Gallery Section
///
/// Product image gallery with main image, 360° view button, indicators, and thumbnails.
library;

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:shimmer/shimmer.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:worker/core/constants/ui_constants.dart';
import 'package:worker/features/products/domain/entities/product.dart';

/// Image Gallery Section
///
/// Displays:
/// - Main product image with 1:1 aspect ratio
/// - 360° view button overlay (if available)
/// - Image indicators (dots)
/// - Thumbnail gallery row (horizontal scroll)
class ImageGallerySection extends StatefulWidget {
  const ImageGallerySection({super.key, required this.product});
  final Product product;

  @override
  State<ImageGallerySection> createState() => _ImageGallerySectionState();
}

class _ImageGallerySectionState extends State<ImageGallerySection> {
  int _currentImageIndex = 0;
  final PageController _pageController = PageController();

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

  void _changeImage(int index) {
    setState(() {
      _currentImageIndex = index;
    });
    _pageController.animateToPage(index, duration: AppDuration.medium, curve: Curves.easeInOut);
  }

  void _open360View() async {
    if (widget.product.customLink360 != null) {
      final url = Uri.parse(widget.product.customLink360!);
      if (await canLaunchUrl(url)) {
        await launchUrl(url, mode: LaunchMode.inAppWebView);
      }
    }
  }

  void _openLightbox() {
    Navigator.of(context).push(
      MaterialPageRoute(
        fullscreenDialog: true,
        builder: (context) => _ImageLightbox(
          images: widget.product.images,
          imageCaptions: widget.product.imageCaptions,
          initialIndex: _currentImageIndex,
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final colorScheme = Theme.of(context).colorScheme;
    final images = widget.product.images;

    return Container(
      color: colorScheme.surface,
      child: Column(
        children: [
          // Main Image with PageView
          AspectRatio(
            aspectRatio: 1.0,
            child: Stack(
              children: [
                // PageView for images
                PageView.builder(
                  controller: _pageController,
                  itemCount: images.length,
                  onPageChanged: (index) {
                    setState(() {
                      _currentImageIndex = index;
                    });
                  },
                  itemBuilder: (context, index) {
                    return GestureDetector(
                      onTap: _openLightbox,
                      child: CachedNetworkImage(
                        imageUrl: images[index],
                        fit: BoxFit.cover,
                        placeholder: (context, url) => Shimmer.fromColors(
                          baseColor: colorScheme.surfaceContainerHighest,
                          highlightColor: colorScheme.surface,
                          child: Container(color: colorScheme.surfaceContainerHighest),
                        ),
                        errorWidget: (context, url, error) => Container(
                          color: colorScheme.surfaceContainerHighest,
                          child: Icon(FontAwesomeIcons.image, size: 64, color: colorScheme.onSurfaceVariant),
                        ),
                      ),
                    );
                  },
                ),

                // 360° Button Overlay
                if (widget.product.has360View)
                  Positioned(
                    top: 16,
                    right: 16,
                    child: Material(
                      color: Colors.black.withAlpha(204), // 0.8 opacity
                      borderRadius: BorderRadius.circular(20),
                      child: InkWell(
                        onTap: _open360View,
                        borderRadius: BorderRadius.circular(20),
                        child: Container(
                          padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                          child: Row(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              TweenAnimationBuilder(
                                tween: Tween<double>(begin: 0, end: 1),
                                duration: const Duration(seconds: 2),
                                builder: (context, double value, child) {
                                  return Transform.rotate(
                                    angle: value * 2 * 3.14159,
                                    child: Icon(FontAwesomeIcons.arrowsRotate, size: 10, color: colorScheme.surface),
                                  );
                                },
                                onEnd: () {
                                  // Loop animation
                                  setState(() {});
                                },
                              ),
                              const SizedBox(width: 6),
                              Text(
                                '360°',
                                style: TextStyle(color: colorScheme.surface, fontSize: 12, fontWeight: FontWeight.w600),
                              ),
                            ],
                          ),
                        ),
                      ),
                    ),
                  ),

                // Image Indicators
                if (images.length > 1)
                  Positioned(
                    bottom: 16,
                    left: 0,
                    right: 0,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: List.generate(
                        images.length,
                        (index) => Container(
                          margin: const EdgeInsets.symmetric(horizontal: 4),
                          width: 8,
                          height: 8,
                          decoration: BoxDecoration(
                            shape: BoxShape.circle,
                            color: _currentImageIndex == index
                                ? colorScheme.surface
                                : colorScheme.surface.withAlpha(128),
                          ),
                        ),
                      ),
                    ),
                  ),
              ],
            ),
          ),

          // Thumbnail Gallery
          if (images.length > 1)
            Container(
              padding: const EdgeInsets.all(16),
              child: SizedBox(
                height: 80,
                child: ListView.builder(
                  scrollDirection: Axis.horizontal,
                  itemCount: images.length,
                  itemBuilder: (context, index) {
                    final isActive = _currentImageIndex == index;
                    final imageUrl = images[index];
                    final imageName = widget.product.imageCaptions[imageUrl];

                    return GestureDetector(
                      onTap: () => _changeImage(index),
                      child: Container(
                        margin: const EdgeInsets.only(right: 12),
                        child: Column(
                          mainAxisSize: .min,
                          mainAxisAlignment: .end,
                          children: [
                            // Image name above thumbnail (only show for active/selected)
                            if (isActive && imageName != null && imageName.isNotEmpty)
                              Padding(
                                padding: const EdgeInsets.only(bottom: 4),
                                child: Text(
                                  imageName,
                                  style: TextStyle(
                                    fontSize: 11,
                                    fontWeight: FontWeight.w600,
                                    color: colorScheme.primary,
                                  ),
                                  maxLines: 1,
                                  overflow: TextOverflow.ellipsis,
                                ),
                              ),

                            // Thumbnail image
                            Container(
                              width: 60,
                              height: 60,
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(8),
                                border: Border.all(
                                  color: isActive ? colorScheme.primary : Colors.transparent,
                                  width: 2,
                                ),
                              ),
                              child: ClipRRect(
                                borderRadius: BorderRadius.circular(6),
                                child: CachedNetworkImage(
                                  imageUrl: imageUrl,
                                  fit: BoxFit.cover,
                                  placeholder: (context, url) => Container(color: colorScheme.surfaceContainerHighest),
                                  errorWidget: (context, url, error) => Container(
                                    color: colorScheme.surfaceContainerHighest,
                                    child: Icon(FontAwesomeIcons.image, size: 20, color: colorScheme.onSurfaceVariant),
                                  ),
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                    );
                  },
                ),
              ),
            ),
        ],
      ),
    );
  }
}

/// Image Lightbox for full-screen image viewing
class _ImageLightbox extends StatefulWidget {
  const _ImageLightbox({required this.images, required this.imageCaptions, required this.initialIndex});
  final List<String> images;
  final Map<String, String> imageCaptions;
  final int initialIndex;

  @override
  State<_ImageLightbox> createState() => _ImageLightboxState();
}

class _ImageLightboxState extends State<_ImageLightbox> {
  late int _currentIndex;
  late PageController _pageController;

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

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

  void _nextImage() {
    if (_currentIndex < widget.images.length - 1) {
      _pageController.nextPage(duration: AppDuration.medium, curve: Curves.easeInOut);
    }
  }

  void _previousImage() {
    if (_currentIndex > 0) {
      _pageController.previousPage(duration: AppDuration.medium, curve: Curves.easeInOut);
    }
  }

  @override
  Widget build(BuildContext context) {
    final colorScheme = Theme.of(context).colorScheme;

    return Scaffold(
      backgroundColor: Colors.black,
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        foregroundColor: colorScheme.surface,
        elevation: 0,
        leading: IconButton(
          icon: const FaIcon(FontAwesomeIcons.xmark, size: 28),
          onPressed: () => Navigator.of(context).pop(),
        ),
        title: Text(
          '${_currentIndex + 1} / ${widget.images.length}',
          style: TextStyle(color: colorScheme.surface, fontSize: 16),
        ),
      ),
      body: Stack(
        children: [
          // Image PageView
          PageView.builder(
            controller: _pageController,
            itemCount: widget.images.length,
            onPageChanged: (index) {
              setState(() {
                _currentIndex = index;
              });
            },
            itemBuilder: (context, index) {
              return Center(
                child: InteractiveViewer(
                  minScale: 0.5,
                  maxScale: 4.0,
                  child: CachedNetworkImage(
                    imageUrl: widget.images[index],
                    fit: BoxFit.contain,
                    errorWidget: (context, url, error) =>
                        Icon(FontAwesomeIcons.circleExclamation, color: colorScheme.surface, size: 64),
                  ),
                ),
              );
            },
          ),

          // Navigation Arrows
          if (widget.images.length > 1) ...[
            // Previous button
            if (_currentIndex > 0)
              Positioned(
                left: 16,
                top: 0,
                bottom: 0,
                child: Center(
                  child: IconButton(
                    icon: Icon(FontAwesomeIcons.chevronLeft, color: colorScheme.surface, size: 32),
                    onPressed: _previousImage,
                    style: IconButton.styleFrom(backgroundColor: Colors.white.withAlpha(51)),
                  ),
                ),
              ),

            // Next button
            if (_currentIndex < widget.images.length - 1)
              Positioned(
                right: 16,
                top: 0,
                bottom: 0,
                child: Center(
                  child: IconButton(
                    icon: Icon(FontAwesomeIcons.chevronRight, color: colorScheme.surface, size: 32),
                    onPressed: _nextImage,
                    style: IconButton.styleFrom(backgroundColor: Colors.white.withAlpha(51)),
                  ),
                ),
              ),
          ],

          // Caption (if available)
          if (widget.imageCaptions.isNotEmpty)
            Positioned(
              bottom: 0,
              left: 0,
              right: 0,
              child: Container(
                padding: const EdgeInsets.all(16),
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    begin: Alignment.bottomCenter,
                    end: Alignment.topCenter,
                    colors: [Colors.black.withAlpha(128), Colors.transparent],
                  ),
                ),
                child: Text(
                  widget.imageCaptions[widget.images[_currentIndex]] ?? '',
                  style: TextStyle(color: colorScheme.surface, fontSize: 16),
                  textAlign: TextAlign.center,
                ),
              ),
            ),
        ],
      ),
    );
  }
}
