import 'package:dropdown_button2/dropdown_button2.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:hamlemuhcrm/core/extensions/log_extension.dart';
import 'package:hamlemuhcrm/core/extensions/responsive_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/permissions/cubit/permission_cubit.dart';
import '../../../core/constants/color_constants.dart';
import '../../../core/constants/font_styles.dart';
import '../../auth/login/cubit/login_cubit.dart';
import 'permission_request_page.dart';
import 'dart:convert';

import 'package:dio/dio.dart';

mixin PermissionRequestPageMixin on State<PermissionRequestPage> {
  late FToast fToast;

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

  final String baseURL = URLAPIService.baseURL;
  String? secilenYerineBakacakCalisan;
  String gonderilenYerineBakacakCalisanID = "";
  Map<String, dynamic>? gelenCalisan;

  String? secilenOnayYetkiliID;
  String gonderilenOnayYetkiliID = "";
  Map<String, dynamic>? gelenYetkililer;

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

  Widget calisanDD() {
    List<CalisanDDModel> calisanListesi = List<CalisanDDModel>.from(
      gelenCalisan?["users"].map(
        (i) {
          return CalisanDDModel.fromJSON(i);
        },
      ),
    );

    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,
        onChanged: (newValue) {
          //YERİNE BAKACAK PERSONEL ID
          setState(() {
            secilenYerineBakacakCalisan = newValue.toString();
            gonderilenYerineBakacakCalisanID = secilenYerineBakacakCalisan!;
            "_secilen CalisanID == $secilenYerineBakacakCalisan".log();
          });
        },
        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,
        ),
        dropdownStyleData: DropdownStyleData(
          maxHeight: context.dynamicHeight(0.17),
          isOverButton: false,
          width: context.dynamicWidth(0.9),
          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> calisanYetkiliData(
      String userfirm, String token, String loginuserid) async {
    var yetkiliURL = "$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,
        onChanged: (newValue) {
          //İZNİ ONAYLAYACAK PERSONEL ID
          setState(() {
            secilenOnayYetkiliID = newValue.toString();
            //_selected2 = "";
            gonderilenOnayYetkiliID = secilenOnayYetkiliID!; //medium new
            "seçilen onayYetkiliID == $secilenOnayYetkiliID".log();
          });
        },
        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,
        ),
        dropdownStyleData: DropdownStyleData(
          maxHeight: context.dynamicHeight(0.17),
          isOverButton: false,
          width: context.dynamicWidth(0.9),
          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),
        ),
      ),
    );
  }

  bool isFinish = false;

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

  final GlobalKey<FormState> permissionsKey = GlobalKey<FormState>();

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

  Future<void> ddCek() async {
    isFinish = false;
    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, userfirmid);
    await calisanYetkiliData(userfirmid, token, loginid);
    isFinish = true;
  }

  Future<bool> isDone(String permissiontype) async {
    String permissionDay =
        context.read<LoginCubit>().kalanyillikizinhakkigunsayisi;
    bool isDayDone = (int.tryParse(permissionDay)! < 1);
    bool isDone = await isCorrect(tarihUygun, gonderilenOnayYetkiliID,
        tfAciklama.text, dbSaatbaslangic, dbSaatbitis);

    if (isDone) {
      _showSnackBarMsg("Eksik Alanlar Mevcut !");
      return false;
    }

    switch (permissiontype) {
      case "0":
        if (permissionDay.isNotEmpty && isDayDone && permissionDay == '0') {
          _showSnackBarMsg("İzin hakkınız bulunmamakta !");
          return false;
        } else if (permissionDay.isNotEmpty && permissionDay == '00') {
          _showSnackBarMsg("İşe giriş tarihiniz kayıtlı değil !");
          return false;
        } else {
          return true;
        }
      case "1":
        return true;
    }
    return true;
  }

  Future<void> sendPermission() async {
    final permissionCubit = context.read<PermissionCubit>();
    final loginCubit = context.read<LoginCubit>();
    bool isComplete = await isDone(secilenIzinTipi ?? '0');
    if (isComplete) {
      permissionCubit
          .izinTalepEt(
              loginCubit.userfirmId,
              loginCubit.id,
              dbSaatbaslangic,
              dbSaatbitis,
              secilenIzinTipi ?? '1',
              gonderilenYerineBakacakCalisanID,
              gonderilenOnayYetkiliID,
              tfAciklama.text,
              loginCubit.token)
          .whenComplete(() {
        Future.delayed(const Duration(seconds: 1), () {
          Navigator.popUntil(context, (route) => route.isFirst);
        });
      });
    }
  }

  Future<bool> isCorrect(bool isDateDone, String gonderilenOnayYetkiliId,
      String tfAciklama, String dbTimeStart, String dbTimeEnd) async {
    //Scenario 1
    if (isDateDone != true ||
        gonderilenOnayYetkiliId.isEmpty ||
        tfAciklama.isEmpty ||
        dbTimeStart.isEmpty ||
        dbTimeEnd.isEmpty) {
      return true;
    }
    return false;
  }

  void _showSnackBarMsg(String msg) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        backgroundColor: ColorsConstants.instance.baseTheme,
        behavior: SnackBarBehavior.floating,
        content: Text(
          msg,
        ),
      ),
    );
  }

  @override
  void initState() {
    'kalan hak : ${widget.kalanHak}'.log();
    fToast = FToast();
    fToast.init(context);
    ddCek();
    super.initState();
  }

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