import 'dart:convert';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:dropdown_button2/dropdown_button2.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_cupertino_datetime_picker/flutter_cupertino_datetime_picker.dart';
import 'package:image_picker/image_picker.dart';
import 'package:intl/intl.dart';
import 'package:hamlemuhcrm/core/constants/app_constants.dart';
import 'package:hamlemuhcrm/core/extensions/log_extension.dart';
import 'package:hamlemuhcrm/features/human_resources/constants/employee_textfield_input.dart';
import 'package:hamlemuhcrm/features/human_resources/model/personel.dart';
import 'package:hamlemuhcrm/data/dropdown_models/personal_getdata_api.dart';
import 'package:hamlemuhcrm/core/constants/url_services_constant.dart';
import 'package:hamlemuhcrm/features/human_resources/cubit/employee_cubit.dart';
import 'package:hamlemuhcrm/features/auth/login/cubit/login_cubit.dart';
import 'package:hamlemuhcrm/core/constants/font_styles.dart';
import 'package:hamlemuhcrm/core/extensions/responsive_extension.dart';
import 'package:http/http.dart' as http;

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

class EmployeeUpdatePage extends StatefulWidget {
  final Personel personel;
  const EmployeeUpdatePage({super.key, required this.personel});

  @override
  State<EmployeeUpdatePage> createState() => _EmployeeUpdatePageState();
}

class _EmployeeUpdatePageState extends State<EmployeeUpdatePage> {
  bool isFinish = false; //sayfa acilisi için
  bool isUpdated = false; //bilgiler güncellenirse true olacak..
  bool yeniEkle = false;
  String cevrilmisTarih = "";
  bool arsivMi = false;
  final String addPhotoServerURL =
      'https://musiad.hamleyazilim.com/api/auth/user/addprofilimage';
  final String baseURLPhoto = 'https://musiad.hamleyazilim.com/upload-user';
  final String baseURL = URLAPIService.baseURL;
  final _uEmployeeKey = GlobalKey<FormState>();
  final tfAd = TextEditingController();
  final tfSoyad = TextEditingController();
  final tfMail = TextEditingController();
  final tfSifre = TextEditingController();
  final tfCepTel = TextEditingController();
  final tfTCNo = TextEditingController();
  final tfAdres = TextEditingController();
  String dbSaat = '';
  String gosterilenSaat = '';

  final Map<String, String> askerlikDD = {
    '-1': 'Muaf',
    '0': 'Yapılmadı',
    '1': 'Yapıldı',
  };

  String? secilenAskerlik = "1";

  //////////////////////////////////////////////////////////////////////////////
  var gelenUnvanlar;
  String? _secilenUnvan;
  String gonderilenUnvanID = "";

  Future<void> unvanData(String token, String loginuserid) async {
    var unvanURL = "$baseURL/mobil/api/dd/unvan_dd_pdo.php";
    var veri = {"token": token, "loginuserid": loginuserid};
    var unvanlarCevap =
        await Dio().post(unvanURL, data: FormData.fromMap(veri));
    if (unvanlarCevap.statusCode == 200) {
      var data = json.decode(unvanlarCevap.data);
      // 'unvanlar' anahtarını kontrol edin ve boş olup olmadığını kontrol edin
      if (data != null &&
          data.containsKey('unvanlar') &&
          data['unvanlar'].isNotEmpty) {
        setState(() {
          gelenUnvanlar = data; // Veri uygun formatta ve boş değil
        });
      } else {
        setState(() {
          gelenUnvanlar = {
            "unvanlar": []
          }; // Boş bir listeyle güvenli bir şekilde başlat
        });
      }
    } else {}
  }

