import 'package:didvan/models/view/app_bar_data.dart';
import 'package:didvan/views/home/settings/bookmarks/filtered_bookmark/filtered_bookmarks_state.dart';
import 'package:didvan/views/home/widgets/news_overview.dart';
import 'package:didvan/views/home/widgets/radar_overview.dart';
import 'package:didvan/views/widgets/didvan/scaffold.dart';
import 'package:didvan/views/widgets/state_handlers/empty_list.dart';
import 'package:didvan/views/widgets/state_handlers/sliver_state_handler.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

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

  @override
  _FilteredBookmarksState createState() => _FilteredBookmarksState();
}

class _FilteredBookmarksState extends State<FilteredBookmarks> {
  @override
  void initState() {
    Future.delayed(
      Duration.zero,
      context.read<FilteredBookmarksState>().getBookmarks,
    );
    super.initState();
  }

  String get _appBarTitle {
    switch (context.read<FilteredBookmarksState>().type) {
      case 'radar':
        return 'تحلیل‌های رادار';
      case 'news':
        return 'اخبار';
      case 'video':
        return 'ویدئو‌ها';
      case 'podcast':
        return 'پادکست‌ها';
      default:
        return 'پادکست‌ها';
    }
  }

  @override
  Widget build(BuildContext context) {
    return DidvanScaffold(
      appBarData: AppBarData(title: _appBarTitle),
      slivers: [
        Consumer<FilteredBookmarksState>(
          builder: (context, state, child) =>
              SliverStateHandler<FilteredBookmarksState>(
            state: state,
            enableEmptyState: state.bookmarks.isEmpty,
            itemPadding: const EdgeInsets.only(bottom: 8),
            placeholder: RadarOverview.placeholder,
            emptyState: const EmptyList(),
            builder: (context, state, index) {
              if (state.type == 'radar') {
                return RadarOverview(
                  radar: state.bookmarks[index],
                  onMarkChanged: _onBookmarkChanged,
                  onCommentsChanged: state.onCommentsChanged,
                  hasUnmarkConfirmation: true,
                );
              }
              return NewsOverview(
                news: state.bookmarks[index],
                onMarkChanged: _onBookmarkChanged,
                hasUnmarkConfirmation: true,
              );
            },
            childCount: state.bookmarks.length,
            onRetry: () => state.getBookmarks(),
          ),
        ),
      ],
    );
  }

  Future<void> _onBookmarkChanged(int id, bool value) async {
    if (value) return;
    final state = context.read<FilteredBookmarksState>();
    state.onMarkChanged(id, false);
  }
}
