import 'dart:convert';

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:intl/intl.dart';
import 'package:hamlemuhcrm/core/extensions/image_enum_extension.dart';
import 'package:hamlemuhcrm/core/extensions/log_extension.dart';
import 'package:hamlemuhcrm/data/dropdown_models/personal_getdata_api.dart';
import 'package:hamlemuhcrm/core/constants/url_services_constant.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:hamlemuhcrm/features/profile/model/profile_permission.dart';

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

class ProfilePermissionDetail extends StatefulWidget {
  final ProfilePermission izinler;

  const ProfilePermissionDetail({super.key, required this.izinler});

  @override
  State<ProfilePermissionDetail> createState() =>
      _ProfilePermissionDetailState();
}

class _ProfilePermissionDetailState extends State<ProfilePermissionDetail> {
  bool isFinish = false;
  bool mazeretMi = false;

  String? secilenIzinTipi = "0";
  String dbSaatbaslangic = '';
  String dbSaatbitis = '';
  String gosterilenSaatbaslangic = '';
  String gosterilenSaatbitis = '';
  DateTime birincidateTime = DateTime.now();
  DateTime ikincidateTime = DateTime.now();
  final tfAciklama = TextEditingController();
  final DateFormat format = DateFormat.yMd('tr');

  final Map<String, String> izinTipiDD = {
    '0': 'Yıllık İzin',
    '1': 'Mazeret İzni',
    // '2': 'Doğum İzni',
    // '3': 'Rapor İzni',
    // '4': 'Evlilik İzni',
    // '5': 'Ücretli İzin',
    // '6': 'Ücretsiz İzin',
  };
  String? secilenYerineBakacakCalisan;

  Map<String, dynamic>? gelenCalisan;

  String? secilenOnayYetkiliID;
  Map<String, dynamic>? gelenYetkililer;

  Future<void> calisanData(String token, String loginuserid) async {
    var calisanURL =
        "${URLAPIService.baseURL}/mobil/api/dd/personel_dd_pdo.php";
    var veri = {"token": token, "loginuserid": loginuserid};
    var cevapCalisan =
        await Dio().post(calisanURL, data: FormData.fromMap(veri));
    if (cevapCalisan.statusCode == 200) {
      setState(() {
        gelenCalisan = json.decode(cevapCalisan.data); //
      });
    } else {}
  }

  Widget calisanDD() {
    List<CalisanDDModel> calisanListesi = [];
    if (gelenCalisan != null && gelenCalisan?["users"] != null) {
      calisanListesi = List<CalisanDDModel>.from(
        gelenCalisan?["users"].map(
          (i) {
            return CalisanDDModel.fromJSON(i);
          },
        ),
      );
      // Geri kalan kod...
    } else {
      'Hata: gelenCalisan veya users alanı null'.log();
      // Gerekirse, null olduğunda yapılması gereken işlemleri burada gerçekleştirin.
    }

    return DropdownButtonHideUnderline(
      child: DropdownButton2(
        hint: const Text(
          "",
          style: TextStyle(fontSize: 12, color: Colors.black54),
        ), //Data1
        isExpanded: true,
        items: calisanListesi.map((calisan) {
          return DropdownMenuItem(
            value: calisan.id,
            child: Text('${calisan.firstName} ${calisan.lastName}',
                style: FontStyles.instance.ddYazi), //value
          );
        }).toList(),
        value: secilenYerineBakacakCalisan,
        buttonStyleData: ButtonStyleData(
          height: context.dynamicHeight(0.05),
          width: context.dynamicWidth(1),
          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,
        ),
      ),
    );
  }

  Future<void> calisanYetkiliData(
      String userfirm, String token, String loginuserid) async {
    var yetkiliURL =
        "${URLAPIService.baseURL}/mobil/api/dd/calisan_yetkililer_pdo.php";
    var veri = {
      "user_userfirm_id": userfirm,
      "token": token,
      "loginuserid": loginuserid
    };
    var cevapYetkililer =
        await Dio().post(yetkiliURL, data: FormData.fromMap(veri));
    if (cevapYetkililer.statusCode == 200) {
      setState(() {
        gelenYetkililer = json.decode(cevapYetkililer.data.toString());
      });
    } else {}
  }

