import 'package:flutter/material.dart';
import 'package:test_sa/extensions/context_extension.dart';
import 'package:test_sa/extensions/int_extensions.dart';
import 'package:test_sa/extensions/text_extensions.dart';
import 'package:test_sa/extensions/widget_extensions.dart';

import '../../../app_style/app_color.dart';

class RequestsTypeFilter extends StatefulWidget {
  final Function(List<int>) onSelect;
  final Map<String, int> items;
  final List<int> initialValues;

  const RequestsTypeFilter({Key? key, required this.items, required this.initialValues, required this.onSelect}) : super(key: key);

  @override
  State<RequestsTypeFilter> createState() => _RequestsTypeFilterState();
}

class _RequestsTypeFilterState extends State<RequestsTypeFilter> {
  List<int> _selected = [];

  @override
  void initState() {
    _selected.addAll(widget.initialValues);
    super.initState();
  }

  @override
  void didUpdateWidget(covariant RequestsTypeFilter oldWidget) {
    if ((widget.initialValues.isEmpty ?? true) || widget.initialValues != oldWidget.initialValues) {
      setState(() {
        _selected = widget.initialValues ?? [];
      });
    }
    super.didUpdateWidget(oldWidget);
  }

  @override
  Widget build(BuildContext context) {
    return Wrap(
      spacing: 8.toScreenWidth,
      runSpacing: 8.toScreenHeight,
      children: widget.items.keys
          .map(
            (data) => Container(
              padding: EdgeInsets.symmetric(vertical: 8.toScreenHeight, horizontal: 12.toScreenWidth),
              decoration: ShapeDecoration(
                color: AppColor.background(context),
                shape: RoundedRectangleBorder(
                  side: BorderSide(width: 1, color: _selected.contains(widget.items[data]) ? AppColor.primary10 : AppColor.border2Color(context)),
                  borderRadius: BorderRadius.circular(6),
                ),
                shadows: [BoxShadow(color: Colors.black.withOpacity(0.05), blurRadius: 14, offset: const Offset(0, 0), spreadRadius: 0)],
              ),
              child: data.tinyFont(context).custom(color: _selected.contains(widget.items[data]) ? AppColor.primary10 : AppColor.filterButtonTextColor(context)),
            ).onPress(
              () {
                if (_selected.contains(widget.items[data])) {
                  _selected.remove(widget.items[data]);
                } else {
                  _selected.add(widget.items[data]!);
                }
                setState(() {
                  widget.onSelect(_selected);
                });
              },
            ),
          )
          .toList(),
    );
  }
}
