import 'dart:async';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:twonly/globals.dart';
import 'package:twonly/src/database/tables/mediafiles.table.dart';
import 'package:twonly/src/database/twonly.db.dart';
import 'package:twonly/src/model/memory_item.model.dart';
import 'package:twonly/src/services/mediafiles/mediafile.service.dart';
import 'package:twonly/src/utils/misc.dart';
import 'package:twonly/src/views/memories/memories_item_thumbnail.dart';
import 'package:twonly/src/views/memories/memories_photo_slider.view.dart';

class MemoriesView extends StatefulWidget {
  const MemoriesView({super.key});

  @override
  State<MemoriesView> createState() => MemoriesViewState();
}

class MemoriesViewState extends State<MemoriesView> {
  bool verticalGallery = false;
  List<MemoryItem> galleryItems = [];
  Map<String, List<int>> orderedByMonth = {};
  List<String> months = [];
  StreamSubscription<List<MediaFile>>? messageSub;

  @override
  void initState() {
    super.initState();
    unawaited(initAsync());
  }

  @override
  void dispose() {
    messageSub?.cancel();
    super.dispose();
  }

  Future<void> initAsync() async {
    await messageSub?.cancel();
    final msgStream = twonlyDB.mediaFilesDao.watchAllStoredMediaFiles();

    messageSub = msgStream.listen((mediaFiles) async {
      // Group items by month
      orderedByMonth = {};
      months = [];
      var lastMonth = '';
      galleryItems = [];
      for (final mediaFile in mediaFiles) {
        final mediaService = MediaFileService(mediaFile);
        if (!mediaService.imagePreviewAvailable) continue;
        if (mediaService.mediaFile.type == MediaType.video) {
          if (!mediaService.thumbnailPath.existsSync()) {
            await mediaService.createThumbnail();
          }
        }
        galleryItems.add(
          MemoryItem(
            mediaService: mediaService,
            messages: [],
          ),
        );
      }
      galleryItems.sort(
        (a, b) => b.mediaService.mediaFile.createdAt.compareTo(
          a.mediaService.mediaFile.createdAt,
        ),
      );
      for (var i = 0; i < galleryItems.length; i++) {
        final month = DateFormat('MMMM yyyy')
            .format(galleryItems[i].mediaService.mediaFile.createdAt);
        if (lastMonth != month) {
          lastMonth = month;
          months.add(month);
        }
        orderedByMonth.putIfAbsent(month, () => []).add(i);
      }
      if (mounted) {
        setState(() {});
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Memories')),
      body: Scrollbar(
        child: (galleryItems.isEmpty)
            ? Center(
                child: Text(
                  context.lang.memoriesEmpty,
                  textAlign: TextAlign.center,
                ),
              )
            : ListView.builder(
                itemCount: months.length * 2,
                itemBuilder: (context, mIndex) {
                  if (mIndex.isEven) {
                    return Padding(
                      padding: const EdgeInsets.all(8),
                      child: Text(months[(mIndex ~/ 2)]),
                    );
                  }
                  final index = (mIndex - 1) ~/ 2;
                  return GridView.builder(
                    shrinkWrap: true,
                    physics: const ClampingScrollPhysics(),
                    gridDelegate:
                        const SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 4,
                      childAspectRatio: 9 / 16,
                    ),
                    itemCount: orderedByMonth[months[index]]!.length,
                    itemBuilder: (context, gIndex) {
                      final gaIndex = orderedByMonth[months[index]]![gIndex];
                      return MemoriesItemThumbnail(
                        galleryItem: galleryItems[gaIndex],
                        onTap: () async {
                          await open(context, gaIndex);
                        },
                      );
                    },
                  );
                },
              ),
      ),
    );
  }

  Future<void> open(BuildContext context, int index) async {
    await Navigator.push(
      context,
      PageRouteBuilder(
        opaque: false,
        pageBuilder: (context, a1, a2) => MemoriesPhotoSliderView(
          galleryItems: galleryItems,
          initialIndex: index,
          scrollDirection: verticalGallery ? Axis.vertical : Axis.horizontal,
        ),
        // transitionsBuilder: (context, animation, secondaryAnimation, child) {
        //   return child;
        // },
        // transitionDuration: Duration.zero,
        // reverseTransitionDuration: Duration.zero,
      ),
    ) as bool?;
    setState(() {});
  }
}
