import 'dart:convert';
import 'package:flick_video_player/flick_video_player.dart';
import 'package:flutter/material.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:flutter_widget_from_html_core/flutter_widget_from_html_core.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:top_news_app/helper/helper.dart';
import 'package:top_news_app/helper/image_cached.dart';
import 'package:top_news_app/model/Ads.dart';
import 'package:top_news_app/model/Article.dart';
import 'package:top_news_app/model/Polling.dart';
import 'package:top_news_app/providers/article_provider.dart';
import 'package:top_news_app/widget/ads_card.dart';
import 'package:top_news_app/widget/audio_widget.dart';
import 'package:top_news_app/widget/carousel_md_one.dart';
import 'package:top_news_app/widget/polling_card.dart';
import 'package:video_player/video_player.dart';
import 'package:visibility_detector/visibility_detector.dart';
import 'package:youtube_player_flutter/youtube_player_flutter.dart';


class PostDetailsWidget extends StatefulWidget {
  final Details postDetails;
  const PostDetailsWidget({super.key, required this.postDetails});

  @override
  State<PostDetailsWidget> createState() => _PostDetailsWidgetState();
}

class _PostDetailsWidgetState extends State<PostDetailsWidget> {
  late bool _isLoading = true;
  late Widget bodyWidget = Container();
  late FlickManager flickManager;
  late YoutubePlayerController controller;
  late PollingData pollingData;
  late AdsData adsData;
  bool isPlaying = false;
  Duration duration = Duration.zero;
  Duration positions = Duration.zero;
  var articleProvider = ArticleProvider();

  renderWidget() async {
    try {
      switch (widget.postDetails.type) {
        case 'youtube_video':
          {
            String videoId = widget.postDetails.content!.replaceAll("https://www.youtube.com/embed/", "");
            controller = YoutubePlayerController(
              initialVideoId: videoId,
              flags: const YoutubePlayerFlags(
                autoPlay: true,
                mute: true,
              ),
            );

            bodyWidget = YoutubePlayer(
              controller: controller,
              aspectRatio: 16 / 9,
            );
          }
          break;
        case 'video_source':
          {
            flickManager = FlickManager(
              videoPlayerController: VideoPlayerController.networkUrl(
                  Uri.parse(widget.postDetails.content!)),
            );

            bodyWidget = VisibilityDetector(
              key: ObjectKey(flickManager),
              onVisibilityChanged: (visibility) {
                if (visibility.visibleFraction == 0 && mounted) {
                  flickManager.flickControlManager?.autoPause();
                } else if (visibility.visibleFraction == 1) {
                  flickManager.flickControlManager?.autoResume();
                }
              },
              child: FlickVideoPlayer(
                flickManager: flickManager,
                flickVideoWithControls: const FlickVideoWithControls(
                  closedCaptionTextStyle: TextStyle(fontSize: 8),
                  controls: FlickPortraitControls(),
                ),
                flickVideoWithControlsFullscreen: const FlickVideoWithControls(
                  controls: FlickLandscapeControls(),
                ),
              ),
            );
          }
          break;

        case 'audio':
          {
            bodyWidget = AudioWidget(url: widget.postDetails.content ?? '');
          }
          break;

        case 'audio_file':
          {
            bodyWidget = AudioWidget(url: widget.postDetails.content ?? '');
          }
          break;

        case 'descriptions':
          {

            bodyWidget = Html(data: widget.postDetails.content!.replaceAll(RegExp(r'<[^>]*>'), ''));
          }
          break;

        case 'descriptions-2nd':
          {
            bodyWidget = Html(data: widget.postDetails.content!.replaceAll(RegExp(r'<[^>]*>'), ''));
          }
          break;

        case 'descriptions-3rd':
          {
            bodyWidget = Html(data: widget.postDetails.content!.replaceAll(RegExp(r'<[^>]*>'), ''));
          }
          break;

        case 'single_image':
          {
            bodyWidget = ImageCached(
              image: '${widget.postDetails.content}',
              width: 600,
              blur: false,
              fit: BoxFit.cover,
              height: 250,
            );
          }
          break;

        case 'polling':
          {
            pollingData = await articleProvider
                .getSinglePolling(widget.postDetails.content);
            bodyWidget = PollingCard(polling: const [], poll: pollingData);
          }
          break;
        case 'ads':
          {
            adsData =
                await articleProvider.getSingleAds(widget.postDetails.content);
            bodyWidget = AdsCardWidget(data: adsData, ads: const []);
          }
          break;

        case 'gallery_image':
          {
            List<dynamic> images = jsonDecode(widget.postDetails.content!);
            bodyWidget = CarouselMdOne(images: images);
          }
          break;

        default:
          {
            //statements;
          }
          break;
      }
    } catch (e) {
      bodyWidget = Container();
    }

    setState(() {
      _isLoading = false;
    });
  }

  @override
  void initState() {

    super.initState();
    renderWidget();
  }

  @override
  void dispose() {
    if (widget.postDetails.type == 'video_source') {
      flickManager.dispose();
    }

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return _isLoading
        ? const Padding(
            padding: EdgeInsets.all(30),
            child: Center(
              child: CircularProgressIndicator(),
            ),
          )
        : Column(
            children: [bodyWidget, customSizeBox(10)],
          );
  }
}
