// ignore_for_file: unused_field

import 'package:cached_network_image/cached_network_image.dart';
import 'package:english_learning/features/learning/modules/material/widgets/loading/media_loading_widget.dart';
import 'package:flutter/material.dart';

class ImageWidget extends StatefulWidget {
  final String imageFileName;
  final String? baseUrl;
  final double? height;
  final BoxFit fit;

  const ImageWidget({
    super.key,
    required this.imageFileName,
    this.baseUrl,
    this.height = 200,
    this.fit = BoxFit.cover,
  });

  @override
  State<ImageWidget> createState() => _ImageWidgetState();
}

class _ImageWidgetState extends State<ImageWidget>
    with TickerProviderStateMixin {
  late AnimationController _loadingController;
  late AnimationController _fadeController;
  bool _isImageLoaded = false;
  String? _errorMessage;
  final TransformationController _transformationController =
      TransformationController();

  @override
  void initState() {
    super.initState();
    _loadingController = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 2),
    )..repeat();

    _fadeController = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 300),
    );
  }

  @override
  void dispose() {
    _loadingController.dispose();
    _fadeController.dispose();
    _transformationController.dispose();
    super.dispose();
  }

  String _getFullImageUrl() {
    if (widget.imageFileName.isEmpty) {
      throw Exception('Image file name cannot be empty');
    }
    return widget.imageFileName.startsWith('http')
        ? widget.imageFileName
        : '${widget.baseUrl ?? ''}${widget.imageFileName}';
  }

  void _showFullScreenImage(BuildContext context, ImageProvider imageProvider) {
    Navigator.of(context).push(
      MaterialPageRoute(
        builder: (context) => FullScreenImageView(
          imageProvider: imageProvider,
          imageUrl: _getFullImageUrl(),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      height: widget.height,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.1),
            blurRadius: 10,
            offset: const Offset(0, 5),
            spreadRadius: 0,
          ),
        ],
      ),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(12),
        child: Stack(
          fit: StackFit.expand,
          children: [
            Container(color: Colors.grey[200]),
            CachedNetworkImage(
              imageUrl: _getFullImageUrl(),
              fit: widget.fit,
              fadeInDuration: const Duration(milliseconds: 300),
              fadeOutDuration: const Duration(milliseconds: 300),
              imageBuilder: (context, imageProvider) {
                _isImageLoaded = true;
                _fadeController.forward();
                return GestureDetector(
                  onTap: () => _showFullScreenImage(context, imageProvider),
                  child: Image(image: imageProvider, fit: widget.fit),
                );
              },
              placeholder: (context, url) => MediaLoadingWidget(
                width: double.infinity,
                height: widget.height ?? 200,
                borderRadius: BorderRadius.circular(12),
              ),
              errorWidget: (context, url, error) => Container(
                color: Colors.grey[300],
                child: const Center(
                  child: Icon(Icons.error_outline, color: Colors.red),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class FullScreenImageView extends StatefulWidget {
  final ImageProvider imageProvider;
  final String imageUrl;

  const FullScreenImageView({
    super.key,
    required this.imageProvider,
    required this.imageUrl,
  });

  @override
  State<FullScreenImageView> createState() => _FullScreenImageViewState();
}

class _FullScreenImageViewState extends State<FullScreenImageView> {
  late TransformationController _controller;
  late TapDownDetails _doubleTapDetails;

  @override
  void initState() {
    super.initState();
    _controller = TransformationController();
  }

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

  void _handleDoubleTapDown(TapDownDetails details) {
    _doubleTapDetails = details;
  }

  void _handleDoubleTap() {
    if (_controller.value != Matrix4.identity()) {
      _controller.value = Matrix4.identity();
    } else {
      final position = _doubleTapDetails.localPosition;
      _controller.value = Matrix4.identity()
        ..translate(-position.dx * 1, -position.dy * 1)
        ..scale(2.0);
    }
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      appBar: AppBar(
        backgroundColor: Colors.black,
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.close, color: Colors.white),
          onPressed: () => Navigator.of(context).pop(),
        ),
      ),
      body: GestureDetector(
        onDoubleTapDown: _handleDoubleTapDown,
        onDoubleTap: _handleDoubleTap,
        child: Center(
          child: InteractiveViewer(
            transformationController: _controller,
            minScale: 1.0,
            maxScale: 4.0,
            child: Hero(
              tag: widget.imageUrl,
              child: Image(
                image: widget.imageProvider,
                fit: BoxFit.contain,
              ),
            ),
          ),
        ),
      ),
    );
  }
}
