import 'package:flutter/material.dart';
import 'dart:ui_web' as ui_web; // <-- new
import 'package:web/web.dart' as web;
import '../theme/app_theme.dart';

class VideoViewer extends StatefulWidget {
  final String videoUrl;
  final String fileName;

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

  @override
  State<VideoViewer> createState() => _VideoViewerState();
}

class _VideoViewerState extends State<VideoViewer> {
  bool _hasError = false;
  late String _viewType;

  @override
  void initState() {
    super.initState();
    _viewType = 'video-viewer-${widget.videoUrl.hashCode}';
    _registerViewFactory();
  }

  void _registerViewFactory() {
    ui_web.platformViewRegistry.registerViewFactory(_viewType, (int viewId) {
      final videoElement = web.HTMLVideoElement()
        ..src = widget.videoUrl
        ..controls = true
        ..autoplay = false
        ..crossOrigin = 'anonymous'
        ..style.width = '100%'
        ..style.height = '100%'
        ..style.objectFit = 'contain';

      videoElement.onError.listen((event) {
        if (mounted) {
          setState(() => _hasError = true);
        }
      });

      return videoElement;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Dialog(
      backgroundColor: Colors.transparent,
      child: ConstrainedBox(
        constraints: const BoxConstraints(maxWidth: 700, maxHeight: 500),
        child: Container(
          decoration: AppTheme.glassDecoration,
          padding: const EdgeInsets.all(16),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Row(
                children: [
                  Expanded(
                    child: Text(
                      widget.fileName,
                      style: const TextStyle(
                        color: AppTheme.primaryText,
                        fontWeight: FontWeight.bold,
                        fontSize: 18,
                      ),
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                  IconButton(
                    icon: const Icon(Icons.close, color: AppTheme.primaryText),
                    onPressed: () => Navigator.of(context).pop(),
                  ),
                ],
              ),
              const SizedBox(height: 16),
              _hasError
                  ? const Text(
                      'File type not supported or video could not be loaded',
                      style: TextStyle(color: AppTheme.primaryText),
                    )
                  : Expanded(
                      child: Container(
                        color: Colors.black,
                        child: HtmlElementView(viewType: _viewType),
                      ),
                    ),
            ],
          ),
        ),
      ),
    );
  }
}
