import 'package:flutter/material.dart';
import 'package:syncfusion_flutter_pdfviewer/pdfviewer.dart';
import 'package:syncfusion_flutter_core/theme.dart';
import 'package:video_player/video_player.dart';
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:web/web.dart' as web;
import 'dart:ui_web' as ui_web;
import '../theme/app_theme.dart';
import 'audio_player_bar.dart';

class FileViewerDispatch {
  static Widget buildFileViewer(
    BuildContext context,
    String url,
    String mimeType, {
    String? token,
    String? fileName,
    required String viewerId,
    void Function(PdfHyperlinkClickedDetails)? onHyperlinkClicked,
  }) {
    final headers = token != null
        ? {'Authorization': 'Bearer $token'}
        : <String, String>{};

    if (mimeType == 'application/pdf') {
      return SfTheme(
        data: SfThemeData(
          pdfViewerThemeData: SfPdfViewerThemeData(
            backgroundColor: AppTheme.primaryBackground,
            progressBarColor: AppTheme.accentColor,
            scrollStatusStyle: PdfScrollStatusStyle(
              backgroundColor: AppTheme.primaryBackground,
            ),
            scrollHeadStyle: PdfScrollHeadStyle(
              backgroundColor: AppTheme.accentColor,
            ),
          ),
        ),
        child: SfPdfViewer.network(
          url,
          headers: headers,
          canShowScrollHead: false,
          canShowScrollStatus: false,
          enableDoubleTapZooming: true,
          enableTextSelection: false,
          onHyperlinkClicked: onHyperlinkClicked,
          onDocumentLoadFailed: (details) {
            // Handle error
          },
        ),
      );
    } else if (mimeType.startsWith('video/')) {
      if (kIsWeb) {
        // Use HTML video element for web
        ui_web.platformViewRegistry.registerViewFactory(viewerId, (int viewId) {
          final videoElement = web.HTMLVideoElement()
            ..src = url
            ..controls = true
            ..autoplay = false
            ..crossOrigin = 'anonymous'
            ..style.width = '100%'
            ..style.height = '100%'
            ..style.objectFit = 'contain';

          // Add headers if token
          if (token != null) {
            // For web, headers are not directly supported, but since it's public or auth, assume ok
          }

          videoElement.onError.listen((event) {
            // Handle error
          });

          return videoElement;
        });

        return Container(
          color: Colors.black,
          child: HtmlElementView(viewType: viewerId),
        );
      } else {
        // Use VideoPlayer for mobile
        final controller = VideoPlayerController.networkUrl(Uri.parse(url));
        return FutureBuilder<void>(
          future: controller.initialize(),
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.done) {
              return AspectRatio(
                aspectRatio: controller.value.aspectRatio,
                child: VideoPlayer(controller),
              );
            } else {
              return const Center(child: CircularProgressIndicator());
            }
          },
        );
      }
    } else if (mimeType.startsWith('audio/')) {
      return Center(
        child: AudioPlayerBar(
          fileName: fileName ?? 'Audio',
          fileUrl: url,
          mimeType: mimeType,
        ),
      );
    } else if (mimeType.startsWith('image/')) {
      Widget child;
      if (kIsWeb && token == null) {
        // Use HTML img element for web public shares to handle CORS
        ui_web.platformViewRegistry.registerViewFactory(viewerId, (int viewId) {
          final imgElement = web.HTMLImageElement()
            ..src = url
            ..style.width = '100%'
            ..style.height = '100%'
            ..style.objectFit = 'contain'
            ..crossOrigin = 'anonymous';

          imgElement.onError.listen((event) {
            // Handle error
          });

          return imgElement;
        });

        child = HtmlElementView(viewType: viewerId);
      } else {
        // For mobile or authenticated web, use Image.network with headers
        child = Image.network(
          url,
          headers: headers,
          fit: BoxFit.contain,
          errorBuilder: (context, error, stackTrace) {
            return Center(
              child: Text(
                'Failed to load image',
                style: TextStyle(color: Colors.red[400]),
              ),
            );
          },
        );
      }

      Widget viewerChild = child;
      if (!(kIsWeb && token == null)) {
        // Use InteractiveViewer for mobile or authenticated web
        viewerChild = InteractiveViewer(
          minScale: 0.5,
          maxScale: 4.0,
          child: child,
        );
      }

      return Container(color: AppTheme.primaryBackground, child: viewerChild);
    } else {
      return Container(
        color: AppTheme.primaryBackground,
        child: Center(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Icon(
                Icons.description,
                size: 80,
                color: AppTheme.primaryText.withValues(alpha: 0.7),
              ),
              const SizedBox(height: 16),
              Text(
                'File type not supported for preview',
                style: TextStyle(color: AppTheme.primaryText, fontSize: 18),
              ),
              const SizedBox(height: 16),
              ElevatedButton(
                onPressed: () {
                  // Download
                  final anchor = web.HTMLAnchorElement()
                    ..href = url
                    ..download = fileName ?? 'download';
                  anchor.click();
                },
                child: const Text('Download File'),
              ),
            ],
          ),
        ),
      );
    }
  }
}
