import 'dart:async';

import 'package:didvan/config/design_config.dart';
import 'package:didvan/constants/app_icons.dart';
import 'package:didvan/models/requests/studio.dart';
import 'package:didvan/models/view/action_sheet_data.dart';
import 'package:didvan/routes/routes.dart';
import 'package:didvan/utils/action_sheet.dart';
import 'package:didvan/views/home/studio/studio_state.dart';
import 'package:didvan/views/home/studio/widgets/slider.dart';
import 'package:didvan/views/home/studio/widgets/tab_bar.dart';
import 'package:didvan/views/home/widgets/logo_app_bar.dart';
import 'package:didvan/views/home/widgets/overview/podcast.dart';
import 'package:didvan/views/home/widgets/overview/video.dart';
import 'package:didvan/views/home/widgets/search_field.dart';
import 'package:didvan/views/widgets/animated_visibility.dart';
import 'package:didvan/views/widgets/didvan/divider.dart';
import 'package:didvan/views/widgets/didvan/icon_button.dart';
import 'package:didvan/views/widgets/didvan/radial_button.dart';
import 'package:didvan/views/widgets/item_title.dart';
import 'package:didvan/views/widgets/state_handlers/sliver_state_handler.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class Studio extends StatefulWidget {
  const Studio({Key? key}) : super(key: key);

  @override
  State<Studio> createState() => _StudioState();
}

class _StudioState extends State<Studio> {
  final _focusNode = FocusNode();
  Timer? _timer;

  @override
  void initState() {
    context.read<StudioState>().init();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return CustomScrollView(
      slivers: [
        SliverToBoxAdapter(
          child: Row(
            children: [
              const Expanded(child: LogoAppBar(type: 'studio')),
              Padding(
                padding:
                    EdgeInsets.only(top: MediaQuery.of(context).padding.top),
                child: DidvanIconButton(
                  icon: DidvanIcons.bookmark_regular,
                  onPressed: () => Navigator.of(context).pushNamed(
                    Routes.filteredBookmarks,
                    arguments: {
                      'type': context.read<StudioState>().type,
                      'onDeleted': (_) {}
                    },
                  ),
                ),
              ),
            ],
          ),
        ),
        const SliverToBoxAdapter(
          child: StudioTabBar(),
        ),
        SliverToBoxAdapter(
          child: Padding(
            padding: const EdgeInsets.all(16.0),
            child: SearchField(
              title: 'استودیو',
              onChanged: _onChanged,
              focusNode: _focusNode,
            ),
          ),
        ),
        SliverToBoxAdapter(
          child: Consumer<StudioState>(
            builder: (context, state, child) => AnimatedVisibility(
              isVisible: !state.searching,
              duration: DesignConfig.lowAnimationDuration,
              child: const StudioSlider(),
            ),
          ),
        ),
        const SliverPadding(
          padding: EdgeInsets.symmetric(horizontal: 16),
          sliver: SliverToBoxAdapter(
            child: DidvanDivider(
              verticalPadding: 0,
            ),
          ),
        ),
        SliverPadding(
          padding: const EdgeInsets.symmetric(horizontal: 16),
          sliver: SliverToBoxAdapter(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Consumer<StudioState>(
                  builder: (context, state, child) => AnimatedVisibility(
                    isVisible: !state.searching,
                    duration: DesignConfig.lowAnimationDuration,
                    child: ItemTitle(title: state.orderString),
                  ),
                ),
                DidvanIconButton(
                  gestureSize: 36,
                  icon: DidvanIcons.sort_regular,
                  onPressed: _showSortDialog,
                ),
              ],
            ),
          ),
        ),
        Consumer<StudioState>(
          builder: (context, state, child) => SliverStateHandler<StudioState>(
            state: state,
            itemPadding: const EdgeInsets.only(
              bottom: 8,
              left: 16,
              right: 16,
            ),
            placeholder: state.videosSelected
                ? VideoOverview.placeHolder
                : PodcastOverview.placeholder,
            builder: (context, state, index) => state.videosSelected
                ? VideoOverview(
                    onMarkChanged: state.changeMark,
                    hasUnmarkConfirmation: false,
                    video: state.studios[index],
                    studioRequestArgs: StudioRequestArgs(
                      page: state.page,
                      order: state.order,
                      search: state.search,
                      type: state.type,
                      asc: state.selectedSortTypeIndex == 1,
                    ),
                  )
                : PodcastOverview(
                    podcast: state.studios[index],
                    onMarkChanged: state.changeMark,
                    studioRequestArgs: StudioRequestArgs(
                      page: state.page,
                      order: state.order,
                      search: state.search,
                      type: state.type,
                      asc: state.selectedSortTypeIndex == 1,
                    ),
                  ),
            childCount: state.studios.length,
            onRetry: () => state.getStudios(page: 1),
          ),
        ),
      ],
    );
  }

  void _onChanged(String value) {
    final state = context.read<StudioState>();
    if (value.length < 4 && value.isNotEmpty || state.lastSearch == value) {
      return;
    }
    _timer?.cancel();
    _timer = Timer(const Duration(seconds: 1), () {
      state.search = value;
      state.getStudios(page: 1);
    });
  }

  void _showSortDialog() {
    final state = context.read<StudioState>();
    ActionSheetUtils.showBottomSheet(
      data: ActionSheetData(
        content: StatefulBuilder(
          builder: (context, setState) => Column(
            children: [
              DidvanRadialButton(
                title: 'تازه‌ترین‌ها',
                onSelected: () => setState(
                  () => state.selectedSortTypeIndex = 0,
                ),
                value: state.selectedSortTypeIndex == 0,
              ),
              const SizedBox(height: 24),
              DidvanRadialButton(
                title: 'قدیمی‌ترین‌ها',
                onSelected: () => setState(
                  () => state.selectedSortTypeIndex = 1,
                ),
                value: state.selectedSortTypeIndex == 1,
              ),
              const SizedBox(height: 24),
              DidvanRadialButton(
                title: 'پربازدیدترین‌ها',
                onSelected: () => setState(
                  () => state.selectedSortTypeIndex = 2,
                ),
                value: state.selectedSortTypeIndex == 2,
              ),
              const SizedBox(height: 24),
              DidvanRadialButton(
                title: 'پربحث‌ترین‌ها',
                onSelected: () => setState(
                  () => state.selectedSortTypeIndex = 3,
                ),
                value: state.selectedSortTypeIndex == 3,
              ),
            ],
          ),
        ),
        title: 'مرتب‌‌سازی',
        titleIcon: DidvanIcons.sort_regular,
        hasDismissButton: false,
        confrimTitle: 'مرتب سازی',
        onConfirmed: () => state.getStudios(page: 1),
      ),
    );
  }
}
