import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hamlemuhcrm/data/dropdown_models/personal_getdata_api.dart';

import '../../../../../core/constants/color_constants.dart';
import '../../../core/cubits/dropdown_cubit.dart';

class MultiSelectPersonalDropdown extends StatefulWidget {
  final List<String> items;
  const MultiSelectPersonalDropdown({Key? key, required this.items})
      : super(key: key);

  @override
  State<StatefulWidget> createState() => _MultiSelectPersonalDropdownState();
}

class _MultiSelectPersonalDropdownState
    extends State<MultiSelectPersonalDropdown> {
  final String dialogTxt = 'Katılan Personelleri Seç';
  final String confirmTxt = 'Onayla';
  final String cancelTxt = 'İptal';
  List<String> mSelectedPersonalItemsValues = [];

  void _itemChange(String itemValue, bool isSelected, String itemText,
      CalisanYetkiliDDModel model) {
    setState(() {
      if (isSelected) {
        mSelectedPersonalItemsValues.add(itemValue);
        mSelectedPersonalItemsValues.add(itemText);
        debugPrint(
            'eklenen calisan : ${model.id} ${model.firstName} ${model.lastName}');
        context.read<DropdownCubit>().calisanEkle(CalisanYetkiliDDModel(
            id: model.id,
            firstName: model.firstName,
            lastName: model.lastName,
            image: model.image));
      } else {
        mSelectedPersonalItemsValues.remove(itemValue);
        mSelectedPersonalItemsValues.remove(itemText);
        debugPrint(
            'silinen calisan : ${model.id} ${model.firstName} ${model.lastName}');
        context.read<DropdownCubit>().calisanCikart(CalisanYetkiliDDModel(
            id: model.id,
            firstName: model.firstName,
            lastName: model.lastName,
            image: model.image));
      }
    });
  }

  void _cancel() {
    Navigator.pop(context);
  }

  void _submit() async {
    Navigator.pop(context, mSelectedPersonalItemsValues);
  }

  void _loadSelectedValues() {
    List<String> selectedValues = [];

    for (var k in context.read<DropdownCubit>().state.secilenCalisanlar) {
      selectedValues.add(k.id);
    }

    if (selectedValues.isNotEmpty) {
      mSelectedPersonalItemsValues.addAll(selectedValues);
    }
  }

  @override
  void initState() {
    _loadSelectedValues();
    debugPrint("multi_select_personal_dropdown initState çalıştı");
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<DropdownCubit, DropdownState>(
      builder: (context, state) {
        return AlertDialog(
          title: Text(
            dialogTxt,
          ),
          content: SingleChildScrollView(
            child: ListBody(
              children: state.calisanlar
                  .map((entry) => CheckboxListTile(
                        value: mSelectedPersonalItemsValues.contains(entry.id),
                        title: Text('${entry.firstName} ${entry.lastName}'),
                        controlAffinity: ListTileControlAffinity.trailing,
                        activeColor: ColorsConstants.instance.baseTheme,
                        onChanged: (isChecked) {
                          _itemChange(
                            entry.id,
                            isChecked!,
                            '${entry.firstName} ${entry.lastName}',
                            CalisanYetkiliDDModel(
                                id: entry.id,
                                firstName: entry.firstName,
                                lastName: entry.lastName,
                                image: entry.image),
                          );
                        },
                      ))
                  .toList(),
            ),
          ),
          actions: [
            TextButton(
              onPressed: _cancel,
              style: ElevatedButton.styleFrom(
                  backgroundColor: ColorsConstants.instance.baseTheme),
              child: Text(
                cancelTxt,
                style: const TextStyle(color: Colors.white),
              ),
            ),
            ElevatedButton(
              onPressed: _submit,
              style: ElevatedButton.styleFrom(
                  backgroundColor: ColorsConstants.instance.baseTheme),
              child: Text(
                confirmTxt,
                style: const TextStyle(color: Colors.white),
              ),
            ),
          ],
        );
      },
    );
  }
}
