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 MultiSelectEmployee extends StatefulWidget {
  final List<String> items;
  const MultiSelectEmployee({Key? key, required this.items}) : super(key: key);

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

class _MultiSelectEmployeeState extends State<MultiSelectEmployee> {
  final List<String> _mSelectedEmployeeItemsValues = [];

  void itemChange(String itemValue, bool isSelected, String itemText) {
    if (isSelected != false) {
      if (!_mSelectedEmployeeItemsValues.contains(itemValue)) {
        _mSelectedEmployeeItemsValues.add(itemValue);
        context.read<ProjectCubit>().secilenPersonelIdler.add(itemValue);
        _mSelectedEmployeeItemsValues.add(itemText);
        context.read<ProjectCubit>().secilenPersonelAdlar.add(itemText);
      }
    } else {
      if (_mSelectedEmployeeItemsValues.contains(itemValue)) {
        _mSelectedEmployeeItemsValues.remove(itemValue);
        context.read<ProjectCubit>().secilenPersonelIdler.remove(itemValue);
        _mSelectedEmployeeItemsValues.remove(itemText);
        context
            .read<ProjectCubit>()
            .secilenPersonelAdlar
            .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 _cancel() {
    Navigator.pop(context);
  }

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

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

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

  Map<String, dynamic>? dataPersonel;

  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(() {
        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(
        'Görevlileri Seç',
        style: TextStyle(),
      ),
      content: SingleChildScrollView(
        child: ListBody(
          children: calisanListesi
              .map((entry) => CheckboxListTile(
                    value: _mSelectedEmployeeItemsValues.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)),
        ),
      ],
    );
  }
}
