import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:dropdown_button2/dropdown_button2.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_cupertino_datetime_picker/flutter_cupertino_datetime_picker.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:intl/intl.dart';
import 'package:hamlemuhcrm/core/extensions/log_extension.dart';
import 'package:hamlemuhcrm/features/projects/widgets/multiselect_widgets/selected_employee_chip.dart';
import '../../../../core/constants/app_constants.dart';
import '../../../../core/extensions/image_enum_extension.dart';
import '../../../../core/utility/toast_manager.dart';
import '../../model/projeler.dart';
import '../../../../data/dropdown_models/personal_getdata_api.dart';
import '../../../../core/constants/url_services_constant.dart';
import '../../../auth/login/cubit/login_cubit.dart';
import '../../cubit/project_cubit.dart';
import '../../../../core/constants/font_styles.dart';
import '../../../../core/extensions/responsive_extension.dart';
import '../../widgets/employee_type_headline.dart';
import '../../widgets/multiselect_widgets/multi_select_employee.dart';
import '../../widgets/multiselect_widgets/multi_select_leaders.dart';

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

class ProjectUpdatePage extends StatefulWidget {
  final Projeler projeler;

  const ProjectUpdatePage({super.key, required this.projeler});

  @override
  State<ProjectUpdatePage> createState() => _ProjectUpdatePageState();
}

class _ProjectUpdatePageState extends State<ProjectUpdatePage> {
  final tfProjeAd = 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;
  final DateFormat format = DateFormat.yMd('tr');

  List<String> _secilenPersonelList = [];
  List<String> _secilenAmirList = [];

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

  String gonderilenfirmaID = "";
  String? _secilenFirma;
  var gelenFirmalar;
  final String baseURL = URLAPIService.baseURL;

  String kayitliFirma = "0";

  Future<void> firmaData(
      String userfirmid, String token, String loginuserid) async {
    var url = "$baseURL/mobil/api/dd/userfirme_gore_firma_dd_pdo.php";
    var veri = {
      "firma_firmuser_id": userfirmid,
      "token": token,
      "loginuserid": loginuserid
    };
    var cevapFirmalar = await Dio().post(url, data: FormData.fromMap(veri));
    if (cevapFirmalar.statusCode == 200) {
      setState(() {
        gelenFirmalar = json.decode(cevapFirmalar.data.toString()); //
        "gelenFirmalar = $gelenFirmalar".log();
      });
    } else {}
  }

