import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../../core/cubits/dropdown_cubit.dart';
import '../../../core/utility/toast_manager.dart';
import '../../auth/login/cubit/login_cubit.dart';
import '../../customers/cubit/customers_cubit.dart';
import '../cubit/calendar_cubit.dart';
import '../model/new_meet_model.dart';
import '../widgets/multi_select_company_employee_dropdown.dart';
import '../widgets/multi_select_personal_dropdown.dart';
import '../view/add_meet_second_view.dart';

mixin AddMeetSecondViewMixin on State<AddMeetSecondView> {
  @override
  void initState() {
    changeLoading();
    context.read<DropdownCubit>().fetchYetkiliData(widget.projeFirmaId,
        context.read<LoginCubit>().token, context.read<LoginCubit>().id);
    changeLoading();
    super.initState();
  }

  void changeLoading() {
    setState(() {
      isLoading = !isLoading;
    });
  }

  @override
  void dispose() {
    super.dispose();
    context.read<CalendarCubit>().selectedItemsMultiSelectReset();
    context.read<DropdownCubit>().secilenCalisanListeTemizle();
    context.read<DropdownCubit>().secilenYetkiliListeTemizle();
  }

  bool isLoading = true;

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

  List<String> secilenFirmaYetkiliList = [];
  String gonderilecekFirmaYetkiliIdler = '';

  void showMultiSelectCompanyEmployee() async {
    final List<String> items = [];

    final List<String>? results = await showDialog(
      context: context,
      builder: (BuildContext context) {
        return MultiSelectCompanyEmployeeDropdown(items: items);
      },
    );

    if (results != null) {
      setState(() {
        secilenFirmaYetkiliList = results;
        // seçili gelen listenin id değerlerini virgüllerle veritabanı formatına uygun alıyoruz.
        List<int> yetkiliIdler = secilenFirmaYetkiliList
            .where((eleman) => int.tryParse(eleman) != null)
            .map((eleman) => int.parse(eleman))
            .toList();
        gonderilecekFirmaYetkiliIdler = yetkiliIdler.join(',');
      });
    }
  }

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

  List<String> secilenPersonelList = [];
  String gonderilecekPersonelIdler = '';

  void showMultiSelectPersonal() async {
    final List<String> items2 = [];

    final List<String>? results2 = await showDialog(
      context: context,
      builder: (BuildContext context) {
        return MultiSelectPersonalDropdown(items: items2);
      },
    );

    if (results2 != null) {
      setState(() {
        secilenPersonelList = results2;
        // seçili gelen listenin id değerlerini virgüllerle veritabanı formatına uygun alıyoruz.
        List<int> personelIdler = secilenPersonelList
            .where((eleman) => int.tryParse(eleman) != null)
            .map((eleman) => int.parse(eleman))
            .toList();
        gonderilecekPersonelIdler = personelIdler.join(',');
      });
    }
  }

  void mixinAddMeetMethod() {
    if (widget.tfBaslik.isNotEmpty &&
        widget.tfGundem.isNotEmpty &&
        widget.tfToplantiYeri.isNotEmpty &&
        widget.tfToplantiAciklama.isNotEmpty &&
        widget.toplantiYoneticiId.isNotEmpty &&
        widget.alinanTarih.isNotEmpty &&
        widget.projeid.isNotEmpty &&
        widget.projeFirmaId.isNotEmpty &&
        gonderilecekFirmaYetkiliIdler.isNotEmpty &&
        gonderilecekPersonelIdler.isNotEmpty) {
      String employeesID = ',$gonderilecekPersonelIdler,'.replaceAll(
          RegExp(',+'),
          ','); //fazladan art arda virgül var ise fazla virgülleri kaldırıyor..
      String leadersID =
          ',$gonderilecekFirmaYetkiliIdler,'.replaceAll(RegExp(',+'), ',');
      context
          .read<CalendarCubit>()
          .addMeets(NewMeetModel(
              loginuserID: context.read<LoginCubit>().id,
              token: context.read<LoginCubit>().token,
              toplantiUserFirmID: context.read<LoginCubit>().userfirmId,
              toplantiProjeId: widget.projeid,
              toplantiYoneticiId: widget.toplantiYoneticiId,
              toplantiFirmaID: widget.projeFirmaId,
              toplantiYetkiliIdler: leadersID,
              toplantiUserIdler: employeesID,
              toplantiBaslik: widget.tfBaslik,
              toplantiGundem: widget.tfGundem,
              toplantiNot: widget.tfToplantiAciklama,
              toplantiTip: context.read<CustomersCubit>().secilenGorusmeTipi,
              toplantiTarihi: widget.alinanTarih,
              toplantiSure: widget.alinanSure,
              toplantiYeri: widget.tfToplantiYeri,
              toplantiTekrar:
                  context.read<CalendarCubit>().secilenToplantiTekrarTipi))
          .whenComplete(() async {
        context.read<DropdownCubit>().resetDropdown();
        ToastManager.instance.toastMessageService('Toplantı Eklendi');
        await Future.delayed(const Duration(milliseconds: 1600), () {
          backToPage();
        });
      });
    } else {
      ToastManager.instance.toastMessageService('Eksik Alanlar Var !');
    }
  }

  void backToPage() {
    Navigator.popUntil(context, (route) => route.isFirst);
  }
}
