// ignore_for_file: public_member_api_docs, sort_constructors_first
import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hamlemuhcrm/core/constants/url_services_constant.dart';
import 'package:hamlemuhcrm/core/extensions/log_extension.dart';
import 'package:hamlemuhcrm/data/dropdown_models/personal_getdata_api.dart';
import 'package:hamlemuhcrm/features/auth/login/cubit/login_cubit.dart';
import 'package:hamlemuhcrm/features/message/cubit/message_cubit.dart';

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

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

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

class _GroupLeaderMultiSelectState extends State<GroupLeaderMultiSelect> {
  final List<String> _mSelectedGroupLeaderItemsValues = [];

  void _itemChange(String itemValue, bool isSelected, String itemText) {
    setState(() {
      if (isSelected) {
        if (_mSelectedGroupLeaderItemsValues.contains(itemValue)) return;
        _mSelectedGroupLeaderItemsValues.add(itemValue);
        if (!context
            .read<MessageCubit>()
            .secilenGrupYoneticileriIdler
            .contains(itemValue)) {
          context
              .read<MessageCubit>()
              .secilenGrupYoneticileriIdler
              .add(itemValue);
          context
              .read<MessageCubit>()
              .secilenGrupYoneticileriAdlar
              .add(itemText);
        }
        _mSelectedGroupLeaderItemsValues.add(itemText);
      } else {
        _mSelectedGroupLeaderItemsValues.remove(itemValue);
        if (context
            .read<MessageCubit>()
            .secilenGrupYoneticileriIdler
            .contains(itemValue)) {
          context
              .read<MessageCubit>()
              .secilenGrupYoneticileriIdler
              .remove(itemValue);
          context
              .read<MessageCubit>()
              .secilenGrupYoneticileriAdlar
              .remove(itemText);
        }

        _mSelectedGroupLeaderItemsValues.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>().secilenGrupYoneticileriIdler;
    if (selectedValues.isNotEmpty) {
      _setIdFromGrupLeaderToName(selectedValues);
      _mSelectedGroupLeaderItemsValues.addAll(selectedValues);
    }
  }

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

  final String baseURL = URLAPIService.baseURL;

  Map<String, dynamic>? dataPersonel;

  List<PersonelDDModel> calisanListesi = [];

  Future<List<PersonelDDModel>> 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());
      });
      return calisanListesi = List<PersonelDDModel>.from(
        dataPersonel?["users"].map(
          (i) {
            return PersonelDDModel.fromJSON(i);
          },
        ),
      );
    }
    return [];
  }

  void _setIdFromGrupLeaderToName(List<String> leaderIds) {
    'setIdFromGrupLeaderToName metoduna girdi'.log();
    for (var item in calisanListesi) {
      for (int i = 0; i < leaderIds.length; i++) {
        'burda döndü : ${item.firstName}'.log();
        if (item.id == leaderIds[i]) {
          context
              .read<MessageCubit>()
              .secilenGrupYoneticileriAdlar
              .add('${item.firstName} ${item.lastName}');
        }
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: const Text(
        'Grup Yöneticilerini Seç',
        style: TextStyle(),
      ),
      content: SingleChildScrollView(
        child: ListBody(
          children: calisanListesi
              .map((entry) => CheckboxListTile(
                    value: _mSelectedGroupLeaderItemsValues.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)),
        ),
      ],
    );
  }
}