  Widget calisanYetkiliDD() {
    List<CalisanYetkiliDDModel> calisanyetkiliListesi = [];
    if (gelenYetkililer != null && gelenYetkililer?["users"] != null) {
      calisanyetkiliListesi = List<CalisanYetkiliDDModel>.from(
        gelenYetkililer?["users"].map(
          (i) {
            return CalisanYetkiliDDModel.fromJSON(i);
          },
        ),
      );
      // Geri kalan kod...
    } else {
      'Hata: gelenCalisan veya users alanı null'.log();
      // Gerekirse, null olduğunda yapılması gereken işlemleri burada gerçekleştirin.
    }

    return DropdownButtonHideUnderline(
      child: DropdownButton2(
        hint: const Text(
          "",
          style: TextStyle(fontSize: 13, color: Colors.black54),
        ),
        isExpanded: true,
        items: calisanyetkiliListesi.map((yetkili) {
          return DropdownMenuItem(
            value: yetkili.id,
            child: Text(
              '${yetkili.firstName} ${yetkili.lastName}',
              style: FontStyles.instance.ddYazi,
            ), //DATA SENDING
          );
        }).toList(),
        value: secilenOnayYetkiliID,
        buttonStyleData: ButtonStyleData(
          height: context.dynamicHeight(0.05),
          width: context.dynamicWidth(1),
          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,
        ),
      ),
    );
  }

  Future<void> ddCek() async {
    final String token = context.read<LoginCubit>().token;
    final String loginId = context.read<LoginCubit>().id;
    final String userfirmId = context.read<LoginCubit>().userfirmId;
    await calisanData(token, loginId);
    await calisanYetkiliData(userfirmId, token, loginId);
  }

