import 'package:dropdown_button2/dropdown_button2.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_cupertino_datetime_picker/flutter_cupertino_datetime_picker.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:intl/intl.dart';
import 'package:hamlemuhcrm/core/extensions/log_extension.dart';
import '../../../core/extensions/image_enum_extension.dart';
import '../../../core/constants/font_styles.dart';
import '../../../core/extensions/responsive_extension.dart';

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

class PermissionRequestPage extends StatefulWidget {
  final String kalanHak;

  const PermissionRequestPage({super.key, required this.kalanHak});

  @override
  State<PermissionRequestPage> createState() => _PermissionRequestPageState();
}

class _PermissionRequestPageState extends State<PermissionRequestPage>
    with PermissionRequestPageMixin {
  @override
  Widget build(BuildContext context) {
    return isFinish
        ? Scaffold(
            appBar: AppBar(
                backgroundColor: Colors.transparent,
                elevation: 0,
                title: Text('İzin Talep Et',
                    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);
                  },
                  icon: const Icon(
                    Icons.arrow_back_ios_new,
                    color: Colors.black87,
                  ),
                )),
            body: Center(
              child: SingleChildScrollView(
                child: Column(
                  children: [
                    SizedBox(
                        height: context.dynamicHeight(0.2),
                        child: ImageEnums.leave.toPageImage),
                    SizedBox(
                      height: context.dynamicHeight(0.04),
                    ),
                    Padding(
                      padding: EdgeInsets.symmetric(
                          horizontal:
                              context.dynamicWidth(0.05)), //kenar boslukları
                      child: Column(
                        children: [
                          Container(
                            height: context.dynamicHeight(0.05),
                            decoration: const BoxDecoration(color: Colors.grey),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceAround,
                              children: [
                                const Text(
                                  'Kalan Yıllık İzin Hakkı',
                                  style: TextStyle(
                                      color: Colors.white,
                                      fontSize: 14,
                                      fontWeight: FontWeight.w500),
                                ),
                                const SizedBox(width: 12),
                                Text(widget.kalanHak,
                                    style: const TextStyle(
                                        color: Colors.white,
                                        fontSize: 17,
                                        fontWeight: FontWeight
                                            .w800)), //BURAYA KİŞİNİN KULLANABİLECEĞİ YILLIK İZİN HAKKI GELECEK...
                              ],
                            ),
                          ),
                          const SizedBox(height: 15),
                          Row(
                            children: [
                              Text(
                                'İzin Tipi',
                                style: FontStyles.instance.employeetbxBaslik,
                              ),
                              SizedBox(
                                width: context.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(),
                              onChanged: (value) {
                                secilenIzinTipi = value;
                                //eğer mazeret izni seçiliyorsa mazeret sebebi ile ilgili bir rapor ekleyebilir....
                                setState(() {
                                  secilenIzinTipi == '1'
                                      ? mazeretMi = true
                                      : mazeretMi = false;
                                });
                                'Seçilen Deger DD : $secilenIzinTipi'.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),
                              ),
                            ),
                          ),
                          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: context.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: context.dynamicWidth(0.01),
                              ),
                              Text(
                                '(zorunlu)',
                                style: FontStyles.instance.employeetbxRequired,
                              )
                            ],
                          ),
                          const SizedBox(height: 8),
                          Container(
                            height: context.dynamicHeight(0.055),
                            width: context.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: context.dynamicHeight(0.05),
                                  width: context.dynamicWidth(0.1),
                                  decoration: BoxDecoration(
                                      color: ColorsConstants.instance.baseTheme,
                                      borderRadius: BorderRadius.circular(10)),
                                  child: IconButton(
                                      padding: const EdgeInsets.all(0),
                                      onPressed: () {
                                        dateTimePickerWidget1(context);
                                      },
                                      tooltip: 'İzin Başlangıç Tarihi Seç',
                                      icon: Icon(
                                        Icons.calendar_month,
                                        size: 23,
                                        color: Colors.white.withOpacity(0.9),
                                      )),
                                ),
                              ],
                            ),
                          ),
                          const SizedBox(height: 8),
                          Row(
                            children: [
                              Text(
                                'İzin Bitiş Tarihi',
                                style: FontStyles.instance.employeetbxBaslik,
                              ),
                              SizedBox(
                                width: context.dynamicWidth(0.01),
                              ),
                              Text(
                                '(zorunlu)',
                                style: FontStyles.instance.employeetbxRequired,
                              )
                            ],
                          ),
                          const SizedBox(height: 8),
                          Container(
                            height: context.dynamicHeight(0.055),
                            width: context.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: context.dynamicHeight(0.05),
                                    width: context.dynamicWidth(0.1),
                                    decoration: BoxDecoration(
                                        color:
                                            ColorsConstants.instance.baseTheme,
                                        borderRadius:
                                            BorderRadius.circular(10)),
                                    child: baslangicSecildi
                                        ? IconButton(
                                            padding: const EdgeInsets.all(0),
                                            onPressed: () {
                                              dateTimePickerWidget2(context);
                                            },
                                            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),
                          Row(
                            children: [
                              Text('Açıklama',
                                  style: FontStyles.instance.employeetbxBaslik),
                              SizedBox(
                                width: context.dynamicWidth(0.01),
                              ),
                              Text(
                                '(zorunlu)',
                                style: FontStyles.instance.employeetbxRequired,
                              )
                            ],
                          ),
                          SizedBox(
                            height: context.dynamicHeight(0.01),
                          ),
                          Form(
                            key: permissionsKey,
                            child: 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: tfAciklama,
                                decoration: const InputDecoration(
                                    border: InputBorder.none),
                              ),
                            ),
                          ),
                          SizedBox(
                            height: context.dynamicHeight(0.01),
                          ),
                          mazeretMi
                              ? Column(
                                  children: [
                                    Row(
                                      children: [
                                        Text(
                                          'Dosya',
                                          style: FontStyles
                                              .instance.employeetbxBaslik,
                                        ),
                                      ],
                                    ),
                                    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.',
                                              style: TextStyle(
                                                  color: Colors.grey,
                                                  fontSize: 11,
                                                  letterSpacing: 0.5),
                                              textAlign: TextAlign.left,
                                            ),
                                          ],
                                        )),
                                  ],
                                )
                              : const SizedBox(),
                          SizedBox(
                            height: context.dynamicHeight(0.03),
                          ),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              SizedBox(
                                height: context.dynamicHeight(0.05),
                                width: context.dynamicWidth(0.25),
                                child: TextButton(
                                  onPressed: () async {
                                    sendPermission();
                                  },
                                  style: TextButton.styleFrom(
                                    backgroundColor:
                                        ColorsConstants.instance.baseTheme,
                                    shape: RoundedRectangleBorder(
                                      borderRadius: BorderRadius.circular(10),
                                    ),
                                  ),
                                  child: const Text(
                                    'İzin İsteği',
                                    style: TextStyle(color: Colors.white),
                                  ),
                                ),
                              ),
                            ],
                          ),
                          SizedBox(
                            height: context.dynamicHeight(0.03),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          )
        : const Scaffold();
  }

  dateTimePickerWidget1(BuildContext context) {
    return DatePicker.showDatePicker(
      context,
      dateFormat: 'dd/MM/yyyy',
      locale: DateTimePickerLocale.tr,
      initialDateTime: DateTime.now(),
      minDateTime: DateTime(2005),
      maxDateTime: DateTime(2100),
      pickerTheme: DateTimePickerTheme(
        backgroundColor: ColorsConstants.instance.backgroundColor,
        confirm: Text(
          'Onay',
          style: TextStyle(
              color: ColorsConstants.instance.baseTheme.withOpacity(0.7)),
        ),
      ),
      onConfirm: (dateTime, List<int> index) {
        DateTime selectdate1 = dateTime;
        birincidateTime = selectdate1;
        final baslangicTarihi =
            DateFormat('yyyy-MM-dd HH:mm').format(selectdate1);
        setState(() {
          dbSaatbaslangic = '$baslangicTarihi:00';
          gosterilenSaatbaslangic = dbSaatbaslangic.substring(0, 16);
          final DateFormat format = DateFormat.yMd('tr');
          var trTarih = format.format(DateTime.parse(gosterilenSaatbaslangic));
          gosterilenSaatbaslangic = trTarih;
          baslangicSecildi = true;
        });
        'birinci tarih ikinci tarihten önce mi ? ${ikincidateTime.isAfter(birincidateTime)}'
            .log();
      },
    );
  }

  dateTimePickerWidget2(BuildContext context) {
    return DatePicker.showDatePicker(
      context,
      dateFormat: 'dd/MM/yyyy',
      locale: DateTimePickerLocale.tr,
      minDateTime: DateTime(2005),
      maxDateTime: DateTime(2100),
      pickerTheme: DateTimePickerTheme(
        backgroundColor: ColorsConstants.instance.backgroundColor,
        confirm: Text(
          'Onay',
          style: TextStyle(
              color: ColorsConstants.instance.baseTheme.withOpacity(0.7)),
        ),
      ),
      onConfirm: (dateTime, List<int> index) {
        DateTime selectdate2 = dateTime;
        ikincidateTime = selectdate2;
        Duration fark = ikincidateTime.difference(birincidateTime);
        int gunFarki = fark.inDays;
        final bitisTarihi = DateFormat('yyyy-MM-dd HH:mm').format(selectdate2);
        setState(() {
          dbSaatbitis = '$bitisTarihi:00';
          gosterilenSaatbitis = dbSaatbitis.substring(0, 16);
          final DateFormat format = DateFormat.yMd('tr');
          var trTarih = format.format(DateTime.parse(gosterilenSaatbitis));
          gosterilenSaatbitis = trTarih;
          if (ikincidateTime.isAfter(birincidateTime) == false) {
            gosterilenSaatbitis = '';
            dbSaatbitis = '';
            ToastManager.instance
                .toastMessageService("Geçerli bir tarih seçin..");
            tarihUygun = false;
          }
        });
        if (tarihlerArasiGunFark > 0 && tarihlerArasiGunFark > 30) {
          gosterilenSaatbitis = '';
          dbSaatbitis = '';
          tarihUygun = false;
          ToastManager.instance.toastMessageService('İzin aralığı geçersiz..');
        }
        if (dbSaatbaslangic.isNotEmpty && dbSaatbitis.isNotEmpty) {
          if (dbSaatbaslangic.substring(0, 10) ==
              dbSaatbitis.substring(0, 10)) {
            tarihUygun = false;
            Fluttertoast.showToast(
                    msg: "Aynı Tarihi Seçemezsiniz",
                    toastLength: Toast.LENGTH_SHORT,
                    gravity: ToastGravity.CENTER,
                    timeInSecForIosWeb: 1,
                    textColor: Colors.white,
                    backgroundColor: ColorsConstants.instance.baseTheme,
                    fontSize: 14.0)
                .whenComplete(() {
              setState(() {
                dbSaatbitis = '';
                gosterilenSaatbitis = '';
              });
            });
          }
        }
        if (gunFarki > 0 &&
            gunFarki < 30 &&
            ikincidateTime.isAfter(birincidateTime) == true) {
          tarihUygun = true;
        }
      },
    );
  }
}