  Widget unvanDD() {
    List<UnvanDDModel> unvanListesi = List<UnvanDDModel>.from(
      gelenUnvanlar["unvanlar"].map(
        (i) {
          return UnvanDDModel.fromJSON(i);
        },
      ),
    );

    return DropdownButtonHideUnderline(
      child: DropdownButton2(
        hint: const Text(
          "",
          style: TextStyle(fontSize: 12, color: Colors.black54),
        ), //Data1
        isExpanded: true,
        items: unvanListesi.map((unvan) {
          return DropdownMenuItem(
            value: unvan.unvanId,
            child: Text(unvan.unvanAd ?? '',
                style: FontStyles.instance.employeetbxYazi), //value
          );
        }).toList(),
        value: _secilenUnvan,
        onChanged: (newValue) {
          setState(() {
            _secilenUnvan = newValue.toString();
            gonderilenUnvanID = _secilenUnvan!;
            "_secilen UnvanID == $_secilenUnvan".log();
          });
        },
        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.shade400),
          ),
          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,
          width: context.dynamicWidth(0.86),
          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),
        ),
      ),
    );
  }

  Future<void> unvanCek() async {
    await unvanData(
        context.read<LoginCubit>().token, context.read<LoginCubit>().id);
  }

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

  final ImagePicker _imagePicker = ImagePicker();
  File? uploadimage;
  String fileName = "";

  Future<void> chooseImage() async {
    var chooseimage = await _imagePicker.pickImage(source: ImageSource.gallery);
    setState(() {
      if (chooseimage != null) {
        uploadimage = File(chooseimage.path);
        fileName = chooseimage.name;
      }
    });
  }

  Future<void> uploadImage(
    File imageFile,
    String userId,
    String loginUserId,
    String loginUserType,
    String loginUserFirmId,
    String token,
    String userEmail,
    String oldImage,
  ) async {
    // API endpoint ve dosya adı
    final url = Uri.parse(addPhotoServerURL);
    final fileName = imageFile.path.split('/').last;

    // multipart/form-data isteği oluşturma
    final request = http.MultipartRequest('POST', url)
      ..fields['user_id'] = userId
      ..fields['loginuserid'] = loginUserId
      ..fields['loginusertype'] = loginUserType
      ..fields['login_userfirm_id'] = loginUserFirmId
      ..fields['token'] = token
      ..fields['user_email'] = userEmail
      ..fields['old_image'] = oldImage
      ..files.add(await http.MultipartFile.fromPath(
        'image',
        imageFile.path,
        filename: fileName,
      ));

    // isteği gönderme ve cevabı alma
    final response = await http.Response.fromStream(await request.send());

    // istek başarılıysa 200 döndürür
    if (response.statusCode == 200) {
      debugPrint('Resim başarıyla yüklendi.');
      debugPrint(response.body.toString());
    } else {
      debugPrint(
          'Resim yüklenirken bir hata oluştu. Hata kodu: ${response.statusCode}');
    }
  }

  @override
  void initState() {
    debugPrint('gelen unvan id : ${widget.personel.unvanId}');
    isFinish = false;
    yeniEkle = widget.personel.image == 'buresimyok.jpg';
    if (widget.personel.unvanId == '0' ||
        widget.personel.unvanId == '' ||
        widget.personel.unvanId == null) {
      _secilenUnvan = '15'; //veritabanındaki 15 id Personel Unvanı
      gonderilenUnvanID = '15';
    } else {
      _secilenUnvan = widget.personel.unvanId;
      gonderilenUnvanID = widget.personel.unvanId!;
    }
    tfAd.text = widget.personel.firstName!;
    tfSoyad.text = widget.personel.lastName!;
    tfMail.text = widget.personel.email!;
    tfSifre.text = '**********';
    tfCepTel.text = widget.personel.ceptelefon!;
    tfTCNo.text = widget.personel.userdataTcKimlik!;
    tfAdres.text = widget.personel.userdataAdres!;
    if (widget.personel.userdataAskerlikDurumu != null &&
        widget.personel.userdataAskerlikDurumu != '') {
      secilenAskerlik = widget.personel.userdataAskerlikDurumu;
    }
    arsivMi = widget.personel.onay == '0';
    if (widget.personel.userdataIseGirisTarihi != '' &&
        widget.personel.userdataIseGirisTarihi != '0' &&
        widget.personel.userdataIseGirisTarihi != null) {
      trTariheCevir(widget.personel.userdataIseGirisTarihi!);
      gosterilenSaat = cevrilmisTarih;
      dbSaat = widget.personel.userdataIseGirisTarihi!;
    }
    unvanData(context.read<LoginCubit>().token, context.read<LoginCubit>().id)
        .whenComplete(() {
      isFinish = true;
    });
    super.initState();
  }

  void trTariheCevir(String tarih) async {
    final DateFormat format = DateFormat.yMd('tr');
    if (tarih != '0') {
      cevrilmisTarih = format.format(DateTime.parse(tarih));
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: appBar(context),
      body: isFinish
          ? SingleChildScrollView(
              child: Form(
                key: _uEmployeeKey,
                child: Column(
                  children: [
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        SizedBox(
                          height: context.dynamicHeight(0.2),
                          width: context.dynamicWidth(
                              0.38), //üst kısım sayfada kapladığı genişlik
                          child: Stack(children: [
                            uploadimage == null
                                ? CircleAvatar(
                                    minRadius: context.dynamicHeight(0.2),
                                    backgroundImage: widget.personel.image !=
                                            'buresimyok.jpg'
                                        ? NetworkImage(
                                            "$baseURLPhoto/${widget.personel.image}")
                                        : const NetworkImage(
                                            'https://musiad.hamleyazilim.com/panel/images/profil.png'),
                                    child: Container(
                                      alignment: Alignment.center,
                                      decoration: BoxDecoration(
                                          shape: BoxShape.circle,
                                          border: Border.all(
                                              color: ColorsConstants
                                                  .instance.baseTheme,
                                              width: 3)),
                                    ),
                                  )
                                : CircleAvatar(
                                    minRadius: context.dynamicHeight(0.2),
                                    backgroundImage: FileImage(uploadimage!),
                                    child: Container(
                                      alignment: Alignment.center,
                                      decoration: BoxDecoration(
                                          shape: BoxShape.circle,
                                          border: Border.all(
                                              color: ColorsConstants
                                                  .instance.baseTheme,
                                              width: 3)),
                                    ),
                                  ),
                            Positioned(
                              bottom: 0,
                              right: 4,
                              child: Container(
                                height: 30,
                                width: 30,
                                decoration: BoxDecoration(
                                  color: ColorsConstants.instance.baseTheme,
                                  shape: BoxShape.circle,
                                ),
                                child: IconButton(
                                  padding: const EdgeInsets.all(0),
                                  icon: Icon(
                                    yeniEkle
                                        ? Icons.add_a_photo_outlined
                                        : Icons.add_a_photo_rounded,
                                    color: Colors.white,
                                    size: 14,
                                  ),
                                  onPressed: () {
                                    setState(() {
                                      chooseImage();
                                    });
                                  },
                                ),
                              ),
                            ),
                          ]),
                        ),
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            SizedBox(
                              height: context.dynamicHeight(0.01),
                            ),
                            _headLine(
                              'Adı',
                              context,
                            ),
                            SizedBox(
                              height: context.dynamicHeight(0.01),
                            ),
                            Container(
                              height: context.dynamicHeight(0.05),
                              width: context.dynamicWidth(0.43),
                              padding: EdgeInsets.symmetric(
                                  horizontal: context.dynamicWidth(0.02),
                                  vertical: context.dynamicHeight(0.01)),
                              alignment: Alignment.center,
                              decoration: BoxDecoration(
                                  color: Colors.white,
                                  border:
                                      Border.all(color: Colors.grey.shade400),
                                  borderRadius: BorderRadius.circular(10)),
                              child: TextFormField(
                                inputFormatters: [
                                  LengthLimitingTextInputFormatter(20)
                                ],
                                style: FontStyles.instance.employeetbxYazi,
                                magnifierConfiguration:
                                    TextMagnifierConfiguration.disabled,
                                validator: (value) {
                                  if (value!.isEmpty ||
                                      !RegExp(r"^[a-zA-Z]+(([',. -][a-zA-Z ])?[a-zA-Z]*)*$")
                                          .hasMatch(value)) {
                                    tfAd.text = 'geçersiz';
                                    ScaffoldMessenger.of(context).showSnackBar(
                                      SnackBar(
                                        backgroundColor: ColorsConstants
                                            .instance.backgroundColor,
                                        content: const Text(
                                          'Geçerli bir isim girin..',
                                        ),
                                        behavior: SnackBarBehavior.floating,
                                        action: SnackBarAction(
                                          label: "Tamam",
                                          textColor: Colors.white,
                                          onPressed: () {},
                                        ),
                                      ),
                                    );
                                  }
                                  return null;
                                },
                                textInputAction: TextInputAction.done,
                                cursorColor: ColorsConstants.instance.baseTheme,
                                controller: tfAd,
                                decoration: const InputDecoration(
                                    border: InputBorder.none),
                              ),
                            ),
                            SizedBox(
                              height: context.dynamicHeight(0.01),
                            ),
                            _headLine(
                              'Soyadı',
                              context,
                            ),
                            SizedBox(
                              height: context.dynamicHeight(0.01),
                            ),
                            Container(
                              height: context.dynamicHeight(0.05),
                              width: context.dynamicWidth(0.43),
                              padding: EdgeInsets.symmetric(
                                  horizontal: context.dynamicWidth(0.02),
                                  vertical: context.dynamicHeight(0.01)),
                              alignment: Alignment.center,
                              decoration: BoxDecoration(
                                  color: Colors.white,
                                  border:
                                      Border.all(color: Colors.grey.shade400),
                                  borderRadius: BorderRadius.circular(10)),
                              child: TextFormField(
                                inputFormatters: [
                                  LengthLimitingTextInputFormatter(20)
                                ],
                                style: FontStyles.instance.employeetbxYazi,
                                magnifierConfiguration:
                                    TextMagnifierConfiguration.disabled,
                                validator: (value) {
                                  if (value!.isEmpty ||
                                      !RegExp(r"^[a-zA-Z]+(([',. -][a-zA-Z ])?[a-zA-Z]*)*$")
                                          .hasMatch(value)) {
                                    tfSoyad.text = 'geçersiz';
                                    ScaffoldMessenger.of(context).showSnackBar(
                                      SnackBar(
                                        backgroundColor: ColorsConstants
                                            .instance.backgroundColor,
                                        content: const Text(
                                          'Geçerli bir soyisim girin..',
                                        ),
                                        behavior: SnackBarBehavior.floating,
                                        action: SnackBarAction(
                                          label: "Tamam",
                                          textColor: Colors.white,
                                          onPressed: () {},
                                        ),
                                      ),
                                    );
                                  }
                                  return null;
                                },
                                textInputAction: TextInputAction.done,
                                cursorColor: ColorsConstants.instance.baseTheme,
                                controller: tfSoyad,
                                decoration: const InputDecoration(
                                    border: InputBorder.none),
                              ),
                            ),
                          ],
                        ),
                      ],
                    ),
                    SizedBox(
                      height: context.dynamicHeight(0.02),
                    ),
                    Container(
                      width: context.dynamicWidth(0.9),
                      margin: EdgeInsets.symmetric(
                          horizontal: context.dynamicWidth(
                              0.07)), //orta kısım yanlardaki boşluk miktarı
                      child: Column(
                        children: [
                          Column(
                            children: [
                              _headLine(
                                'Mail Adresi',
                                context,
                              ),
                              SizedBox(
                                height: context.dynamicHeight(0.01),
                              ),
                              Container(
                                height: context.dynamicHeight(0.05),
                                width: context.dynamicWidth(1),
                                padding: EdgeInsets.symmetric(
                                    horizontal: context.dynamicWidth(0.02),
                                    vertical: context.dynamicHeight(0.01)),
                                alignment: Alignment.center,
                                decoration: BoxDecoration(
                                    color: Colors.white,
                                    border:
                                        Border.all(color: Colors.grey.shade400),
                                    borderRadius: BorderRadius.circular(10)),
                                child: TextFormField(
                                  magnifierConfiguration:
                                      TextMagnifierConfiguration.disabled,
                                  validator: (value) {
                                    if (value!.isEmpty ||
                                        !RegExp(r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+@[a-zA-Z0-9]+\.[a-zA-Z]+")
                                            .hasMatch(value)) {
                                      tfMail.text = 'geçersiz';
                                      ScaffoldMessenger.of(context)
                                          .showSnackBar(
                                        SnackBar(
                                          backgroundColor: ColorsConstants
                                              .instance.backgroundColor,
                                          content: const Text(
                                            'Geçerli bir mail adresi girin..',
                                          ),
                                          behavior: SnackBarBehavior.floating,
                                          action: SnackBarAction(
                                            label: "Tamam",
                                            textColor: Colors.white,
                                            onPressed: () {},
                                          ),
                                        ),
                                      );
                                    }
                                    return null;
                                  },
                                  inputFormatters: [
                                    LengthLimitingTextInputFormatter(50)
                                  ],
                                  style: FontStyles.instance.employeetbxYazi,
                                  textInputAction: TextInputAction.done,
                                  cursorColor:
                                      ColorsConstants.instance.baseTheme,
                                  controller: tfMail,
                                  decoration: InputDecoration(
                                      border: InputBorder.none,
                                      errorStyle:
                                          FontStyles.instance.employeetbxError),
                                ),
                              ),
                            ],
                          ),
                          SizedBox(
                            height: context.dynamicHeight(0.02),
                          ),
                          Column(
                            children: [
                              _headLine(
                                'Şifre',
                                context,
                              ),
                              SizedBox(
                                height: context.dynamicHeight(0.01),
                              ),
                              Container(
                                height: context.dynamicHeight(0.05),
                                width: context.dynamicWidth(1),
                                padding: EdgeInsets.symmetric(
                                    horizontal: context.dynamicWidth(0.02),
                                    vertical: context.dynamicHeight(0.01)),
                                alignment: Alignment.center,
                                decoration: BoxDecoration(
                                    color: Colors.white,
                                    border:
                                        Border.all(color: Colors.grey.shade400),
                                    borderRadius: BorderRadius.circular(10)),
                                child: TextFormField(
                                  obscureText: true,
                                  //php tarafında 10 tane yıldız ve boş gönderilirse şifre değiştirilmeyecek...
                                  onTap: () {
                                    tfSifre.clear();
                                  },
                                  magnifierConfiguration:
                                      TextMagnifierConfiguration.disabled,
                                  validator: (value) {
                                    if (value!.isEmpty || value.length < 4) {
                                      tfSifre.text = 'geçersiz';
                                      ScaffoldMessenger.of(context)
                                          .showSnackBar(
                                        SnackBar(
                                          backgroundColor: ColorsConstants
                                              .instance.backgroundColor,
                                          content: const Text(
                                            'Geçerli bir sifre girin..',
                                          ),
                                          behavior: SnackBarBehavior.floating,
                                          action: SnackBarAction(
                                            label: "Tamam",
                                            textColor: Colors.white,
                                            onPressed: () {},
                                          ),
                                        ),
                                      );
                                    }
                                    return null;
                                  },
                                  inputFormatters: [
                                    LengthLimitingTextInputFormatter(50)
                                  ],
                                  style: FontStyles.instance.employeetbxYazi,
                                  textInputAction: TextInputAction.done,
                                  cursorColor:
                                      ColorsConstants.instance.baseTheme,
                                  controller: tfSifre,
                                  decoration: InputDecoration(
                                      border: InputBorder.none,
                                      errorStyle:
                                          FontStyles.instance.employeetbxError),
                                ),
                              ),
                            ],
                          ),
                          SizedBox(
                            height: context.dynamicHeight(0.02),
                          ),
                          Column(
                            children: [
                              _headLine('Ünvan', context),
                              SizedBox(
                                height: context.dynamicHeight(0.01),
                              ),
                              unvanDD(),
                            ],
                          ),
                          SizedBox(
                            height: context.dynamicHeight(0.02),
                          ),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  _headLine(
                                    'Cep Telefonu',
                                    context,
                                  ),
                                  SizedBox(
                                    height: context.dynamicHeight(0.01),
                                  ),
                                  Container(
                                    height: context.dynamicHeight(0.05),
                                    width: context.dynamicWidth(0.38),
                                    alignment: Alignment.center,
                                    decoration: BoxDecoration(
                                        color: Colors.white,
                                        border: Border.all(
                                            color: Colors.grey.shade400),
                                        borderRadius:
                                            BorderRadius.circular(10)),
                                    child: TextFormField(
                                      magnifierConfiguration:
                                          TextMagnifierConfiguration.disabled,
                                      validator: (value) {
                                        if (value!.isEmpty ||
                                            !RegExp(r'^\s*(?:\+?(\d{1,3}))?[-. (]*(\d{3})[-. )]*(\d{3})[-. ]*(\d{4})(?: *x(\d+))?\s*$')
                                                .hasMatch(value) ||
                                            value.length != 11) {
                                          tfCepTel.text = 'geçersiz';
                                          ScaffoldMessenger.of(context)
                                              .showSnackBar(
                                            SnackBar(
                                              backgroundColor: ColorsConstants
                                                  .instance.backgroundColor,
                                              content: const Text(
                                                'Geçerli bir telefon numarası girin..',
                                              ),
                                              behavior:
                                                  SnackBarBehavior.floating,
                                              action: SnackBarAction(
                                                label: "Tamam",
                                                textColor: Colors.white,
                                                onPressed: () {},
                                              ),
                                            ),
                                          );
                                        }
                                        return null;
                                      },
                                      inputFormatters: [
                                        LengthLimitingTextInputFormatter(11)
                                      ],
                                      style:
                                          FontStyles.instance.employeetbxYazi,
                                      textInputAction: TextInputAction.done,
                                      cursorColor:
                                          ColorsConstants.instance.baseTheme,
                                      controller: tfCepTel,
                                      decoration: EmployeeTextFieldInput(
                                          context, '5556669988'),
                                    ),
                                  ),
                                ],
                              ),
                              Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  _headLine(
                                    'İşe Giriş Tarihi',
                                    context,
                                  ),
                                  SizedBox(
                                    height: context.dynamicHeight(0.01),
                                  ),
                                  Container(
                                      height: context.dynamicHeight(0.05),
                                      width: context.dynamicWidth(0.38),
                                      alignment: Alignment.center,
                                      decoration: BoxDecoration(
                                        borderRadius: BorderRadius.circular(10),
                                        color: Colors.white,
                                        border: Border.all(
                                            color: Colors.grey.shade400),
                                      ),
                                      child: Row(
                                        children: [
                                          const SizedBox(width: 10),
                                          Text(
                                            gosterilenSaat,
                                            style: FontStyles
                                                .instance.employeetbxYazi,
                                          ),
                                          const Spacer(),
                                          IconButton(
                                              onPressed: () {
                                                dateTimePickerWidget(context);
                                              },
                                              padding: EdgeInsets.zero,
                                              tooltip: 'Tarih Seç',
                                              icon: Icon(
                                                Icons.calendar_month_outlined,
                                                size: 23,
                                                color: ColorsConstants
                                                    .instance.baseTheme,
                                              )),
                                        ],
                                      )), //buraya işe başlama tarihi gelecek.
                                ],
                              ),
                            ],
                          ),
                          SizedBox(
                            height: context.dynamicHeight(0.02),
                          ),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  _headLine('Toplam İzin', context,
                                      isRequired: false),
                                  SizedBox(
                                    height: context.dynamicHeight(0.01),
                                  ),
                                  Container(
                                    height: context.dynamicHeight(0.05),
                                    width: context.dynamicWidth(0.38),
                                    alignment: Alignment.center,
                                    decoration: BoxDecoration(
                                        color: Colors.white,
                                        border: Border.all(
                                            color: Colors.grey.shade400),
                                        borderRadius:
                                            BorderRadius.circular(10)),
                                    child: Text(
                                      widget
                                          .personel.toplamhakkettigiizinsayisi!,
                                      style:
                                          FontStyles.instance.employeetbxYazi,
                                    ),
                                  ), //buraya toplam izin sayısı gelecek..
                                ],
                              ),
                              Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  _headLine('Kullanılan İzin', context,
                                      isRequired: false),
                                  SizedBox(
                                    height: context.dynamicHeight(0.01),
                                  ),
                                  Container(
                                    height: context.dynamicHeight(0.05),
                                    width: context.dynamicWidth(0.38),
                                    alignment: Alignment.center,
                                    decoration: BoxDecoration(
                                        color: Colors.white,
                                        border: Border.all(
                                            color: Colors.grey.shade400),
                                        borderRadius:
                                            BorderRadius.circular(10)),
                                    child: Text(
                                      widget.personel.userkullanilanizin
                                          .toString(),
                                      style:
                                          FontStyles.instance.employeetbxYazi,
                                    ),
                                  ), //buraya kullanılan izin sayısı gelecek..
                                ],
                              ),
                            ],
                          ),
                          SizedBox(
                            height: context.dynamicHeight(0.02),
                          ),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  _headLine(
                                    'TC No',
                                    context,
                                  ),
                                  SizedBox(
                                    height: context.dynamicHeight(0.01),
                                  ),
                                  Container(
                                    height: context.dynamicHeight(0.05),
                                    width: context.dynamicWidth(0.38),
                                    padding: EdgeInsets.symmetric(
                                        horizontal: context.dynamicWidth(0.02),
                                        vertical: context.dynamicHeight(0.01)),
                                    alignment: Alignment.center,
                                    decoration: BoxDecoration(
                                        color: Colors.white,
                                        border: Border.all(
                                            color: Colors.grey.shade400),
                                        borderRadius:
                                            BorderRadius.circular(10)),
                                    child: TextFormField(
                                      magnifierConfiguration:
                                          TextMagnifierConfiguration.disabled,
                                      validator: (value) {
                                        if (value!.isEmpty ||
                                            !RegExp(r'^\s*(?:\+?(\d{1,3}))?[-. (]*(\d{3})[-. )]*(\d{3})[-. ]*(\d{4})(?: *x(\d+))?\s*$')
                                                .hasMatch(value) ||
                                            value.length != 11) {
                                          tfTCNo.text = 'geçersiz';
                                          ScaffoldMessenger.of(context)
                                              .showSnackBar(
                                            SnackBar(
                                              backgroundColor: ColorsConstants
                                                  .instance.backgroundColor,
                                              content: const Text(
                                                'Geçerli bir tc no girin..',
                                              ),
                                              behavior:
                                                  SnackBarBehavior.floating,
                                              action: SnackBarAction(
                                                label: "Tamam",
                                                textColor: Colors.white,
                                                onPressed: () {},
                                              ),
                                            ),
                                          );
                                        }
                                        return null;
                                      },
                                      inputFormatters: [
                                        LengthLimitingTextInputFormatter(11)
                                      ],
                                      style:
                                          FontStyles.instance.employeetbxYazi,
                                      textInputAction: TextInputAction.done,
                                      cursorColor:
                                          ColorsConstants.instance.baseTheme,
                                      controller: tfTCNo,
                                      decoration: InputDecoration(
                                          border: InputBorder.none,
                                          errorStyle: FontStyles
                                              .instance.employeetbxError),
                                    ),
                                  ),
                                ],
                              ),
                              Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  _headLine(
                                    'Askerlik Durumu',
                                    context,
                                  ),
                                  SizedBox(
                                    height: context.dynamicHeight(0.01),
                                  ),
                                  //buraya askerlik durumu dropdown gelecek..
                                  DropdownButtonHideUnderline(
                                    child: DropdownButton2(
                                      isExpanded: true,
                                      value: secilenAskerlik,
                                      items: askerlikDD.entries
                                          .map((entry) =>
                                              DropdownMenuItem<String>(
                                                value: entry.key,
                                                child: Text(
                                                  entry.value,
                                                  style: FontStyles
                                                      .instance.employeetbxYazi,
                                                ),
                                              ))
                                          .toList(),
                                      onChanged: (value) {
                                        secilenAskerlik = value;
                                        setState(() {
                                          //context.read<CustomersCubit>().secilenGorusmeTipi = selectedValue!;
                                        });
                                        'Seçilen Deger DD : $value'.log();
                                      },
                                      buttonStyleData: ButtonStyleData(
                                        height: context.dynamicHeight(0.05),
                                        width: context.dynamicWidth(0.38),
                                        padding: const EdgeInsets.symmetric(
                                            horizontal: 10),
                                        decoration: BoxDecoration(
                                            borderRadius:
                                                BorderRadius.circular(10),
                                            color: Colors.white,
                                            border: Border.all(
                                                color: Colors.black26)),
                                        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,
                                        width: context.dynamicWidth(0.38),
                                        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),
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ],
                          ),
                          SizedBox(
                            height: context.dynamicHeight(0.013),
                          ),
                          _headLine(
                            'Adres',
                            context,
                          ),
                          SizedBox(
                            height: context.dynamicHeight(0.01),
                          ),
                          Container(
                            height: context.dynamicHeight(0.15),
                            width: context.dynamicWidth(1),
                            padding: const EdgeInsets.symmetric(horizontal: 4),
                            alignment: Alignment.center,
                            decoration: BoxDecoration(
                                color: Colors.white,
                                border: Border.all(color: Colors.grey.shade400),
                                borderRadius: BorderRadius.circular(10)),
                            child: TextFormField(
                              inputFormatters: [
                                LengthLimitingTextInputFormatter(100)
                              ],
                              textInputAction: TextInputAction.next,
                              maxLines: 5,
                              style: FontStyles.instance.employeetbxYazi,
                              cursorColor: ColorsConstants.instance.baseTheme,
                              controller: tfAdres,
                              decoration: const InputDecoration(
                                  border: InputBorder.none),
                            ),
                          ),
                          SizedBox(
                            height: context.dynamicHeight(0.01),
                          ),
                          Row(
                            children: [
                              Text(
                                'Dosya',
                                style: TextStyle(
                                    color: ColorsConstants.instance.baseTheme,
                                    fontSize: 11,
                                    fontWeight: FontWeight.w500),
                              ),
                            ],
                          ),
                          SizedBox(
                            height: context.dynamicHeight(0.01),
                          ),
                          Container(
                              height: context.dynamicHeight(0.15),
                              padding: const EdgeInsets.all(10),
                              decoration: BoxDecoration(
                                  color: Colors.white,
                                  border:
                                      Border.all(color: Colors.grey.shade400),
                                  borderRadius: BorderRadius.circular(10)),
                              child: const Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceEvenly,
                                children: [
                                  Icon(
                                    Icons.post_add_outlined,
                                    size: 40,
                                    color: Colors.grey,
                                  ),
                                  Text(
                                    'Dosya yüklemek için buraya tıklayın.\nDosya formatı PDF,PNG,JPG, GIF en \nfazla 10MB büyüklükte olacak...',
                                    style: TextStyle(
                                        color: Colors.grey,
                                        fontSize: 11,
                                        letterSpacing: 0.5),
                                    textAlign: TextAlign.left,
                                  ),
                                ],
                              )),
                          SizedBox(
                            height: context.dynamicHeight(0.03),
                          ),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.end,
                            children: [
                              arsivMi
                                  ? _unArchiveEmployeeButton()
                                  : _archiveEmployeeButton(),
                              SizedBox(width: context.dynamicWidth(0.04)),
                              _updateEmployeeButton(),
                            ],
                          ),
                        ],
                      ),
                    ),
                    SizedBox(
                      height: context.dynamicHeight(0.05),
                    ),
                  ],
                ),
              ),
            )
          : _isLoadingBar,
    );
  }

  AppBar appBar(BuildContext context) {
    return AppBar(
        backgroundColor: Colors.transparent,
        elevation: 0,
        title: Text('${widget.personel.firstName} ${widget.personel.lastName}',
            style: FontStyles.instance.appbarTitleStyle),
        centerTitle: true,
        actions: [
          IconButton(
              onPressed: () {},
              icon: const Icon(
                Icons.notifications_none_outlined,
                color: Colors.black,
              )),
        ],
        leading: IconButton(
          onPressed: () {
            FocusScope.of(context).unfocus();
            Navigator.pop(context, isUpdated);
          },
          icon: const Icon(
            Icons.arrow_back_ios_new,
            color: Colors.black87,
          ),
        ));
  }

  Widget _unArchiveEmployeeButton() {
    return SizedBox(
      height: context.dynamicHeight(0.05),
      width: context.dynamicWidth(0.33),
      child: TextButton(
        onPressed: () {
          context
              .read<EmployeeCubit>()
              .personelArsivdenCikar(
                  widget.personel.id ?? "0",
                  context.read<LoginCubit>().token,
                  context.read<LoginCubit>().id)
              .whenComplete(() {
            ToastManager.instance
                .toastMessageService('Personel Arşivden Çıkarıldı');
            Future.delayed(const Duration(milliseconds: 800), () {
              context
                  .read<EmployeeCubit>()
                  .personelListele(
                      context.read<LoginCubit>().userfirmId,
                      context.read<LoginCubit>().token,
                      context.read<LoginCubit>().id)
                  .whenComplete(() =>
                      Navigator.popUntil(context, (route) => route.isFirst));
            });
          });
        },
        style: TextButton.styleFrom(
          backgroundColor: ColorsConstants.instance.backgroundColor,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(10),
          ),
        ),
        child: Text(
          ApplicationConstants.instance.moduleUnArchiveTxt,
          style: const TextStyle(color: Colors.white),
        ),
      ),
    );
  }

  Widget _archiveEmployeeButton() {
    return SizedBox(
      height: context.dynamicHeight(0.05),
      width: context.dynamicWidth(0.25),
      child: TextButton(
        onPressed: () {
          context
              .read<EmployeeCubit>()
              .personelArsivle(
                  widget.personel.id ?? "0",
                  context.read<LoginCubit>().token,
                  context.read<LoginCubit>().id)
              .whenComplete(() {
            ToastManager.instance.toastMessageService('Personel Arşivlendi');
            Future.delayed(const Duration(milliseconds: 800), () {
              context
                  .read<EmployeeCubit>()
                  .personelListele(
                      context.read<LoginCubit>().userfirmId,
                      context.read<LoginCubit>().token,
                      context.read<LoginCubit>().id)
                  .whenComplete(() =>
                      Navigator.popUntil(context, (route) => route.isFirst));
            });
          });
        },
        style: TextButton.styleFrom(
          backgroundColor: ColorsConstants.instance.backgroundColor,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(10),
          ),
        ),
        child: Text(
          ApplicationConstants.instance.moduleArchiveTxt,
          style: const TextStyle(color: Colors.white),
        ),
      ),
    );
  }

  Widget _updateEmployeeButton() {
    return SizedBox(
      height: context.dynamicHeight(0.05),
      width: context.dynamicWidth(0.25),
      child: TextButton(
        onPressed: () {
          if (dbSaat == '') {
            ToastManager.instance.toastMessageService('İşe Girih Tarihi Seçin');
          }
          if (tfAdres.text == '') {
            ToastManager.instance.toastMessageService('Adres Girin');
          }
          if (tfAd.text != 'geçersiz' &&
              tfAd.text != '' &&
              tfSoyad.text != 'geçersiz' &&
              tfSoyad.text != '' &&
              tfMail.text != 'geçersiz' &&
              tfMail.text != '' &&
              tfSifre.text != 'geçersiz' &&
              tfSifre.text != '' &&
              tfCepTel.text != 'geçersiz' &&
              tfCepTel.text != '' &&
              tfTCNo.text != 'geçersiz' &&
              tfTCNo.text != '' &&
              tfAdres.text != 'geçersiz' &&
              tfAdres.text != '' &&
              dbSaat != '') {
            context.read<EmployeeCubit>().personelGuncelle(
                widget.personel.id!,
                context.read<LoginCubit>().userfirmId,
                tfAd.text,
                tfSoyad.text,
                tfMail.text,
                tfSifre.text,
                tfCepTel.text,
                tfAdres.text,
                dbSaat,
                tfTCNo.text,
                secilenAskerlik!,
                gonderilenUnvanID,
                context.read<LoginCubit>().token,
                context.read<LoginCubit>().id,
                context.read<LoginCubit>().tip);
            if (uploadimage != null) {
              //uploadimage yeni fotoğraf seçildiyse yeni seçilen fotoğrafı servera yükle... değilse hiçbir şey yapma..
              uploadImage(
                  uploadimage!,
                  widget.personel.id!,
                  context.read<LoginCubit>().id,
                  context.read<LoginCubit>().tip,
                  context.read<LoginCubit>().userfirmId,
                  context.read<LoginCubit>().token,
                  widget.personel.email!,
                  widget.personel.image!);
            }
            isUpdated = true;
            ToastManager.instance.toastMessageService('Personel Güncellendi !');
            Future.delayed(const Duration(seconds: 2), () {
              Navigator.pushNamed(context, '/');
            });
          } else {
            ToastManager.instance
                .toastMessageService('Personel Güncellenemedi');
          }
          //////////////////////////////////////////////////
        },
        style: TextButton.styleFrom(
          backgroundColor: ColorsConstants.instance.baseTheme,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(10),
          ),
        ),
        child: Text(
          ApplicationConstants.instance.moduleUpdateTxt,
          style: const TextStyle(color: Colors.white),
        ),
      ),
    );
  }

  Widget get _isLoadingBar => const Center(
        child: CircularProgressIndicator(),
      );

  Widget _headLine(String headline, BuildContext context,
      {bool isRequired = true}) {
    return Row(
      children: [
        Text(
          headline,
          style: TextStyle(
              color: ColorsConstants.instance.baseTheme,
              fontSize: 11,
              fontWeight: FontWeight.w500),
        ),
        Row(
          children: [
            SizedBox(
              width: context.dynamicWidth(0.01),
            ),
            Text(
              isRequired ? '(*)' : '',
              style: FontStyles.instance.employeetbxRequired,
            )
          ],
        )
      ],
    );
  }

  dateTimePickerWidget(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(
          'Yeni Tarih Seç',
          style: TextStyle(color: ColorsConstants.instance.baseTheme),
        ),
      ),
      onMonthChangeStartWithFirstDate: true,
      onConfirm: (dateTime, List<int> index) {
        DateTime selectdate = dateTime;
        final selIOS = DateFormat('yyyy-MM-dd HH:mm').format(selectdate);
        setState(() {
          dbSaat = '$selIOS:00';
          gosterilenSaat = dbSaat.substring(0, 16);
          final DateFormat format = DateFormat.yMd('tr');
          var trTarih = format.format(DateTime.parse(gosterilenSaat));
          gosterilenSaat = trTarih;
          debugPrint(dbSaat);
          debugPrint(gosterilenSaat);
        });
      },
    );
  }
}
