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/data/dropdown_models/personal_getdata_api.dart';
import 'package:hamlemuhcrm/features/auth/login/cubit/login_cubit.dart';
import 'package:hamlemuhcrm/features/projects/cubit/project_cubit.dart';

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

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

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

class _MultiSelectLeadersState extends State<MultiSelectLeaders> {
  final List<String> _mSelectedLeadersValues = [];

  void itemChange(String itemValue, bool isSelected, String itemText) {
    if (isSelected != false) {
      if (!_mSelectedLeadersValues.contains(itemValue)) {
        _mSelectedLeadersValues.add(itemValue);
        context.read<ProjectCubit>().secilenAmirIdler.add(itemValue);
        _mSelectedLeadersValues.add(itemText);
        context.read<ProjectCubit>().secilenAmirAdlar.add(itemText);
      }
    } else {
      if (_mSelectedLeadersValues.contains(itemValue)) {
        _mSelectedLeadersValues.remove(itemValue);
        context.read<ProjectCubit>().secilenAmirIdler.remove(itemValue);
        _mSelectedLeadersValues.remove(itemText);
        context
            .read<ProjectCubit>()
            .secilenAmirAdlar
            .removeWhere((element) => element.contains(itemText));
      }
    }
    setState(() {});
  }

  @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 _loadSelectedValues() {
    // Eğer daha önce seçilen değerler varsa _selectedLeadersValues listesine ekleyin
    final List<String> selectedValues =
        context.read<ProjectCubit>().secilenAmirIdler;

    if (selectedValues.isNotEmpty) {
      _mSelectedLeadersValues.addAll(selectedValues);
      _mSelectedLeadersValues.removeWhere((element) => element.isEmpty);
    }
  }

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

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

  Map<String, dynamic>? dataYetkili;

  List<PersonelDDModel> calisanListesi = [];

  Future<void> userfirmCalisanData(
      String userfirmid, String token, String loginuserid) async {
    var calisanURL =
        "${URLAPIService.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(() {
        dataYetkili = json.decode(response.data.toString());
      });
      calisanListesi = List<PersonelDDModel>.from(
        dataYetkili?["users"].map(
          (i) {
            return PersonelDDModel.fromJSON(i);
          },
        ),
      );
    } else {}
  }

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