import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/services.dart';
import 'package:http/http.dart' as http;
import 'package:path_provider/path_provider.dart';
import 'package:share_plus/share_plus.dart';
import 'package:tugas_akhir_supabase/utils/plugin_utils.dart';
import 'dart:io';

class ImageDetailScreen extends StatefulWidget {
  final String imageUrl;
  final String? senderName;
  final DateTime? timestamp;
  final String heroTag;

  const ImageDetailScreen({
    super.key,
    required this.imageUrl,
    this.senderName,
    this.timestamp,
    required this.heroTag,
  });

  @override
  State<ImageDetailScreen> createState() => _ImageDetailScreenState();
}

class _ImageDetailScreenState extends State<ImageDetailScreen> {
  final TransformationController _transformationController =
      TransformationController();
  bool _isFullScreen = false;
  bool _isDownloading = false;
  final bool _showControls = true;
  String? _errorMessage;

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      appBar: AppBar(
        backgroundColor: Colors.black,
        elevation: 0,
        title: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            if (widget.senderName != null)
              Text(
                widget.senderName!,
                style: const TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                  color: Colors.white,
                ),
              ),
            if (widget.timestamp != null)
              Text(
                widget.timestamp!.toString(),
                style: const TextStyle(
                  fontSize: 12,
                  fontWeight: FontWeight.normal,
                  color: Colors.white70,
                ),
              ),
          ],
        ),
      ),
      body: GestureDetector(
        onTap: () {
          setState(() {
            _isFullScreen = !_isFullScreen;
          });
        },
        child: Center(
          child: InteractiveViewer(
            transformationController: _transformationController,
            minScale: 0.5,
            maxScale: 4.0,
            child: Hero(
              tag: widget.heroTag,
              child: CachedNetworkImage(
                imageUrl: widget.imageUrl,
                fit: BoxFit.contain,
                width: MediaQuery.of(context).size.width,
                height: MediaQuery.of(context).size.height,
                progressIndicatorBuilder:
                    (context, url, downloadProgress) => Center(
                      child: CircularProgressIndicator(
                        value: downloadProgress.progress,
                        color: Colors.white,
                      ),
                    ),
                errorWidget:
                    (context, url, error) => Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Icon(Icons.error, color: Colors.red, size: 48),
                        SizedBox(height: 16),
                        Text(
                          'Image failed to load',
                          style: TextStyle(color: Colors.white),
                        ),
                        SizedBox(height: 16),
                        ElevatedButton(
                          onPressed: () => Navigator.pop(context),
                          child: Text('Go Back'),
                        ),
                      ],
                    ),
              ),
            ),
          ),
        ),
      ),
    );
  }

  Future<void> _shareImage() async {
    if (kIsWeb) {
      setState(() {
        _errorMessage = 'Sharing images is not supported on web version';
      });
      return;
    }

    setState(() {
      _isDownloading = true;
      _errorMessage = null;
    });

    try {
      // Download image
      final http.Response response = await http.get(Uri.parse(widget.imageUrl));

      // Save to temporary file
      final tempDir = await getTemporaryDirectory();
      final file = File('${tempDir.path}/shared_image.jpg');
      await file.writeAsBytes(response.bodyBytes);

      // Share the file
      await Share.shareXFiles([
        XFile(file.path),
      ], text: 'Image from TaniSM4RT app');

      setState(() {
        _isDownloading = false;
      });
    } catch (e) {
      setState(() {
        _isDownloading = false;
        _errorMessage = 'Failed to share image: ${e.toString()}';
      });
    }
  }

  void _zoomIn() {
    final Matrix4 currentMatrix = _transformationController.value;
    final Matrix4 newMatrix =
        currentMatrix * Matrix4.identity()
          ..scale(1.25);
    _transformationController.value = newMatrix;
  }

  void _zoomOut() {
    final Matrix4 currentMatrix = _transformationController.value;
    final Matrix4 newMatrix =
        currentMatrix * Matrix4.identity()
          ..scale(0.8);
    _transformationController.value = newMatrix;
  }

  void _resetZoom() {
    _transformationController.value = Matrix4.identity();
  }
}
