import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import '../../../../../core/constants/color_constants.dart';
import '../../../core/constants/url_services_constant.dart';
import '../../../data/dropdown_models/personal_getdata_api.dart';
import '../../auth/login/cubit/login_cubit.dart';
import '../cubit/message_cubit.dart';

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

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

class _GroupUserMultiSelectState extends State<GroupUserMultiSelect> {
  final List<String> _mSelectedGroupUserItemsValues = [];

  void _itemChange(String itemValue, bool isSelected, String itemText) {
    setState(() {
      if (isSelected) {
        if (_mSelectedGroupUserItemsValues.contains(itemValue)) return;
        _mSelectedGroupUserItemsValues.add(itemValue);

        if (!context
            .read<MessageCubit>()
            .secilenGrupKullanicilariIdler
            .contains(itemValue)) {
          context
              .read<MessageCubit>()
              .secilenGrupKullanicilariIdler
              .add(itemValue);
          context
              .read<MessageCubit>()
              .secilenGrupKullanicilariAdlar
              .add(itemText);
        }
        _mSelectedGroupUserItemsValues.add(itemText);
      } else {
        _mSelectedGroupUserItemsValues.remove(itemValue);
        if (context
            .read<MessageCubit>()
            .secilenGrupKullanicilariIdler
            .contains(itemValue)) {
          context
              .read<MessageCubit>()
              .secilenGrupKullanicilariIdler
              .remove(itemValue);
          context
              .read<MessageCubit>()
              .secilenGrupKullanicilariAdlar
              .remove(itemText);
        }

        _mSelectedGroupUserItemsValues.remove(itemText);
      }
    });
  }

  @override
  void initState() {
    ddCek();
    _loadSelectedValues();
    super.initState();
  }

  Future<void> ddCek() async {
    userfirmCalisanData(context.read<LoginCubit>().userfirmId,
        context.read<LoginCubit>().token, context.read<LoginCubit>().id);
  }

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

  void _loadSelectedValues() {
    // Eğer daha önce seçilen değerler varsa _selectedLeadersValues listesine ekleyin
    final List<String> selectedValues =
        context.read<MessageCubit>().secilenGrupKullanicilariIdler;

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

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

  final String baseURL = URLAPIService.baseURL;

  Map<String, dynamic>? dataPersonel;

  List<PersonelDDModel> calisanListesi = [];
  Future<void> userfirmCalisanData(
      String userfirmid, String token, String loginuserid) async {
    var calisanURL = "$baseURL/mobil/api/dd/firmaya_gore_personel_dd_pdo.php";
    var veri = {
      "user_userfirm_id": userfirmid,
      "token": token,
      "loginuserid": loginuserid
    };
    var response = await Dio().post(calisanURL, data: FormData.fromMap(veri));

    if (response.statusCode == 200) {
      setState(() {
        dataPersonel = json.decode(response.data.toString());
      });
      calisanListesi = List<PersonelDDModel>.from(
        dataPersonel?["users"].map(
          (i) {
            return PersonelDDModel.fromJSON(i);
          },
        ),
      );
    } else {}
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: const Text(
        'Grup Kullanıcılarını Seç',
        style: TextStyle(),
      ),
      content: SingleChildScrollView(
        child: ListBody(
          children: calisanListesi
              .map((entry) => CheckboxListTile(
                    value: _mSelectedGroupUserItemsValues.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}');
                    },
                  ))
              .toList(),
        ),
      ),
      actions: [
        TextButton(
          onPressed: _cancel,
          style: ElevatedButton.styleFrom(
              backgroundColor: ColorsConstants.instance.baseTheme),
          child: const Text(
            'İptal',
            style: TextStyle(color: Colors.white),
          ),
        ),
        ElevatedButton(
          onPressed: _submit,
          style: ElevatedButton.styleFrom(
              backgroundColor: ColorsConstants.instance.baseTheme),
          child: const Text('Onayla', style: TextStyle(color: Colors.white)),
        ),
      ],
    );
  }
}
