import 'package:collection/collection.dart';
import 'package:didvan/models/enums.dart';
import 'package:didvan/views/home/home_state.dart';
import 'package:didvan/views/home/search/widgets/search_result_item.dart';
import 'package:didvan/views/widgets/categories_list.dart';
import 'package:didvan/views/widgets/state_handlers/empty_result.dart';
import 'package:didvan/views/widgets/state_handlers/state_handler.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class SearchPage extends StatelessWidget {
  const SearchPage({super.key});

  @override
  Widget build(BuildContext context) {
    final state = context.watch<HomeState>();
    return SizedBox(
      height: MediaQuery.of(context).size.height,
      width: MediaQuery.of(context).size.width,
      child: Stack(
        children: [
          StateHandler<HomeState>(
            state: state,
            enableEmptyState:
                state.appState == AppState.idle && state.results.isEmpty,
            emptyState: EmptyResult(
              onNewSearch: () => state.searchFieldFocusNode.requestFocus(),
            ),
            onRetry: () => state.searchAll(page: state.page),
            builder: (context, state) => ListView.builder(
              padding: const EdgeInsets.all(16)
                  .copyWith(top: state.selectedCats.length <= 1 ? 72 : 16),
              itemBuilder: (context, index) {
                index += 2;
                if (index % 15 == 0 && state.lastPage != state.page) {
                  state.searchAll(page: state.page + 1);
                }
                index -= 2;
                return Padding(
                  padding: const EdgeInsets.only(bottom: 8),
                  child: SearchResultItem(
                    item: state.results[index],
                  ),
                );
              },
              itemCount: state.results.length,
            ),
          ),
          CategoriesList(
            isColapsed: state.selectedCats.length <= 1,
            selectedCats: state.selectedCats,
            categories: state.categoryFilters,
            disableHoushan: true,
            onSelected: (id) {
              state.selectedCats.clear();
              final cat = state.categoryFilters
                  .firstWhereOrNull((element) => element.id == id);
              if (cat != null) {
                state.selectedCats.add(cat);
              }
              state.searchAll(page: 1);
            },
            top: 0,
          ),
        ],
      ),
    );
  }
}
