// Copyright (C) 2022 WYATT GROUP
// Please see the AUTHORS file for details.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

import 'package:architecture_example/domain/entities/photo.dart';
import 'package:architecture_example/presentation/features/photos/blocs/photo/photo_bloc.dart';
import 'package:architecture_example/presentation/features/photos/state_management/widgets/photos_grid_thumbnail.dart';
import 'package:architecture_example/presentation/shared/widgets/bottom_loader.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

class PhotosGrid extends StatefulWidget {
  const PhotosGrid({
    required this.photos,
    required this.albumId,
    required this.hasReachedMax,
    super.key,
  });

  final List<Photo> photos;
  final int albumId;
  final bool hasReachedMax;

  @override
  State<PhotosGrid> createState() => _PhotosGridState();
}

class _PhotosGridState extends State<PhotosGrid> {
  final _scrollController = ScrollController();

  @override
  void initState() {
    super.initState();
    _scrollController.addListener(_onScroll);
  }

  @override
  void dispose() {
    _scrollController
      ..removeListener(_onScroll)
      ..dispose();
    super.dispose();
  }

  void _onScroll() {
    if (_isBottom) {
      context.read<PhotoBloc>().add(PhotoFetched(widget.albumId));
    }
  }

  bool get _isBottom {
    if (!_scrollController.hasClients) {
      return false;
    }
    final maxScroll = _scrollController.position.maxScrollExtent;
    final currentScroll = _scrollController.offset;
    return currentScroll >= (maxScroll * 0.9);
  }

  @override
  Widget build(BuildContext context) => GridView.builder(
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisSpacing: 4,
        mainAxisSpacing: 4,
        crossAxisCount: 4,
      ),
      itemCount: widget.hasReachedMax
          ? widget.photos.length
          : widget.photos.length + 1,
      controller: _scrollController,
      itemBuilder: (context, index) => index >= widget.photos.length
          ? const BottomLoader()
          : PhotosGridThumbnail(photo: widget.photos[index]),
    );
}
