import 'package:flutter/material.dart';
import 'package:hoshan/core/gen/assets.gen.dart';
import 'package:hoshan/ui/widgets/components/image/custome_image.dart';
import 'package:hoshan/ui/widgets/sections/loading/default_placeholder.dart';
import 'package:path_provider/path_provider.dart';
import 'package:get_thumbnail_video/index.dart';
import 'package:get_thumbnail_video/video_thumbnail.dart';

class VideoThumbnailWidget extends StatefulWidget {
  final String videoUrl;

  const VideoThumbnailWidget({super.key, required this.videoUrl});

  @override
  State<VideoThumbnailWidget> createState() => _VideoThumbnailWidgetState();
}

class _VideoThumbnailWidgetState extends State<VideoThumbnailWidget> {
  XFile? _thumbnailFile;

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

  Future<void> _generateThumbnail() async {
    final thumbnailPath = await VideoThumbnail.thumbnailFile(
      video: widget.videoUrl,
      thumbnailPath: (await getTemporaryDirectory()).path,
      imageFormat: ImageFormat.JPEG,
      maxHeight:
          300, // specify the height of the thumbnail, let the width auto-scaled to keep the source aspect ratio
      quality: 90,
      maxWidth: 800,
    );

    setState(() {
      _thumbnailFile = thumbnailPath;
    });
  }

  @override
  Widget build(BuildContext context) {
    return ClipRRect(
      borderRadius: BorderRadius.circular(8),
      child: AspectRatio(
        aspectRatio: 16 / 9,
        child: _thumbnailFile != null
            ? Stack(
                children: [
                  Center(child: CustomeImage(src: _thumbnailFile!.path)),
                  Positioned.fill(
                    child: Center(
                      child: Assets.icon.bold.play.svg(
                          width: 64,
                          color: Theme.of(context)
                              .colorScheme
                              .primary
                              .withAlpha(200)),
                    ),
                  )
                ],
              )
            : DefaultPlaceHolder(
                child: Container(
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(16),
                        color: Colors.white))),
      ),
    );
  }
}