  @override
  void initState() {
    isFinish = false;
    ddCek().whenComplete(() {
      tfAciklama.text = widget.izinler.izinAciklama ?? '';
      secilenIzinTipi = widget.izinler.izinTipi ?? '0';
      if (widget.izinler.izinOnayUserId != '0') {
        secilenOnayYetkiliID = widget.izinler.izinOnayUserId;
      }
      if (widget.izinler.izinYerineBakacakUser != "0") {
        secilenYerineBakacakCalisan = widget.izinler.izinYerineBakacakUser;
      }
      dbSaatbaslangic = widget.izinler.izinBaslamaTarihi!;
      String trTarihBaslangic = format.format(DateTime.parse(dbSaatbaslangic));
      gosterilenSaatbaslangic = trTarihBaslangic;
      dbSaatbitis = widget.izinler.izinIsbasiTarihi!;
      String trTarihBitis = format.format(DateTime.parse(dbSaatbitis));
      gosterilenSaatbitis = trTarihBitis;
      isFinish = true;
    });
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext permissionpageContext) {
    return isFinish
        ? Scaffold(
            appBar: _appBar(permissionpageContext),
            body: Center(
              child: SingleChildScrollView(
                child: Column(
                  children: [
                    SizedBox(
                        height: permissionpageContext.dynamicHeight(0.2),
                        child: ImageEnums.leave.toPageImage),
                    SizedBox(
                      height: permissionpageContext.dynamicHeight(0.04),
                    ),
                    Padding(
                      padding: EdgeInsets.symmetric(
                          horizontal: permissionpageContext
                              .dynamicWidth(0.05)), //kenar boslukları
                      child: Column(
                        children: [
                          const SizedBox(height: 15),
                          _headLine('İzin Tipi'),
                          _emptySpace,
                          DropdownButtonHideUnderline(
                            child: DropdownButton2(
                              isExpanded: true,
                              value: secilenIzinTipi,
                              items: izinTipiDD.entries
                                  .map((entry) => DropdownMenuItem<String>(
                                        value: entry.key,
                                        child: Text(
                                          entry.value,
                                          style: FontStyles.instance.ddYazi,
                                        ),
                                      ))
                                  .toList(),
                              buttonStyleData: ButtonStyleData(
                                height:
                                    permissionpageContext.dynamicHeight(0.05),
                                width: permissionpageContext.dynamicWidth(1),
                                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,
                              ),
                            ),
                          ),
                          _emptySpace,
                          _headLine('Yerine Bakacak Personel'),
                          _emptySpace,
                          calisanDD(),
                          _emptySpace,
                          Row(
                            children: [
                              Text(
                                'İzni Onaylayacak Personel',
                                style: FontStyles.instance.employeetbxBaslik,
                              ),
                            ],
                          ),
                          _emptySpace,
                          calisanYetkiliDD(),
                          _emptySpace,
                          _headLine('İzin Başlangıç Tarihi'),
                          _emptySpace,
                          Container(
                            height: permissionpageContext.dynamicHeight(0.055),
                            width: permissionpageContext.dynamicWidth(1),
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(10),
                              color: Colors.white,
                              border: Border.all(color: Colors.black26),
                            ),
                            child: Row(
                              children: [
                                const SizedBox(width: 10),
                                Text(
                                  gosterilenSaatbaslangic,
                                  style: FontStyles.instance.ddYazi,
                                ),
                                const Spacer(),
                                Container(
                                    height: permissionpageContext
                                        .dynamicHeight(0.05),
                                    width:
                                        permissionpageContext.dynamicWidth(0.1),
                                    decoration: BoxDecoration(
                                        color:
                                            ColorsConstants.instance.baseTheme,
                                        borderRadius:
                                            BorderRadius.circular(10)),
                                    child: Icon(
                                      Icons.calendar_month,
                                      size: 23,
                                      color: Colors.white.withOpacity(0.9),
                                    )),
                              ],
                            ),
                          ),
                          _emptySpace,
                          _headLine('İzin Bitiş Tarihi'),
                          _emptySpace,
                          Container(
                            height: permissionpageContext.dynamicHeight(0.055),
                            width: permissionpageContext.dynamicWidth(1),
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(10),
                              color: Colors.white,
                              border: Border.all(color: Colors.black26),
                            ),
                            child: Row(
                              children: [
                                const SizedBox(width: 10),
                                Text(
                                  gosterilenSaatbitis,
                                  style: FontStyles.instance.ddYazi,
                                ),
                                const Spacer(),
                                Container(
                                    height: permissionpageContext
                                        .dynamicHeight(0.05),
                                    width:
                                        permissionpageContext.dynamicWidth(0.1),
                                    decoration: BoxDecoration(
                                        color:
                                            ColorsConstants.instance.baseTheme,
                                        borderRadius:
                                            BorderRadius.circular(10)),
                                    child: Icon(
                                      Icons.calendar_month,
                                      size: 23,
                                      color: Colors.white.withOpacity(0.9),
                                    )),
                              ],
                            ),
                          ),
                          _emptySpace,
                          _headLine('Açıklama'),
                          SizedBox(
                            height: permissionpageContext.dynamicHeight(0.01),
                          ),
                          Container(
                            height: permissionpageContext.dynamicHeight(0.15),
                            width: permissionpageContext.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,
                              enabled: false,
                              controller: tfAciklama,
                              decoration: const InputDecoration(
                                  border: InputBorder.none),
                            ),
                          ),
                          SizedBox(
                            height: permissionpageContext.dynamicHeight(0.01),
                          ),
                        ],
                      ),
                    ),
                    SizedBox(
                      height: context.dynamicHeight(0.02),
                    ),
                  ],
                ),
              ),
            ),
          )
        : const Scaffold();
  }

  Widget get _emptySpace => const SizedBox(height: 8);

  Widget _headLine(String title) {
    return Row(
      children: [
        Text(
          title,
          style: FontStyles.instance.employeetbxBaslik,
        ),
      ],
    );
  }

  AppBar _appBar(BuildContext permissionpageContext) {
    return AppBar(
        backgroundColor: Colors.transparent,
        elevation: 0,
        title: Text('Cevaplanmış İzin',
            style: FontStyles.instance.appbarTitleStyle),
        centerTitle: true,
        actions: [
          IconButton(
              onPressed: () {},
              icon: const Icon(
                Icons.notifications_none_outlined,
                color: Colors.black,
              )),
        ],
        leading: IconButton(
          onPressed: () {
            FocusScope.of(permissionpageContext).unfocus();
            Navigator.pop(permissionpageContext);
          },
          icon: const Icon(
            Icons.arrow_back_ios_new,
            color: Colors.black87,
          ),
        ));
  }
}
