import 'dart:async';

import 'package:didvan/constants/app_icons.dart';
import 'package:didvan/models/enums.dart';
import 'package:didvan/models/requests/news.dart';
import 'package:didvan/models/view/action_sheet_data.dart';
import 'package:didvan/utils/action_sheet.dart';
import 'package:didvan/views/home/news/news_state.dart';
import 'package:didvan/views/home/widgets/date_picker_button.dart';
import 'package:didvan/views/home/widgets/logo_app_bar.dart';
import 'package:didvan/views/home/widgets/news_overview.dart';
import 'package:didvan/views/home/widgets/search_field.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 News extends StatefulWidget {
  const News({Key? key}) : super(key: key);

  @override
  State<News> createState() => _NewsState();
}

class _NewsState extends State<News> {
  Timer? _timer;
  final _focusNode = FocusNode();
  @override
  void initState() {
    context.read<NewsState>().init();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    final state = context.watch<NewsState>();
    return CustomScrollView(
      slivers: [
        const SliverToBoxAdapter(child: LogoAppBar()),
        if (state.appState != AppState.failed)
          SliverPadding(
            padding: const EdgeInsets.only(left: 16, right: 16, bottom: 16),
            sliver: SliverToBoxAdapter(
              child: SearchField(
                focusNode: _focusNode,
                title: 'اخبار',
                onChanged: _onChanged,
                onFilterButtonPressed: _showFilterBottomSheet,
                isFiltered: state.isFiltering,
              ),
            ),
          ),
        SliverStateHandler<NewsState>(
          onRetry: () => state.getNews(page: state.page),
          state: state,
          builder: (context, state, index) {
            index += 2;
            if (index % 15 == 0 && state.lastPage != state.page) {
              state.getNews(page: state.page + 1);
            }
            index -= 2;
            if (index >= state.news.length) {
              return NewsOverview.placeholder;
            }
            final news = state.news[index];
            return NewsOverview(
              news: news,
              onMarkChanged: (id, value) => state.onMarkChanged(id, value),
              newsRequestArgs: NewsRequestArgs(
                page: state.page,
                endDate: state.endDate,
                startDate: state.startDate,
                search: state.search,
              ),
            );
          },
          enableEmptyState: state.news.isEmpty,
          emptyState: EmptyResult(
            onNewSearch: () => _focusNode.requestFocus(),
          ),
          childCount:
              state.news.length + (state.lastPage == state.page ? 0 : 3),
          itemPadding: const EdgeInsets.only(left: 16, right: 16, bottom: 16),
          placeholder: NewsOverview.placeholder,
        ),
      ],
    );
  }

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

  Future<void> _showFilterBottomSheet() async {
    final state = context.read<NewsState>();
    await ActionSheetUtils.showBottomSheet(
      data: ActionSheetData(
        title: 'فیلتر جستجو',
        smallDismissButton: true,
        titleIcon: DidvanIcons.filter_regular,
        dismissTitle: 'حذف فیلتر',
        confrimTitle: 'نمایش نتایج',
        onDismissed: state.resetFilters,
        onConfirmed: () => state.getNews(page: 1),
        content: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            ItemTitle(
              title: 'تاریخ خبر',
              style: Theme.of(context).textTheme.bodyText2,
              icon: DidvanIcons.calendar_range_regular,
            ),
            const SizedBox(height: 8),
            StatefulBuilder(
              builder: (context, setState) => Row(
                children: [
                  DatePickerButton(
                    initialValue: state.startDate,
                    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,
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
