import 'dart:async';

import 'package:didvan/config/design_config.dart';
import 'package:didvan/constants/app_icons.dart';
import 'package:didvan/models/view/app_bar_data.dart';
import 'package:didvan/routes/routes.dart';
import 'package:didvan/views/home/settings/bookmarks/bookmark_state.dart';
import 'package:didvan/views/home/widgets/menu_item.dart';
import 'package:didvan/views/home/widgets/multitype_overview.dart';
import 'package:didvan/views/home/widgets/search_field.dart';
import 'package:didvan/views/widgets/animated_visibility.dart';
import 'package:didvan/views/widgets/didvan/card.dart';
import 'package:didvan/views/widgets/didvan/divider.dart';
import 'package:didvan/views/widgets/didvan/scaffold.dart';
import 'package:didvan/views/widgets/item_title.dart';
import 'package:didvan/views/widgets/state_handlers/empty_list.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 Bookmarks extends StatefulWidget {
  const Bookmarks({Key? key}) : super(key: key);

  @override
  State<Bookmarks> createState() => _BookmarksState();
}

class _BookmarksState extends State<Bookmarks> {
  final _focuseNode = FocusNode();
  Timer? _timer;

  @override
  void initState() {
    Future.delayed(Duration.zero, () {
      context.read<BookmarksState>().getBookmarks();
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    final state = context.watch<BookmarksState>();
    return DidvanScaffold(
      appBarData: AppBarData(
        title: 'نشان شده‌ها',
        hasBack: true,
      ),
      children: [
        SearchField(
          title: 'نشان شده‌ها',
          onChanged: _onChanged,
          focusNode: _focuseNode,
        ),
        const SizedBox(height: 16),
        AnimatedVisibility(
          duration: DesignConfig.lowAnimationDuration,
          isVisible: !state.searching,
          child: DidvanCard(
            child: Column(
              children: [
                MenuItem(
                  onTap: () => _onCategorySelected('radar'),
                  title: 'تحلیل‌های رادار',
                  icon: DidvanIcons.radar_regular,
                  iconSize: 24,
                ),
                const DidvanDivider(),
                MenuItem(
                  onTap: () => _onCategorySelected('news'),
                  title: 'اخبار',
                  icon: DidvanIcons.news_regular,
                  iconSize: 24,
                ),
                const DidvanDivider(),
                MenuItem(
                  onTap: () => _onCategorySelected('videos'),
                  title: 'ویدئو‌ها',
                  icon: DidvanIcons.video_regular,
                  iconSize: 24,
                ),
                const DidvanDivider(),
                MenuItem(
                  onTap: () => _onCategorySelected('podcasts'),
                  title: 'پادکست‌ها',
                  icon: DidvanIcons.podcast_regular,
                  iconSize: 24,
                ),
              ],
            ),
          ),
        ),
        Align(
          alignment: Alignment.centerRight,
          child: AnimatedVisibility(
            duration: DesignConfig.lowAnimationDuration,
            isVisible: !state.searching,
            child: const ItemTitle(title: 'آخرین نشان شده‌ها'),
          ),
        ),
      ],
      slivers: [
        SliverStateHandler<BookmarksState>(
          state: state,
          centerEmptyState: state.searching,
          builder: (context, state, index) => MultitypeOverview(
            item: state.bookmarks[index],
            onMarkChanged: state.onMarkChanged,
            hasUnmarkConfirmation: true,
          ),
          placeholder: MultitypeOverview.placeholder,
          itemPadding: const EdgeInsets.only(bottom: 8),
          emptyState: state.searching
              ? EmptyResult(onNewSearch: _focuseNode.requestFocus)
              : const EmptyList(),
          enableEmptyState: state.bookmarks.isEmpty,
          childCount: state.bookmarks.length,
          onRetry: state.getBookmarks,
        ),
      ],
    );
  }

  void _onCategorySelected(String type) {
    if (type != 'radar' && type != 'news') return;
    FocusScope.of(context).unfocus();
    Navigator.of(context).pushNamed(Routes.filteredBookmarks, arguments: type);
  }

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