import 'dart:async';

import 'package:didvan/config/design_config.dart';
import 'package:didvan/constants/app_icons.dart';
import 'package:didvan/models/enums.dart';
import 'package:didvan/models/requests/studio.dart';
import 'package:didvan/models/view/action_sheet_data.dart';
import 'package:didvan/models/view/app_bar_data.dart';
import 'package:didvan/routes/routes.dart';
import 'package:didvan/utils/action_sheet.dart';
import 'package:didvan/views/podcasts/podcasts_state.dart';
import 'package:didvan/views/podcasts/widgets/slider.dart';
import 'package:didvan/views/podcasts/widgets/tab_bar.dart';
import 'package:didvan/views/widgets/date_picker_button.dart';
import 'package:didvan/views/widgets/didvan/scaffold.dart';
import 'package:didvan/views/widgets/overview/podcast.dart';
import 'package:didvan/views/widgets/overview/video.dart';
import 'package:didvan/views/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/empty_result.dart';
import 'package:didvan/views/widgets/state_handlers/sliver_state_handler.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class Podcasts extends StatefulWidget {
  final Map<String, dynamic>? pageData;
  final bool? viewPodcasts;

  const Podcasts({Key? key, this.viewPodcasts, this.pageData})
      : super(key: key);

  @override
  State<Podcasts> createState() => _PodcastsState();
}

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

  @override
  void initState() {
    context.read<PodcastsState>().init(widget.viewPodcasts);

    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': widget.pageData?['id'],
              'type': 'studio',
              'title': '',
            },
          ),
        );
      }
    }

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<PodcastsState>(
      builder: (context, state, child) => DidvanScaffold(
        padding: EdgeInsets.zero,
        appBarData: AppBarData(hasBack: true, title: 'استودیو دیدوان'),
        slivers: [
          // const SliverToBoxAdapter(child: LogoAppBar()),
          SliverAppBar(
            toolbarHeight: 140,
            automaticallyImplyLeading: false,
            pinned: true,
            scrolledUnderElevation: 0,
            backgroundColor: Theme.of(context).colorScheme.surface,
            flexibleSpace: Column(
              children: [
                const StudioTabBar(),
                if (state.appState != AppState.failed)
                  Padding(
                    padding: const EdgeInsets.all(16.0),
                    child: SearchField(
                      title: state.videosSelected ? 'ویدیوکست' : 'پادکست',
                      onChanged: _onChanged,
                      focusNode: _focusNode,
                      isFiltered: false,
                      onFilterButtonPressed: _showFilterBottomSheet,
                    ),
                  ),
              ],
            ),
          ),
          const SliverToBoxAdapter(
              child: SizedBox(
            height: 16,
          )),
          if (state.appState != AppState.failed)
            SliverToBoxAdapter(
              child: AnimatedVisibility(
                isVisible: !state.searching,
                duration: DesignConfig.lowAnimationDuration,
                child: const StudioSlider(),
              ),
            ),
          if (state.appState != AppState.failed && state.studios.isNotEmpty)
            const SliverPadding(
              padding: EdgeInsets.symmetric(horizontal: 16),
              sliver: SliverToBoxAdapter(
                child: DidvanDivider(
                  verticalPadding: 0,
                ),
              ),
            ),
          if (state.appState != AppState.failed && state.studios.isNotEmpty)
            SliverPadding(
              padding: const EdgeInsets.symmetric(horizontal: 16),
              sliver: SliverToBoxAdapter(
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    AnimatedVisibility(
                      isVisible: !state.searching,
                      duration: DesignConfig.lowAnimationDuration,
                      child: ItemTitle(title: state.orderString),
                    ),
                    DidvanIconButton(
                      gestureSize: 36,
                      icon: DidvanIcons.sort_regular,
                      onPressed: _showSortDialog,
                    ),
                  ],
                ),
              ),
            ),
          SliverStateHandler<PodcastsState>(
            state: state,
            itemPadding: const EdgeInsets.only(
              bottom: 8,
              left: 16,
              right: 16,
            ),
            emptyState: EmptyResult(
              onNewSearch: () => _focusNode.requestFocus(),
            ),
            centerEmptyState: false,
            enableEmptyState: state.studios.isEmpty,
            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<PodcastsState>();
    if (value.length < 3 && 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<PodcastsState>();
    ActionSheetUtils(context).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),
      ),
    );
  }

  Future<void> _showFilterBottomSheet() async {
    final state = context.read<PodcastsState>();
    await ActionSheetUtils(context).showBottomSheet(
      data: ActionSheetData(
        title: 'فیلتر جستجو',
        smallDismissButton: true,
        titleIcon: DidvanIcons.filter_regular,
        dismissTitle: 'حذف فیلتر',
        confrimTitle: 'نمایش نتایج',
        onDismissed: () => state.resetFilters(false),
        onConfirmed: () => state.getStudios(page: 1),
        content: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            ItemTitle(
              title: 'تاریخ ایجاد',
              style: Theme.of(context).textTheme.bodyMedium,
              icon: DidvanIcons.calendar_range_regular,
            ),
            const SizedBox(height: 8),
            StatefulBuilder(
              builder: (context, setState) => Row(
                children: [
                  DatePickerButton(
                    initialValue: state.startDate?.toString(),
                    emptyText: 'از تاریخ',
                    onPicked: (date) => setState(() => state.startDate = date),
                    lastDate: state.endDate,
                  ),
                  const SizedBox(width: 8),
                  DatePickerButton(
                    initialValue: state.endDate,
                    emptyText: 'تا تاریخ',
                    onPicked: (date) => setState(() => state.endDate = date),
                    firstDate: state.startDate,
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
