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:fluttertoast/fluttertoast.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/features/permissions/model/izinler.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/features/permissions/cubit/permission_cubit.dart';
import 'package:hamlemuhcrm/core/constants/font_styles.dart';
import 'package:hamlemuhcrm/core/extensions/responsive_extension.dart';

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

class PermissionsConfirmPage extends StatefulWidget {
  final Izinler izinler;

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

  @override
  State<PermissionsConfirmPage> createState() => _PermissionsConfirmPageState();
}

class _PermissionsConfirmPageState extends State<PermissionsConfirmPage> {
  late FToast _fToast;
  final String baseURL = URLAPIService.baseURL;

  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 anahtarKelime = 'izinTalepSayfasi';
  bool isFinish = false;

  bool baslangicSecildi = false;
  bool tarihUygun = false;
  bool mazeretMi = false;
  int tarihlerArasiGunFark = 0;

  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');

  String? secilenYerineBakacakCalisan;
  String gonderilenYerineBakacakCalisanID = "";
  Map<String, dynamic>? gelenCalisan;

  String? secilenOnayYetkiliID;
  String gonderilenOnayYetkiliID = "";
  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));
    //print(res02);

    if (cevapYetkililer.statusCode == 200) {
      setState(() {
        gelenYetkililer = json.decode(cevapYetkililer.data.toString());
        //print(data_02);
      });
    } else {}
  }

  Widget calisanYetkiliDD() {
    List<CalisanYetkiliDDModel> calisanyetkiliListesi =
        List<CalisanYetkiliDDModel>.from(gelenYetkililer?['users'].map((i) {
      return CalisanYetkiliDDModel.fromJSON(i);
    }));

    return DropdownButtonHideUnderline(
      child: DropdownButton2(
        hint: const Text(
          "",
          style: TextStyle(fontSize: 13, color: Colors.black54),
        ), //Data2, Regency
        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 userfirmid = context.read<LoginCubit>().userfirmId;
    final String token = context.read<LoginCubit>().token;
    final String loginid = context.read<LoginCubit>().id;
    await calisanData(token, loginid);
    await calisanYetkiliData(userfirmid, token, loginid);
  }

  @override
  void initState() {
    super.initState();
    isFinish = false;
    _fToast = FToast();
    _fToast.init(context);
    ddCek().whenComplete(() {
      tfAciklama.text = widget.izinler.izinAciklama ?? '';
      secilenIzinTipi = widget.izinler.izinTipi ?? '0';
      if (widget.izinler.izinOnayUserId != '0') {
        secilenOnayYetkiliID = widget.izinler.izinOnayUserId;
        gonderilenOnayYetkiliID = widget.izinler.izinOnayUserId ?? '0';
      }
      if (widget.izinler.izinYerineBakacakUser != '0') {
        secilenYerineBakacakCalisan = widget.izinler.izinYerineBakacakUser;
        gonderilenYerineBakacakCalisanID =
            widget.izinler.izinYerineBakacakUser ?? '0';
      }
      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;
    });
  }

  @override
  void dispose() {
    _fToast.removeQueuedCustomToasts();
    _fToast.removeCustomToast();
    Fluttertoast.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext permissionpageContext) {
    return isFinish
        ? Scaffold(
            appBar: AppBar(
                backgroundColor: Colors.transparent,
                elevation: 0,
                title: Text('İzin Talebi',
                    style: FontStyles.instance.appbarTitleStyle),
                centerTitle: true,
                leading: IconButton(
                  onPressed: () {
                    FocusScope.of(permissionpageContext).unfocus();
                    Navigator.pop(permissionpageContext);
                  },
                  icon: const Icon(
                    Icons.arrow_back_ios_new,
                    color: Colors.black87,
                  ),
                )),
            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),
                          Row(
                            children: [
                              Text(
                                'İzin Tipi',
                                style: FontStyles.instance.employeetbxBaslik,
                              ),
                              SizedBox(
                                width: permissionpageContext.dynamicWidth(0.01),
                              ),
                              Text(
                                '(zorunlu)',
                                style: FontStyles.instance.employeetbxRequired,
                              )
                            ],
                          ),
                          const SizedBox(height: 8),
                          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,
                              ),
                            ),
                          ),
                          const SizedBox(height: 8),
                          Row(
                            children: [
                              Text(
                                'Yerine Bakacak Personel',
                                style: FontStyles.instance.employeetbxBaslik,
                              ),
                            ],
                          ),
                          const SizedBox(height: 8),
                          calisanDD(),
                          const SizedBox(height: 8),
                          Row(
                            children: [
                              Text(
                                'İzni Onaylayacak Personel',
                                style: FontStyles.instance.employeetbxBaslik,
                              ),
                              SizedBox(
                                width: permissionpageContext.dynamicWidth(0.01),
                              ),
                              Text(
                                '(zorunlu)',
                                style: FontStyles.instance.employeetbxRequired,
                              )
                            ],
                          ),
                          const SizedBox(height: 8),
                          calisanYetkiliDD(),
                          const SizedBox(height: 8),
                          Row(
                            children: [
                              Text(
                                'İzin Başlangıç Tarihi',
                                style: FontStyles.instance.employeetbxBaslik,
                              ),
                              SizedBox(
                                width: permissionpageContext.dynamicWidth(0.01),
                              ),
                              Text(
                                '(zorunlu)',
                                style: FontStyles.instance.employeetbxRequired,
                              )
                            ],
                          ),
                          const SizedBox(height: 8),
                          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),
                                    )),
                              ],
                            ),
                          ),
                          const SizedBox(height: 8),
                          _headLine('İzin Bitiş Tarihi'),
                          const SizedBox(height: 8),
                          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: baslangicSecildi
                                        ? IconButton(
                                            padding: const EdgeInsets.all(0),
                                            onPressed: () {
                                              //dateTimePickerWidget2(permissionpageContext);
                                            },
                                            tooltip: 'İzin Bitiş Tarihi Seç',
                                            icon: Icon(
                                              Icons.calendar_month,
                                              size: 23,
                                              color:
                                                  Colors.white.withOpacity(0.9),
                                            ))
                                        : Icon(
                                            Icons.calendar_month,
                                            size: 23,
                                            color:
                                                Colors.white.withOpacity(0.9),
                                          )),
                              ],
                            ),
                          ),
                          const SizedBox(height: 8),
                          _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(
                              enabled: false,
                              inputFormatters: [
                                LengthLimitingTextInputFormatter(300)
                              ],
                              textInputAction: TextInputAction.next,
                              maxLines: 5,
                              style: FontStyles.instance.employeetbxYazi,
                              cursorColor: ColorsConstants.instance.baseTheme,
                              controller: tfAciklama,
                              decoration: const InputDecoration(
                                  border: InputBorder.none),
                            ),
                          ),
                          SizedBox(
                            height: permissionpageContext.dynamicHeight(0.01),
                          ),
                          mazeretMi
                              ? Column(
                                  children: [
                                    Row(
                                      children: [
                                        Text(
                                          'Dosya',
                                          style: FontStyles
                                              .instance.employeetbxBaslik,
                                        ),
                                      ],
                                    ),
                                    SizedBox(
                                      height: permissionpageContext
                                          .dynamicHeight(0.01),
                                    ),
                                    Container(
                                        height: permissionpageContext
                                            .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.',
                                              style: TextStyle(
                                                  color: Colors.grey,
                                                  fontSize: 11,
                                                  letterSpacing: 0.5),
                                              textAlign: TextAlign.left,
                                            ),
                                          ],
                                        )),
                                  ],
                                )
                              : const SizedBox(),
                          SizedBox(
                            height: permissionpageContext.dynamicHeight(0.03),
                          ),
                        ],
                      ),
                    ),
                    widget.izinler.izinOnayUserId ==
                            context.read<LoginCubit>().id
                        ? SizedBox(
                            height: permissionpageContext.dynamicHeight(0.05),
                            width: permissionpageContext.dynamicWidth(0.30),
                            child: TextButton(
                              onPressed: () {
                                _showConfirmPermissionDialog(
                                    permissionpageContext);
                              },
                              style: TextButton.styleFrom(
                                backgroundColor:
                                    ColorsConstants.instance.baseTheme,
                              ),
                              child: const Text(
                                'İzni Cevapla',
                                style: TextStyle(color: Colors.white),
                              ),
                            ),
                          )
                        : Container(
                            height: permissionpageContext.dynamicHeight(0.05),
                            width: permissionpageContext.dynamicWidth(0.30),
                            decoration: BoxDecoration(
                                color: ColorsConstants.instance.baseTheme,
                                borderRadius: BorderRadius.circular(20)),
                            child: const Text("Karar Verme Yetkiniz Yok",
                                style: TextStyle(color: Colors.white)),
                          ),
                    SizedBox(
                      height: context.dynamicHeight(0.02),
                    ),
                  ],
                ),
              ),
            ),
          )
        : const Scaffold();
  }

  void _showConfirmPermissionDialog(BuildContext permissionpageContext) {
    showDialog(
        context: permissionpageContext,
        builder: (context) {
          return AlertDialog(
            shape: const RoundedRectangleBorder(
                borderRadius: BorderRadius.all(Radius.circular(15))),
            content: SizedBox(
              height: context.dynamicHeight(0.44),
              width: context.dynamicWidth(0.85),
              child: Column(
                children: [
                  Row(
                    children: [
                      Text(
                        'İzni Onayla',
                        style: TextStyle(
                            fontSize: 12, color: Colors.grey.shade600),
                      ),
                      const Spacer(),
                      InkWell(
                        onTap: () => Navigator.pop(context),
                        child: const Icon(Icons.close_rounded,
                            size: 12, color: Colors.black87),
                      ),
                    ],
                  ),
                  Divider(
                    color: Colors.black.withOpacity(0.7),
                  ),
                  SizedBox(
                      height: context.dynamicHeight(0.23),
                      child: ImageEnums.question.toPageImage),
                  SizedBox(
                    height: context.dynamicHeight(0.04),
                  ),
                  Text(
                    '${'${widget.izinler.izinAlanAd!} ${widget.izinler.izinAlanSoyad!}'} için izin talebini cevaplayın',
                    style:
                        TextStyle(color: Colors.orange.shade900, fontSize: 14),
                    textAlign: TextAlign.center,
                  ),
                  SizedBox(
                    height: context.dynamicHeight(0.04),
                  ),
                  const Text(
                    "Onaylayın veya reddedin, geçerli sayfada kalmak için çarpıya veya yan tarafa dokunun ",
                    style: TextStyle(color: Colors.black, fontSize: 11),
                    textAlign: TextAlign.center,
                  ),
                ],
              ),
            ),
            actions: [
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  SizedBox(
                    height: context.dynamicHeight(0.05),
                    width: context.dynamicWidth(0.25),
                    child: TextButton(
                      onPressed: () {
                        context
                            .read<PermissionCubit>()
                            .izniCevapla(
                                widget.izinler.izinId!,
                                '3',
                                context.read<LoginCubit>().token,
                                context.read<LoginCubit>().id)
                            .whenComplete(() {
                          Future.delayed(const Duration(milliseconds: 800), () {
                            Navigator.popUntil(
                                context, (route) => route.isFirst);
                          });
                        });
                      },
                      style: TextButton.styleFrom(
                          backgroundColor: Colors.orange.shade900,
                          side:
                              BorderSide(color: Colors.black.withOpacity(0.3))),
                      child: const Text(
                        'Onayla',
                        style: TextStyle(color: Colors.white),
                      ),
                    ),
                  ),
                  SizedBox(
                    width: context.dynamicWidth(0.05),
                  ),
                  SizedBox(
                    height: context.dynamicHeight(0.05),
                    width: context.dynamicWidth(0.25),
                    child: TextButton(
                      onPressed: () {
                        context
                            .read<PermissionCubit>()
                            .izniCevapla(
                                widget.izinler.izinId!,
                                '2',
                                context.read<LoginCubit>().token,
                                context.read<LoginCubit>().id)
                            .whenComplete(() {
                          Future.delayed(const Duration(milliseconds: 800), () {
                            Navigator.popUntil(
                                context, (route) => route.isFirst);
                          });
                        });
                      },
                      style: TextButton.styleFrom(
                        backgroundColor: Colors.grey.shade300,
                        side: BorderSide(color: Colors.black.withOpacity(0.3)),
                      ),
                      child: Text(
                        'Reddet',
                        style: TextStyle(color: Colors.orange.shade900),
                      ),
                    ),
                  ),
                  SizedBox(
                    height: context.dynamicHeight(0.1),
                  ),
                ],
              ),
            ],
          );
        });
  }

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