import 'package:feet/api/api.dart';
import 'package:flutter/material.dart';

class FilterMenu extends StatefulWidget {
  final FeverAPI api;
  final List<int> initData;
  final void Function(List<int> items) onConfirm;
  const FilterMenu({
    super.key,
    required this.api,
    required this.initData,
    required this.onConfirm,
  });

  @override
  State<FilterMenu> createState() => _FilterMenuState();
}

class _FilterMenuState extends State<FilterMenu> {
  final Map<int, bool> _checked = {};

  @override
  void initState() {
    super.initState();
    for (var feed in widget.api.cache.feeds.getAll().values) {
      _checked[feed.id] = widget.initData.contains(feed.id);
    }
  }

  @override
  Widget build(BuildContext context) {
    int selected = _checked.values.where((e) => e == true).length;

    return SimpleDialog(
      title: const Text("Filter"),
      children: [
        Container(
          padding: const EdgeInsets.symmetric(horizontal: 24.0, vertical: 4.0),
          child: Text(
            selected == 0
                ? "All feeds will be shown"
                : "$selected out of ${_checked.length} feeds will be shown",
          ),
        ),
        Container(
          width: 300,
          height: 280,
          padding: const EdgeInsets.all(8.0),
          child: ListView(
            children: widget.api.cache.feeds
                .getAll()
                .values
                .map((feed) => Row(
                      children: [
                        Checkbox(
                          value: _checked[feed.id] ?? false,
                          onChanged: (value) {
                            setState(() {
                              _checked[feed.id] = value ?? true;
                            });
                          },
                        ),
                        Text(feed.title),
                      ],
                    ))
                .toList(),
          ),
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            TextButton(
              onPressed: () {
                setState(() {
                  _checked.forEach((key, value) {
                    _checked[key] = false;
                  });
                });
              },
              child: const Text("Reset")
            ),
            TextButton(
              onPressed: () {
                List<int> items = _checked.keys
                    .where((element) => _checked[element]!)
                    .toList();

                widget.onConfirm(items);
                Navigator.of(context).pop();
              },
              child: const Text("Done"),
            ),
          ],
        )
      ],
    );
  }
}
