import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hamlemuhcrm/core/extensions/log_extension.dart';
import 'package:hamlemuhcrm/core/extensions/responsive_extension.dart';
import 'package:hamlemuhcrm/core/extensions/string_extension.dart';
import 'package:hamlemuhcrm/features/projects/view/missions_partial/project_add_task.dart';
import 'package:flutter_cupertino_datetime_picker/flutter_cupertino_datetime_picker.dart';
import 'package:intl/intl.dart';
import '../../../../core/constants/app_constants.dart';
import '../../../../core/constants/color_constants.dart';
import '../../../../core/constants/url_services_constant.dart';
import '../../../../core/utility/toast_manager.dart';
import '../../../../data/dropdown_models/personal_getdata_api.dart';
import '../../../auth/login/cubit/login_cubit.dart';
import '../../cubit/missions_cubit.dart';
import 'model/task_add_model.dart';

mixin ProjectAddTaskMixin on State<ProjectAddTaskPage> {
  @override
  void initState() {
    fetchAutoCompleteData(context.read<LoginCubit>().token,
        context.read<LoginCubit>().id, context.read<LoginCubit>().userfirmId);
    super.initState();
  }

  bool isFinish = false;
  late List<CalisanYetkiliDDModel> autoCompleteData;
  Map<String, dynamic>? gelenCalisanlar;
  List<CalisanYetkiliDDModel> calisanListesi = [];
  void _changeLoading() {
    setState(() {
      isFinish = !isFinish;
    });
  }

  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);
            },
          ),
        );
      });
    }
  }

  final cursorColor = Colors.grey.shade200;

  final String addEmployeeTagTxt = 'Eklemek istediğiniz ismi girin..';

  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();
    });
  }

  late TextEditingController searchEmployeeController;
  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;
  }

  final tfEkGorevAd = TextEditingController();
  final tfAciklama = TextEditingController();

  ///////////////////////////////////////////////////////////////////////////////

  String dbSaatbaslangic = '';
  String dbSaatbitis = '';
  String gosterilenSaatbaslangic = '';
  String gosterilenSaatbitis = '';

  DateTime birincidateTime = DateTime.now();
  DateTime ikincidateTime = DateTime.now();

  bool baslangicSecildi = false;
  bool tarihUygun = false;

  //////////////////////////////////////////////////////////////////////////////

  dateTimePickerWidget1(BuildContext context) {
    return DatePicker.showDatePicker(
      context,
      dateFormat: 'dd/MM/yyyy',
      locale: DateTimePickerLocale.tr,
      initialDateTime: DateTime.now(),
      minDateTime: DateTime(2005),
      maxDateTime: DateTime(2100),
      pickerTheme: DateTimePickerTheme(
        backgroundColor: ColorsConstants.instance.backgroundColor,
        confirm: Text(
          'Onay',
          style: TextStyle(
              color: ColorsConstants.instance.baseTheme.withOpacity(0.7)),
        ),
      ),
      onConfirm: (dateTime, List<int> index) {
        DateTime selectdate1 = dateTime;
        birincidateTime = selectdate1;
        final baslangicTarihi =
            DateFormat('yyyy-MM-dd HH:mm').format(selectdate1);
        setState(() {
          dbSaatbaslangic = '$baslangicTarihi:00';
          gosterilenSaatbaslangic = dbSaatbaslangic.substring(0, 16);
          final DateFormat format = DateFormat.yMd('tr');
          var trTarih = format.format(DateTime.parse(gosterilenSaatbaslangic));
          gosterilenSaatbaslangic = trTarih;

          if (dbSaatbaslangic != '' && dbSaatbitis != '') {}
          baslangicSecildi = true;
        });
      },
    );
  }

  dateTimePickerWidget2(BuildContext context) {
    return DatePicker.showDatePicker(
      context,
      dateFormat: 'dd/MM/yyyy',
      locale: DateTimePickerLocale.tr,
      minDateTime: DateTime(2005),
      maxDateTime: DateTime(2100),
      pickerTheme: DateTimePickerTheme(
        backgroundColor: ColorsConstants.instance.backgroundColor,
        confirm: Text(
          'Onay',
          style: TextStyle(
              color: ColorsConstants.instance.baseTheme.withOpacity(0.7)),
        ),
      ),
      onConfirm: (dateTime, List<int> index) {
        DateTime selectdate2 = dateTime;
        ikincidateTime = selectdate2;
        final bitisTarihi = DateFormat('yyyy-MM-dd HH:mm').format(selectdate2);
        setState(() {
          dbSaatbitis = '$bitisTarihi:00';
          gosterilenSaatbitis = dbSaatbitis.substring(0, 16);
          final DateFormat format = DateFormat.yMd('tr');
          var trTarih = format.format(DateTime.parse(gosterilenSaatbitis));
          gosterilenSaatbitis = trTarih;
          'ikinci tarih birinci tarihten sonra mı ? ${ikincidateTime.isAfter(birincidateTime)}'
              .log();
          if (ikincidateTime.isAfter(birincidateTime) == false) {
            gosterilenSaatbitis = '';
            ToastManager.instance
                .toastMessageService("Geçerli bir tarih seçin..");
          }
          if (dbSaatbaslangic != '' && dbSaatbitis != '') {
            //Saatler boş geçilmedi ise gerekli metot yazılsın
            debugPrint(dbSaatbaslangic);
            debugPrint(dbSaatbitis);
          }
        });
      },
    );
  }

  Widget get tagEmployee => 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(
              shrinkWrap: true,
              itemCount: options.length,
              itemBuilder: (context, index) {
                final List<CalisanYetkiliDDModel> optionsList =
                    options.toList();
                final CalisanYetkiliDDModel option = optionsList[index];
                return ListTile(
                  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: InputDecoration(
              filled: true,
              fillColor: ColorsConstants.instance.appWhite,
              enabledBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(8),
                  borderSide: BorderSide(color: Colors.grey.shade400)),
              focusedBorder: OutlineInputBorder(
                borderRadius: BorderRadius.circular(8),
                borderSide: BorderSide(
                    color: ColorsConstants.instance.baseTheme.withOpacity(.5)),
              ),
              contentPadding: const EdgeInsets.symmetric(horizontal: 5),
              hintText: addEmployeeTagTxt,
              prefixIcon: Icon(
                Icons.tag,
                color: ColorsConstants.instance.baseTheme,
              ),
            ),
          );
        },
      );

  Widget get selectedEmployeeChips => SizedBox(
        height: context.dynamicHeight(0.04),
        child: ListView.builder(
            scrollDirection: Axis.horizontal,
            shrinkWrap: true,
            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}'))
                  ],
                ),
              );
            }),
      );

  void _showSnackbarMessage(BuildContext context, String msg) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(msg),
        behavior: SnackBarBehavior.floating,
        backgroundColor: ColorsConstants.instance.baseTheme,
      ),
    );
  }

  Widget get addTaskButton => Row(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          TextButton(
            onPressed: () {
              if (tfEkGorevAd.text.isNotEmpty &&
                  tfAciklama.text.isNotEmpty &&
                  dbSaatbaslangic.isNotEmpty &&
                  dbSaatbitis.isNotEmpty) {
                String cevrilmisCalisanlar = '';
                List<int> etiketlenenGorevliler = [];
                for (var k in selectedEmployee) {
                  // etiketlenenleri listeye aktarıyoruz.
                  etiketlenenGorevliler.add(int.tryParse(k.id)!);
                  cevrilmisCalisanlar +=
                      ''.rawComment(k.id, '${k.firstName} ${k.lastName}');
                }
                String allComment =
                    '<p> ${tfAciklama.text}&nbsp;$cevrilmisCalisanlar</p>';
                debugPrint(allComment);
                String ekGorevliler = etiketlenenGorevliler.join(',');
                context
                    .read<MissionsCubit>()
                    .ekGorevEkle(AddTaskModel(
                        loginuserID: context.read<LoginCubit>().id,
                        token: context.read<LoginCubit>().token,
                        gorevUserFirmId: context.read<LoginCubit>().userfirmId,
                        ekgorevliler: ekGorevliler,
                        gorevliler: widget.gorevliler,
                        bagliGorevId: widget.anaGorevId,
                        bagliProjeId: widget.gorevProjeId,
                        ekGorevAd: tfEkGorevAd.text,
                        ekGorevAciklama: allComment,
                        dbSaatbaslangic: dbSaatbaslangic,
                        dbSaatbitis: dbSaatbitis))
                    .whenComplete(() {
                  _showSnackbarMessage(context, 'Ek Görev Eklendi');
                  Future.delayed(const Duration(milliseconds: 1500), () {
                    Navigator.popUntil(context, (route) => route.isFirst);
                  });
                });
              } else {
                ToastManager.instance
                    .toastMessageService("Eksik alanları doldurun");
              }
            },
            style: TextButton.styleFrom(
              backgroundColor: ColorsConstants.instance.baseTheme,
            ),
            child: Text(
              ApplicationConstants.instance.moduleSaveTxt,
              style: const TextStyle(color: Colors.white),
            ),
          ),
        ],
      );
}
