// ignore_for_file: use_build_context_synchronously, deprecated_member_use

import 'package:chewie/chewie.dart';
import 'package:didvan/config/theme_data.dart';
import 'package:didvan/constants/assets.dart';
import 'package:didvan/models/studio_details_data.dart';
import 'package:didvan/models/view/app_bar_data.dart';
import 'package:didvan/services/media/media.dart';
import 'package:didvan/views/podcasts/studio_details/studio_details_state.dart';
import 'package:didvan/views/podcasts/studio_details/widgets/studio_details_widget.dart';
import 'package:didvan/views/widgets/bookmark_button.dart';
import 'package:didvan/views/widgets/didvan/app_bar.dart';
import 'package:didvan/views/widgets/state_handlers/state_handler.dart';
import 'package:didvan/views/widgets/video/primary_controls.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:didvan/routes/routes.dart';
import 'package:video_player/video_player.dart';

class StudioDetails extends StatefulWidget {
  final Map<String, dynamic> pageData;

  const StudioDetails({Key? key, required this.pageData}) : super(key: key);

  @override
  State<StudioDetails> createState() => _StudioDetailsState();
}

class _StudioDetailsState extends State<StudioDetails> {
  int _currentlyPlayingId = 0;
  VideoPlayerController? _videoPlayerController;
  ChewieController? _chewieController;

  @override
  void initState() {
    super.initState();
    final state = context.read<StudioDetailsState>();
    state.args = widget.pageData['args'];

    Future.delayed(
      Duration.zero,
      () => state.getStudioDetails(widget.pageData['id']).then((_) {
        if (mounted) {
          _initializePlayer(state.studio);
        }
      }),
    );

    if (widget.pageData['goToComment'] != null) {
      var openComments = widget.pageData['goToComment'];

      if (openComments) {
        Future.delayed(
          const Duration(seconds: 1),
          () => Navigator.of(context).pushNamed(
            Routes.mentions,
            arguments: {
              'id': context.read<StudioDetailsState>().studio.id,
              'type': 'studio',
              'title': context.read<StudioDetailsState>().studio.title,
            },
          ),
        );
      }
    }
  }

  Future<void> _initializePlayer(StudioDetailsData studio) async {
    // Disposing old controllers before creating new ones.
    _videoPlayerController?.dispose();
    _chewieController?.dispose();

    _videoPlayerController = VideoPlayerController.network(studio.link);
    
    try {
      await _videoPlayerController!.initialize();
      if (mounted) {
        setState(() {
          _chewieController = ChewieController(
            videoPlayerController: _videoPlayerController!,
            customControls: const PrimaryControls(),
            autoPlay: true,
            looping: true,
            aspectRatio: 16 / 9,
            materialProgressColors: ChewieProgressColors(
              playedColor: Theme.of(context).colorScheme.title,
              handleColor: Theme.of(context).colorScheme.title,
            ),
          );
          _currentlyPlayingId = studio.id;
        });
      }
    } catch (e) {
        debugPrint("Error initializing video player: $e");
    }
  }

  @override
  Widget build(BuildContext context) {
    final d = MediaQuery.of(context);
    return Consumer<StudioDetailsState>(
      builder: (context, state, child) {
        if (state.isStudioLoaded && _currentlyPlayingId != state.studio.id) {
          Future.microtask(() => _initializePlayer(state.studio));
        }
        return StateHandler<StudioDetailsState>(
          state: state,
          onRetry: () {
            try {
              state.getStudioDetails(state.studio.id);
            } catch (e) {
              state.getStudioDetails(widget.pageData['id']);
            }
          },
          builder: (context, state) {
            if (!state.isStudioLoaded) {
              return Center(
                child: Image.asset(
                  Assets.loadingAnimation,
                  width: 100,
                  height: 100,
                ),
              );
            }
            return WillPopScope(
              onWillPop: () async {
                if (MediaService.currentPodcast != null) {
                  state.studio = MediaService.currentPodcast!;
                }
                state.handleTracking(id: state.studio.id);
                return true;
              },
              child: SafeArea(
                child: Scaffold(
                  backgroundColor: Theme.of(context).colorScheme.surface,
                  appBar: PreferredSize(
                    preferredSize: const Size.fromHeight(56),
                    child: DidvanAppBar(
                      appBarData: AppBarData(
                        trailing: BookmarkButton(
                          itemId: state.studio.id,
                          type: 'video',
                          value: state.studio.marked,
                          onMarkChanged: (value) {
                            widget.pageData['onMarkChanged'](
                                state.studio.id, value);
                          },
                          gestureSize: 48,
                        ),
                        isSmall: true,
                        title: state.studio.title,
                      ),
                    ),
                  ),
                  body: SingleChildScrollView(
                    child: SizedBox(
                      height: d.size.height - d.padding.top - 56,
                      child: Column(
                        children: [
                          AspectRatio(
                            aspectRatio: 16 / 9,
                            child: (_chewieController != null &&
                                    _chewieController!
                                        .videoPlayerController.value.isInitialized)
                                ? Chewie(controller: _chewieController!)
                                : Center(
                                    child: Image.asset(
                                      Assets.loadingAnimation,
                                      width: 100,
                                      height: 100,
                                    ),
                                  ),
                          ),
                          Expanded(
                            child: StudioDetailsWidget(
                              onMarkChanged: (id, value) => widget
                                  .pageData['onMarkChanged'](id, value, true),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
              ),
            );
          },
        );
      },
    );
  }

  @override
  void dispose() {
    _videoPlayerController?.dispose();
    _chewieController?.dispose();
    super.dispose();
  }
}