  Widget firmalarDD() {
    List<FirmaDDModel> firmalar =
        List<FirmaDDModel>.from(gelenFirmalar['firmalar'].map(
      (i) {
        return FirmaDDModel.fromJSON(i);
      },
    ));
    firmalar.sort(
      (a, b) => a.firmaIsim.compareTo(b.firmaIsim),
    ); // DROPDOWN SIRALAMASI
    return DropdownButtonHideUnderline(
      child: DropdownButton2(
        hint: const Text(
          'Firma Seçiniz...',
          style: TextStyle(color: Colors.black54, fontSize: 13),
        ),
        isExpanded: true,
        items: firmalar.map((firmalar) {
          return DropdownMenuItem(
            value: firmalar.firmaId,
            child: Text(
                firmalar.firmaIsim.toString().length > 35
                    ? "${firmalar.firmaIsim.toString().substring(0, 34)}.. "
                    : firmalar.firmaIsim,
                style: FontStyles.instance.projectbxDdyazi),
          );
        }).toList(),
        value: _secilenFirma,
        onChanged: (newValue) {
          setState(() {
            _secilenFirma = newValue.toString();
            _secilenFirma?.log();
            gonderilenfirmaID = _secilenFirma!;
          });
        },
        buttonStyleData: ButtonStyleData(
          height: context.dynamicHeight(0.054),
          width: context.dynamicWidth(0.9),
          padding: const EdgeInsets.symmetric(horizontal: 10),
          decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(10),
              color: Colors.white,
              border: Border.all(color: Colors.grey.withOpacity(0.7))),
          elevation: 0,
        ),
        iconStyleData: IconStyleData(
          icon: const Icon(
            Icons.keyboard_arrow_down_outlined, //ilk icon
          ),
          openMenuIcon: const Icon(
              Icons.keyboard_arrow_left_outlined), //açıldıktan sonraki icon
          iconSize: 23,
          iconEnabledColor: ColorsConstants.instance.baseTheme,
          iconDisabledColor: Colors.white,
        ),
        dropdownStyleData: DropdownStyleData(
          maxHeight: context.dynamicHeight(0.17),
          isOverButton: false,
          padding: null,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(10),
            color: ColorsConstants
                .instance.backgroundColor, //açılır menü arkaplan rengi
          ),
          elevation: 8,
          offset: const Offset(0, 0),
          scrollbarTheme: ScrollbarThemeData(
            thumbColor: MaterialStateColor.resolveWith((states) =>
                ColorsConstants
                    .instance.baseTheme), //dropdown scroll rengi değiştirme
            radius: const Radius.circular(10),
            thickness: MaterialStateProperty.all<double>(6),
            thumbVisibility: MaterialStateProperty.all<bool>(true),
          ),
        ),
        menuItemStyleData: const MenuItemStyleData(
          height: 35,
          padding: EdgeInsets.symmetric(horizontal: 14),
        ),
      ),
    );
  }

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

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

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

    if (results != null) {
      setState(() {
        _secilenPersonelList = results;
      });
    }
  }

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

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

    if (results2 != null) {
      setState(() {
        _secilenAmirList = results2;
      });
    }
  }

  String _gonderilecekPersonelIdler = '';
  String _gonderilecekAmirIdler = '';

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

  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;
          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;
          if (ikincidateTime.isAfter(birincidateTime) == false) {
            gosterilenSaatbitis = '';
            ToastManager.instance
                .toastMessageService("Geçerli bir tarih seçin..");
          }
        });
      },
    );
  }

  @override
  void initState() {
    isFinish = false;
    debugPrint('sayfa proje id : ${widget.projeler.projeId}');
    _degerleriAta();
    firmaData(context.read<LoginCubit>().userfirmId,
            context.read<LoginCubit>().token, context.read<LoginCubit>().id)
        .whenComplete(() {
      if (widget.projeler.projeFirmaId != '' &&
          widget.projeler.projeFirmaId != null) {
        _secilenFirma = widget.projeler.projeFirmaId;
      }
      isFinish = true;
    });
    super.initState();
  }

  void _degerleriAta() {
    tfProjeAd.text = widget.projeler.projeAd!;
    dbSaatbaslangic = widget.projeler.projeBaslangicTarihi!;
    String trTarihBaslangic = format.format(DateTime.parse(dbSaatbaslangic));
    gosterilenSaatbaslangic = trTarihBaslangic;
    dbSaatbitis = widget.projeler.projeBitisTarihi!;
    String trTarihBitis = format.format(DateTime.parse(dbSaatbitis));
    gosterilenSaatbitis = trTarihBitis;
    tfAciklama.text = widget.projeler.projeAciklama!;
    seciliSorumlulariEkle();
    seciliGorevlileriEkle();
    kayitliFirma = context.read<LoginCubit>().userfirmId;
  }

  @override
  void deactivate() {
    super.deactivate();
    context.read<ProjectCubit>().secilenPersonelAdlar.clear();
    context.read<ProjectCubit>().secilenPersonelIdler.clear();
    context.read<ProjectCubit>().secilenAmirAdlar.clear();
    context.read<ProjectCubit>().secilenAmirIdler.clear();
  }

  void seciliSorumlulariEkle() {
    if (widget.projeler.projeSorumluIsimler! != ',') {
      context.read<ProjectCubit>().secilenAmirAdlar =
          widget.projeler.projeSorumluIsimler!.split(',').toSet().toList();
    }

    if (widget.projeler.projeSorumlular != ',') {
      _secilenAmirList = widget.projeler.projeSorumlular!.split(',');
      context.read<ProjectCubit>().secilenAmirIdler =
          widget.projeler.projeSorumlular!.split(',');
      _gonderilecekAmirIdler = widget.projeler.projeSorumlular!
          .trim()
          .replaceAll(RegExp('^,|,\$'), '');
    }
  }

  void seciliGorevlileriEkle() {
    if (widget.projeler.projeGorevliIsimler! != ',') {
      context.read<ProjectCubit>().secilenPersonelAdlar =
          widget.projeler.projeGorevliIsimler!.split(',').toSet().toList();
    }
    if (widget.projeler.projeGorevliler != ',') {
      _secilenPersonelList = widget.projeler.projeGorevliler!.split(',');
      context.read<ProjectCubit>().secilenPersonelIdler =
          widget.projeler.projeGorevliler!.split(',');
      _gonderilecekPersonelIdler = widget.projeler.projeGorevliler!
          .trim()
          .replaceAll(RegExp('^,|,\$'), '');
    }
  }

  bool isFinish = true;
  bool isArchiveTab = false;

  @override
  Widget build(BuildContext context) {
    return isFinish
        ? Scaffold(
            appBar: appBar(context),
            body: SingleChildScrollView(
              child: Column(
                children: [
                  SizedBox(
                      height: context.dynamicHeight(0.2),
                      child: ImageEnums.cproject.toPageImage),
                  SizedBox(
                    height: context.dynamicHeight(0.04),
                  ),
                  Padding(
                    padding: EdgeInsets.symmetric(
                        horizontal: context.dynamicWidth(0.07)),
                    child: Column(
                      children: [
                        Column(
                          children: [
                            _headLine(context, 'Firma'),
                            _emptySpace(context),
                            firmalarDD(),
                          ],
                        ),
                        _emptySpace(context),
                        Column(
                          children: [
                            _headLine(context, 'Proje Adı'),
                            _emptySpace(context),
                            _tfProjectContainer,
                          ],
                        ),
                        _emptySpace(context),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                _headLine(context, 'Başlangıç Tarihi'),
                                _emptySpace(context),
                                _timeContainer(Row(
                                  children: [
                                    const SizedBox(width: 10),
                                    Text(
                                      gosterilenSaatbaslangic,
                                      style: FontStyles.instance.ddYazi,
                                    ),
                                    const Spacer(),
                                    IconButton(
                                        padding: EdgeInsets.zero,
                                        onPressed: () {
                                          dateTimePickerWidget1(context);
                                        },
                                        tooltip: 'Tarih Seç',
                                        icon: Icon(
                                          Icons.calendar_month_outlined,
                                          size: 23,
                                          color: ColorsConstants
                                              .instance.baseTheme,
                                        )),
                                  ],
                                )),
                              ],
                            ),
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                _headLine(context, 'Bitiş Tarihi'),
                                _emptySpace(context),
                                _timeContainer(
                                  Row(
                                    children: [
                                      const SizedBox(width: 10),
                                      Text(
                                        gosterilenSaatbitis,
                                        style: FontStyles.instance.ddYazi,
                                      ),
                                      const Spacer(),
                                      baslangicSecildi
                                          ? IconButton(
                                              padding: EdgeInsets.zero,
                                              onPressed: () {
                                                dateTimePickerWidget2(context);
                                              },
                                              tooltip: 'Bitiş Tarihi Seç',
                                              icon: Icon(
                                                Icons.calendar_month_outlined,
                                                size: 23,
                                                color: ColorsConstants
                                                    .instance.baseTheme,
                                              ))
                                          : IconButton(
                                              padding: EdgeInsets.zero,
                                              onPressed: () {
                                                ToastManager.instance
                                                    .toastMessageService(
                                                        "Başlangıç tarihini seçin..");
                                              },
                                              tooltip: 'Bitiş Tarihi Seç',
                                              icon: Icon(
                                                Icons.calendar_month_outlined,
                                                size: 23,
                                                color: ColorsConstants
                                                    .instance.baseTheme,
                                              ))
                                    ],
                                  ),
                                ),
                              ],
                            ),
                          ],
                        ),
                        _emptySpace(context),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                _headLine(context, 'Proje Sorumluları'),
                                _emptySpace(context),
                                Container(
                                  height: context.dynamicHeight(0.055),
                                  width: context.dynamicWidth(0.40),
                                  decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(10),
                                    color: _secilenAmirList.isNotEmpty
                                        ? Colors.grey.shade200
                                        : Colors.white,
                                    border: Border.all(
                                      color: Colors.grey.withOpacity(0.6),
                                    ),
                                  ),
                                  child: Row(
                                    children: [
                                      SizedBox(
                                          width: context.dynamicWidth(0.04)),
                                      Text(
                                        _secilenAmirList.isNotEmpty
                                            ? 'Seçildi'
                                            : '',
                                        style: const TextStyle(fontSize: 13.5),
                                      ),
                                      const Spacer(),
                                      IconButton(
                                          padding: EdgeInsets.zero,
                                          onPressed: () {
                                            isFinish = false;
                                            _showMultiSelectLeaders();
                                            isFinish = true;
                                          },
                                          tooltip: 'Sorumlu Seç',
                                          icon: Icon(
                                            Icons.arrow_drop_down_sharp,
                                            size: 23,
                                            color: ColorsConstants
                                                .instance.baseTheme,
                                          ))
                                    ],
                                  ),
                                ),
                              ],
                            ),
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                _headLine(context, 'Proje Görevlileri'),
                                _emptySpace(context),
                                Container(
                                  height: context.dynamicHeight(0.055),
                                  width: context.dynamicWidth(0.40),
                                  decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(10),
                                    color: _secilenPersonelList.isNotEmpty
                                        ? Colors.grey.shade200
                                        : Colors.white,
                                    border: Border.all(
                                      color: Colors.grey.withOpacity(0.6),
                                    ),
                                  ),
                                  child: Row(
                                    children: [
                                      SizedBox(
                                          width: context.dynamicWidth(0.04)),
                                      Text(
                                        _secilenPersonelList.isNotEmpty
                                            ? 'Seçildi'
                                            : '',
                                        style: const TextStyle(fontSize: 13.5),
                                      ),
                                      const Spacer(),
                                      IconButton(
                                          padding: EdgeInsets.zero,
                                          onPressed: () {
                                            isFinish = false;
                                            _showMultiSelectEmployee();
                                            isFinish = true;
                                          },
                                          tooltip: 'Görevli Seç',
                                          icon: Icon(
                                            Icons.arrow_drop_down_sharp,
                                            size: 23,
                                            color: ColorsConstants
                                                .instance.baseTheme,
                                          ))
                                    ],
                                  ),
                                ),
                              ],
                            ),
                          ],
                        ),
                        context.read<ProjectCubit>().secilenAmirIdler.isNotEmpty
                            ? Column(children: [
                                const EmployeeTypeHeadline(
                                    employeeType: "Sorumlular "),
                                SelectedEmployeeWidget(
                                    selectedLeaders: context
                                        .read<ProjectCubit>()
                                        .secilenAmirAdlar)
                              ])
                            : _emptySpace(context),
                        context
                                .read<ProjectCubit>()
                                .secilenPersonelIdler
                                .isNotEmpty
                            ? Column(children: [
                                const EmployeeTypeHeadline(
                                    employeeType: "Görevliler "),
                                SelectedEmployeeWidget(
                                    selectedLeaders: context
                                        .read<ProjectCubit>()
                                        .secilenPersonelAdlar),
                                const Divider(
                                  height: 20,
                                ),
                              ])
                            : SizedBox(height: context.dynamicHeight(0.02)),
                        Column(
                          children: [
                            _headLine(context, 'Açıklama'),
                            _emptySpace(context),
                            Container(
                              padding: const EdgeInsets.all(5),
                              height: context.dynamicHeight(0.14),
                              width: context.dynamicWidth(1),
                              decoration: BoxDecoration(
                                  color: Colors.white,
                                  borderRadius: BorderRadius.circular(10),
                                  border: Border.all(
                                      color: Colors.grey.withOpacity(0.6))),
                              child: TextField(
                                onTapOutside: (event) {
                                  FocusScope.of(context).unfocus();
                                },
                                textInputAction: TextInputAction.done,
                                maxLines: 5,
                                cursorColor: ColorsConstants.instance.baseTheme,
                                style: FontStyles.instance.projectbxDdyazi,
                                controller: tfAciklama,
                                decoration: const InputDecoration(
                                    border: InputBorder.none,
                                    contentPadding:
                                        EdgeInsets.symmetric(horizontal: 2)),
                              ),
                            ),
                          ],
                        ),
                        SizedBox(height: context.dynamicHeight(0.02)),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.end,
                          children: [
                            widget.projeler.projeOnay == '1'
                                ? _archiveButton
                                : _unarchiveButton,
                            _buttonWidthEmptySpace,
                            _updatedButton,
                          ],
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          )
        : const Scaffold();
  }

  AppBar appBar(BuildContext context) {
    return AppBar(
      backgroundColor: Colors.transparent,
      elevation: 0,
      title: Text(
          widget.projeler.projeAd!.length > 20
              ? widget.projeler.projeAd!.substring(0, 19)
              : widget.projeler.projeAd!,
          style: FontStyles.instance.appbarTitleStyle),
      centerTitle: true,
      actions: [
        IconButton(
            onPressed: () {},
            icon: const Icon(
              Icons.notifications_none_outlined,
              color: Colors.black,
            )),
      ],
      leading: IconButton(
          onPressed: () {
            Navigator.pop(context, true);
          },
          icon: const Icon(
            Icons.arrow_back_ios_new,
            color: Colors.black54,
            size: 20,
          )),
    );
  }

  Widget _timeContainer(Widget child) {
    return Container(
        height: context.dynamicHeight(0.05),
        width: context.dynamicWidth(0.4),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(10),
          color: Colors.white,
          border: Border.all(
            color: Colors.grey.withOpacity(0.6),
          ),
        ),
        child: child);
  }

  Widget get _tfProjectContainer => Container(
        height: context.dynamicHeight(0.05),
        width: context.dynamicWidth(0.88),
        alignment: Alignment.center,
        decoration: BoxDecoration(
            color: Colors.white,
            border: Border.all(color: Colors.grey.shade400),
            borderRadius: BorderRadius.circular(10)),
        child: TextFormField(
          textAlignVertical: TextAlignVertical.center,
          decoration: const InputDecoration(
            contentPadding: EdgeInsets.symmetric(horizontal: 8),
            border: OutlineInputBorder(borderSide: BorderSide.none),
          ),
          style: FontStyles.instance.projectbxDdyazi,
          magnifierConfiguration: TextMagnifierConfiguration.disabled,
          validator: (value) {
            if (value!.isEmpty ||
                !RegExp(r"^[a-zA-Z]+(([',. -][a-zA-Z ])?[a-zA-Z]*)*$")
                    .hasMatch(value)) {
              tfProjeAd.text = 'geçersiz';
              ScaffoldMessenger.of(context).showSnackBar(
                SnackBar(
                  backgroundColor: ColorsConstants.instance.baseTheme,
                  content: const Text(
                    'Geçerli bir proje adı girin..',
                  ),
                  behavior: SnackBarBehavior.floating,
                  action: SnackBarAction(
                    label: "Tamam",
                    textColor: Colors.white,
                    onPressed: () {},
                  ),
                ),
              );
            } else {
              return null;
            }
            return null;
          },
          textInputAction: TextInputAction.done,
          cursorColor: ColorsConstants.instance.baseTheme,
          controller: tfProjeAd,
        ),
      );

  Widget get _buttonWidthEmptySpace => SizedBox(
        width: context.dynamicWidth(0.05),
      );

  Widget get _archiveButton => TextButton(
        onPressed: () {
          context
              .read<ProjectCubit>()
              .projeArsivleArsivdenCikar(
                  widget.projeler.projeId!,
                  "0",
                  context.read<LoginCubit>().token,
                  context.read<LoginCubit>().id,
                  context.read<LoginCubit>().userfirmId,
                  context.read<LoginCubit>().tip)
              .whenComplete(() {
            Fluttertoast.showToast(
                    msg: 'Proje Arşivlendi !',
                    backgroundColor: ColorsConstants.instance.baseTheme,
                    toastLength: Toast.LENGTH_SHORT,
                    textColor: Colors.white,
                    gravity: ToastGravity.BOTTOM)
                .whenComplete(() {
              Future.delayed(const Duration(milliseconds: 1000), () {
                Navigator.pop(context, true);
              });
            });
          });
        },
        style: TextButton.styleFrom(
          backgroundColor: ColorsConstants.instance.baseTheme,
        ),
        child: Text(
          ApplicationConstants.instance.moduleArchiveTxt,
          style: const TextStyle(color: Colors.white),
        ),
      );

  Widget get _unarchiveButton => TextButton(
        onPressed: () {
          context
              .read<ProjectCubit>()
              .projeArsivleArsivdenCikar(
                  widget.projeler.projeId!,
                  "1",
                  context.read<LoginCubit>().token,
                  context.read<LoginCubit>().id,
                  context.read<LoginCubit>().userfirmId,
                  context.read<LoginCubit>().tip)
              .whenComplete(() {
            Fluttertoast.showToast(
                    msg: 'Proje Arşivden Çıkarıldı !',
                    backgroundColor: ColorsConstants.instance.baseTheme,
                    toastLength: Toast.LENGTH_SHORT,
                    textColor: Colors.white,
                    gravity: ToastGravity.BOTTOM)
                .whenComplete(() {
              Future.delayed(const Duration(milliseconds: 1000), () {
                Navigator.pop(context, true);
              });
            });
          });
        },
        style: TextButton.styleFrom(
          backgroundColor: ColorsConstants.instance.baseTheme,
        ),
        child: Text(
          ApplicationConstants.instance.moduleUnArchiveTxt,
          style: const TextStyle(color: Colors.white),
        ),
      );

  Widget get _updatedButton => TextButton(
        onPressed: () {
          _gonderilecekAmirIdler =
              context.read<ProjectCubit>().secilenAmirIdler.join(",");
          String safAmirIdler =
              _gonderilecekAmirIdler.replaceAll(RegExp(',+'), ',');
          _gonderilecekPersonelIdler =
              context.read<ProjectCubit>().secilenPersonelIdler.join(",");
          String safPersonelIdler =
              _gonderilecekPersonelIdler.replaceAll(RegExp(',+,'), ',');

          if (_secilenFirma != null &&
              _secilenFirma!.isNotEmpty &&
              tfProjeAd.text.isNotEmpty &&
              dbSaatbaslangic.isNotEmpty &&
              dbSaatbitis.isNotEmpty &&
              safAmirIdler.isNotEmpty &&
              safPersonelIdler.isNotEmpty &&
              tfAciklama.text.isNotEmpty) {
            context.read<ProjectCubit>().projeGuncelle(
                widget.projeler.projeId!,
                _secilenFirma!,
                tfProjeAd.text,
                tfAciklama.text,
                dbSaatbaslangic,
                dbSaatbitis,
                safAmirIdler,
                safPersonelIdler,
                context.read<LoginCubit>().token,
                context.read<LoginCubit>().id,
                context.read<LoginCubit>().userfirmId,
                context.read<LoginCubit>().tip);
            Fluttertoast.showToast(
                    msg: 'Proje Güncellendi !',
                    backgroundColor: ColorsConstants.instance.baseTheme,
                    gravity: ToastGravity.CENTER,
                    textColor: Colors.white)
                .whenComplete(() {
              Future.delayed(const Duration(milliseconds: 1000), () {
                Navigator.pop(context, true);
              });
            });
          } else {
            ToastManager.instance.toastMessageService('Proje Güncellenemedi');
          }
        },
        style: TextButton.styleFrom(
          backgroundColor: ColorsConstants.instance.baseTheme,
        ),
        child: Text(
          ApplicationConstants.instance.moduleUpdateTxt,
          style: const TextStyle(color: Colors.white),
        ),
      );
}

Widget _emptySpace(BuildContext context) {
  return SizedBox(
    height: context.dynamicHeight(0.01),
  );
}

Widget _headLine(BuildContext context, String title, {bool isRequired = true}) {
  return Row(
    children: [
      Text(
        title,
        style: FontStyles.instance.projectbxBaslik,
      ),
      isRequired
          ? Row(
              children: [
                SizedBox(
                  width: context.dynamicWidth(0.01),
                ),
                Text(
                  '(zorunlu)',
                  style: FontStyles.instance.employeetbxRequired,
                ),
              ],
            )
          : const SizedBox.shrink()
    ],
  );
}


// _gonderilecekPersonelIdler.trim().replaceAll(RegExp('^,|,\$'), ''); ------ Stringin başındaki ve sonundaki virgülleri kaldırma kodu
// String duzenlenmisAmirIdler = _gonderilecekAmirIdler.replaceAll(RegExp(',+'), ','); ----- peş peşe olan virgülleri kaldırma kodu
