import 'dart:async';
import 'package:didvan/routes/routes.dart';
import 'package:didvan/views/home/media/widgets/featured_video_card.dart';
import 'package:didvan/views/home/media/widgets/videocast_grid_card.dart';
import 'package:didvan/views/podcasts/podcasts_state.dart';
import 'package:didvan/views/widgets/overview/podcast.dart';
import 'package:didvan/views/widgets/state_handlers/empty_result.dart';
import 'package:didvan/views/widgets/state_handlers/state_handler.dart';
import 'package:didvan/views/widgets/item_title.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:provider/provider.dart';

class VideoCastTabPage extends StatefulWidget {
  const VideoCastTabPage({super.key});

  @override
  State<VideoCastTabPage> createState() => _VideoCastTabPageState();
}

class _VideoCastTabPageState extends State<VideoCastTabPage> {
  int _currentFeaturedIndex = 0;
  Timer? _rotationTimer;

  @override
  void initState() {
    super.initState();
    Future.microtask(() {
      context.read<PodcastsState>().init(false);
      context.read<PodcastsState>().getStudios(page: 1);
    });
  }

  void _startRotation() {
    _rotationTimer?.cancel();
    _rotationTimer = Timer.periodic(const Duration(seconds: 5), (timer) {
      final state = context.read<PodcastsState>();
      if (state.studios.isNotEmpty && mounted) {
        setState(() {
          _currentFeaturedIndex =
              (_currentFeaturedIndex + 1) % state.studios.length;
        });
      }
    });
  }

  void _showSortDialog() {
    final state = context.read<PodcastsState>();
    showModalBottomSheet(
      backgroundColor: Colors.white,
      context: context,
      builder: (context) {
        return Container(
          padding: const EdgeInsets.all(16),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              ListTile(
                title: const Text('تازه‌ترین‌ها'),
                onTap: () {
                  state.selectedSortTypeIndex = 0;
                  state.getStudios(page: 1);
                  Navigator.pop(context);
                },
              ),
              ListTile(
                title: const Text('قدیمی‌ترین‌ها'),
                onTap: () {
                  state.selectedSortTypeIndex = 1;
                  state.getStudios(page: 1);
                  Navigator.pop(context);
                },
              ),
              ListTile(
                title: const Text('پربازدیدترین‌ها'),
                onTap: () {
                  state.selectedSortTypeIndex = 2;
                  state.getStudios(page: 1);
                  Navigator.pop(context);
                },
              ),
              ListTile(
                title: const Text('پربحث‌ترین‌ها'),
                onTap: () {
                  state.selectedSortTypeIndex = 3;
                  state.getStudios(page: 1);
                  Navigator.pop(context);
                },
              ),
            ],
          ),
        );
      },
    );
  }

  @override
  void dispose() {
    _rotationTimer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final state = context.watch<PodcastsState>();

    return StateHandler<PodcastsState>(
      state: state,
      emptyState: EmptyResult(
        onNewSearch: () {},
      ),
      enableEmptyState: state.studios.isEmpty,
      placeholder: PodcastOverview.placeholder,
      builder: (context, state) {
        if (state.studios.isEmpty) {
          return const SizedBox.shrink();
        }

        if (_rotationTimer == null || !_rotationTimer!.isActive) {
          WidgetsBinding.instance.addPostFrameCallback((_) {
            _startRotation();
          });
        }

        return SingleChildScrollView(
          child: Column(
            children: [
              AnimatedSwitcher(
                duration: const Duration(milliseconds: 500),
                transitionBuilder: (Widget child, Animation<double> animation) {
                  return FadeTransition(opacity: animation, child: child);
                },
                child: FeaturedVideoCard(
                  key: ValueKey<int?>(state.studios[_currentFeaturedIndex].id),
                  videocast: state.studios[_currentFeaturedIndex],
                  onTap: () {
                    Navigator.pushNamed(
                      context,
                      Routes.videoDetails,
                      arguments: {
                        'id': state.studios[_currentFeaturedIndex].id,
                        'type': state.studios[_currentFeaturedIndex].type,
                      },
                    );
                  },
                ),
              ),

              if (state.studios.length > 1)
                Padding(
                  padding:
                      const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      const ItemTitle(
                        title: 'همه ویدیوکست‌ها',
                        color: Color.fromARGB(255, 0, 53, 70),
                        style: TextStyle(fontWeight: FontWeight.bold,fontSize: 18),
                      ),
                      Row(
                        children: [
                          GestureDetector(
                              onTap: _showSortDialog,
                              child: Text(
                                state.orderString,
                                style: const TextStyle(
                                    color: Color.fromARGB(255, 0, 53, 70)),
                              )),
                          IconButton(
                              onPressed: _showSortDialog,
                              icon: SvgPicture.asset(
                                  'lib/assets/icons/sort2.svg')),
                        ],
                      ),
                    ],
                  ),
                ),

              if (state.studios.length > 1)
                Padding(
                  padding: const EdgeInsets.all(16),
                  child: GridView.builder(
                    shrinkWrap: true,
                    physics: const NeverScrollableScrollPhysics(),
                    gridDelegate:
                        const SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 2,
                      crossAxisSpacing: 12,
                      mainAxisSpacing: 12,
                      childAspectRatio: 0.75,
                    ),
                    itemCount: state.studios.length,
                    itemBuilder: (context, index) {
                      final videocast = state.studios[index];
                      return VideocastGridCard(
                        videocast: videocast,
                        onTap: () {
                          Navigator.pushNamed(
                            context,
                            Routes.videoDetails,
                            arguments: {
                              'id': videocast.id,
                              'type': videocast.type,
                            },
                          );
                        },
                      );
                    },
                  ),
                ),
            ],
          ),
        );
      },
      onRetry: () => context.read<PodcastsState>().getStudios(page: 1),
    );
  }
}