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/color_constants.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/mission_employee_notes_cubit.dart';
import 'package:hamlemuhcrm/features/projects/model/mission_employee_note_add_model.dart';
import 'package:hamlemuhcrm/features/projects/view/missions_partial/utility/custom_auto_complete_decoration.dart';

import '../../../../../core/utility/toast_manager.dart';

class CustomAutoComplete extends StatefulWidget {
  final String isGorevId;

  const CustomAutoComplete({super.key, required this.isGorevId});

  @override
  State<CustomAutoComplete> createState() => _CustomAutoCompleteState();
}

class _CustomAutoCompleteState extends State<CustomAutoComplete>
    with _AutoCancel {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ColorsConstants.instance.appWhite,
      body: Form(
        key: tagKey,
        child: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Column(
            children: [
              _addNote,
              _autoComplete,
              _searchEmployee,
              BlocBuilder<MissionEmployeeCubit, MissionEmployeeState>(
                builder: (context, state) {
                  return ElevatedButton(
                      onPressed: state.isLoading
                          ? null
                          : () {
                              if (addNoteController.text.isNotEmpty) {
                                String cevrilmisCalisanlar = '';
                                List<int> etiketlenenGorevliler = [];
                                for (var k in selectedEmployee) {
                                  etiketlenenGorevliler
                                      .add(int.tryParse(k.id)!);
                                  cevrilmisCalisanlar += rawComment(
                                      k.id, '${k.firstName} ${k.lastName}');
                                }
                                String sonuc =
                                    '<p> ${addNoteController.text}&nbsp;$cevrilmisCalisanlar</p>';

                                // Birden fazla kişi etiketlenebilir.
                                String etiketlenenIdler =
                                    etiketlenenGorevliler.join(',');
                                context
                                    .read<MissionEmployeeCubit>()
                                    .addNewMissionNote(MissionAddNoteModel(
                                        token: context.read<LoginCubit>().token,
                                        loginuserid:
                                            context.read<LoginCubit>().id,
                                        isUserFirmId: context
                                            .read<LoginCubit>()
                                            .userfirmId,
                                        isUserId: context.read<LoginCubit>().id,
                                        isGorevId: widget.isGorevId,
                                        etiketlenenler: etiketlenenIdler,
                                        isCalisma: sonuc));
                              } else {
                                ToastManager.instance.toastMessageService(
                                    'Boş Not Kaydı Ekleyemezsiniz !');
                              }
                            },
                      style: ElevatedButton.styleFrom(
                        backgroundColor: ColorsConstants.instance.baseTheme,
                      ),
                      child: Text(
                        addNoteButtonTxt,
                        style: const TextStyle(color: Colors.white),
                      ));
                },
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget get _addNote => Expanded(
      child: TextField(
          cursorColor: cursorColor,
          controller: addNoteController,
          decoration: CustomAutoCompleteInputDecoration(
              addNoteTxt, Icons.note_add_rounded)));

  Widget get _autoComplete => Autocomplete<CalisanYetkiliDDModel>(
        optionsBuilder: (TextEditingValue textEditingValue) {
          if (textEditingValue.text.isEmpty) {
            return const Iterable<CalisanYetkiliDDModel>.empty();
          } else {
            return autoCompleteData.where((word) =>
                word.firstName
                    .toLowerCase()
                    .contains(textEditingValue.text.toLowerCase()) ||
                word.lastName
                    .toLowerCase()
                    .contains(textEditingValue.text.toLowerCase()));
          }
        },
        optionsViewBuilder:
            (context, Function(CalisanYetkiliDDModel) onSelected, options) {
          return Material(
            color: ColorsConstants.instance.backgroundColor,
            child: ListView.builder(
              itemCount: options.length,
              itemBuilder: (context, index) {
                final List<CalisanYetkiliDDModel> optionsList =
                    options.toList();
                final CalisanYetkiliDDModel option = optionsList[index];
                return ListTile(
                  dense: true,
                  contentPadding: EdgeInsets.zero,
                  title: Text("${option.firstName} ${option.lastName}"),
                  onTap: () {
                    secilenCalisanMetodu(option);
                  },
                );
              },
            ),
          );
        },
        onSelected: (option) {
          setState(() {
            searchEmployeeController.clear();
          });
        },
        fieldViewBuilder: (context, controller, focusNode, onEditingComplete) {
          searchEmployeeController = controller;
          return TextField(
              cursorColor: cursorColor,
              controller: controller,
              focusNode: focusNode,
              onEditingComplete: () async {
                setState(() {
                  focusNode.unfocus();
                });
              },
              decoration: CustomAutoCompleteInputDecoration(
                  addEmployeeTagTxt, Icons.tag));
        },
      );

  Widget get _searchEmployee => Expanded(
      flex: 2,
      child: ListView.builder(
          scrollDirection: Axis.horizontal,
          itemCount: selectedEmployee.length,
          itemBuilder: (context, index) {
            var employee = selectedEmployee[index];
            return Padding(
              padding: const EdgeInsets.only(right: 15),
              child: Row(
                children: [
                  IconButton(
                      onPressed: () {
                        setState(() {
                          if (selectedEmployee
                              .any((element) => element.id == employee.id)) {
                            selectedEmployee.removeWhere(
                                (element) => element.id == employee.id);
                          }
                        });
                      },
                      icon: Icon(
                        Icons.remove_circle,
                        size: 18,
                        color: ColorsConstants.instance.appRed,
                      )),
                  Chip(
                      label: Text('${employee.firstName} ${employee.lastName}'))
                ],
              ),
            );
          }));
}

mixin _AutoCancel on State<CustomAutoComplete> {
  List<CalisanYetkiliDDModel> calisanListesi = [];

  bool isFinish = false;

  //late MissionEmployeeCubit cubit;
  final tagKey = GlobalKey<FormState>();
  final cursorColor = Colors.grey.shade200;
  final String addNoteTxt = 'Not Ekle';
  final String addEmployeeTagTxt = 'Çalışan Etiketle';
  final String addNoteButtonTxt = 'Notu Kaydet';

  @override
  void initState() {
    //cubit = MissionEmployeeCubit();
    fetchAutoCompleteData(context.read<LoginCubit>().token,
        context.read<LoginCubit>().id, context.read<LoginCubit>().userfirmId);
    super.initState();
  }

  void _changeLoading() {
    setState(() {
      isFinish = !isFinish;
    });
  }

  void secilenCalisanMetodu(CalisanYetkiliDDModel option) {
    setState(() {
      if (selectedEmployee.any((element) => element.id == option.id)) {
        selectedEmployee.removeWhere((element) => element.id == option.id);
        searchEmployeeController.clear();
        return;
      }
      selectedEmployee.add(option);
      searchEmployeeController.clear();
    });
  }

  // void seciliOlanListeyiDondur() {
  //   //mevcut seçili olan isimlerin listesini ana sayfaya gönderdik call back metodu sayesinde
  //   widget.onPressed?.call(selectedEmployee);
  // }

  late List<CalisanYetkiliDDModel> autoCompleteData;
  late TextEditingController searchEmployeeController;
  TextEditingController addNoteController = TextEditingController();

  Future fetchAutoCompleteData(
      String token, String loginuserid, String userfirmId) async {
    _changeLoading();
    var calisanURL =
        "${URLAPIService.baseURL}/mobil/api/dd/firmaya_gore_personel_dd_pdo.php";
    var veri = {
      "token": token,
      "loginuserid": loginuserid,
      "user_userfirm_id": userfirmId
    };
    var calisanCevap =
        await Dio().post(calisanURL, data: FormData.fromMap(veri));
    if (calisanCevap.statusCode == 200) {
      setState(() {
        isFinish = false;
        gelenCalisanlar = json.decode(calisanCevap.data);
        autoCompleteData = List<CalisanYetkiliDDModel>.from(
          gelenCalisanlar?["users"].map(
            (i) {
              return CalisanYetkiliDDModel.fromJSON(i);
            },
          ),
        );
      });
    }
  }

  String rawComment(String id, String ad) =>
      '<a href="$id" onclick="worktaskuser($id); return false;" style="font-weight:bold;"> @$ad </a>&nbsp;&nbsp;';

  Map<String, dynamic>? gelenCalisanlar;

  List<CalisanYetkiliDDModel> selectedEmployee = [];

  Future<List<CalisanYetkiliDDModel>> search(String key) async {
    var liste = <CalisanYetkiliDDModel>[];
    if (calisanListesi.isNotEmpty) {
      for (var element in calisanListesi) {
        if (element.firstName.toLowerCase().contains(key.toLowerCase()) ||
            element.lastName.toLowerCase().contains(key.toLowerCase())) {
          liste.add(element);
        }
      }
    }
    return liste;
  }
}
