import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:intl/intl.dart';
import 'package:hamlemuhcrm/core/constants/font_styles.dart';
import 'package:hamlemuhcrm/core/extensions/log_extension.dart';
import 'package:hamlemuhcrm/core/extensions/responsive_extension.dart';
import 'package:hamlemuhcrm/features/permissions/cubit/permission_cubit.dart';
import 'package:hamlemuhcrm/features/permissions/model/izinler.dart';
import 'package:hamlemuhcrm/features/permissions/view/employee_permissions_confirm.dart';
import 'package:hamlemuhcrm/features/permissions/view/employee_permissions_view.dart';

import '../../../core/extensions/image_enum_extension.dart';
import '../../../core/route/page_route.dart';

final class EmployeePermissionPage extends StatefulWidget {
  final List<Izinler> cevapBekleyenler;
  final List<Izinler> cevaplananIzinler;

  const EmployeePermissionPage(
      {super.key,
      required this.cevapBekleyenler,
      required this.cevaplananIzinler});

  @override
  State<EmployeePermissionPage> createState() => _EmployeePermissionPageState();
}

class _EmployeePermissionPageState extends State<EmployeePermissionPage> {
  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    isFinish = true;
  }

  bool isFinish = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
          backgroundColor: Colors.transparent,
          elevation: 0,
          title: Text('İzin Talepleri',
              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: Column(
          children: [
            SizedBox(
                height: context.dynamicHeight(0.2),
                child: ImageEnums.leave.toPageImage),
            _emptySpace(context),
            Padding(
              padding:
                  EdgeInsets.symmetric(horizontal: context.dynamicWidth(0.05)),
              child: Column(
                children: [
                  _headLine('Bekleyen İzinler'),
                  _emptySpace(context),
                  Container(
                    padding: EdgeInsets.symmetric(
                        horizontal: context.dynamicWidth(0.03)),
                    height: context.dynamicHeight(0.25),
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(
                            10), //bekleyen izinler genel container kenar yuvarlaklığı
                        color: Colors.white,
                        border:
                            Border.all(color: Colors.grey.withOpacity(0.6))),
                    child: BlocBuilder<PermissionCubit, List<Izinler>>(
                        builder: (context, izinler) {
                      'izinbekleyenler : ${izinler.where((veri) => veri.izinDurum == '1').length}'
                          .log();
                      'cevaplananlar olumsuz : ${izinler.where((veri) => veri.izinDurum == '2').length}'
                          .log();
                      'cevaplananlar olumlu : ${izinler.where((veri) => veri.izinDurum == '3').length}'
                          .log();
                      // izin_durum = 2 = izin onaylanmadı
                      // izin_durum = 3 = izin onaylandı
                      if (widget.cevapBekleyenler.isNotEmpty) {
                        return _scrollBar(
                          ListView.builder(
                              itemCount: widget.cevapBekleyenler.length,
                              itemBuilder: (context, indeks) {
                                var izinlerNesnesi =
                                    widget.cevapBekleyenler[indeks];
                                if (isFinish) {
                                  return InkWell(
                                    highlightColor: Colors.grey.shade50,
                                    onTap: () {
                                      Navigator.push(
                                          context,
                                          CustomPageRoute(
                                              child: PermissionsConfirmPage(
                                                  izinler: izinlerNesnesi)));
                                      "cevaplanmamış izin : ${izinlerNesnesi.izinDurum}"
                                          .log();
                                    },
                                    child: Container(
                                      margin: _marginPaddingAll,
                                      height: context.dynamicHeight(0.045),
                                      decoration: BoxDecoration(
                                          border: Border.all(
                                              color:
                                                  Colors.grey.withOpacity(0.5),
                                              width: 1),
                                          borderRadius:
                                              BorderRadius.circular(5)),
                                      child: Row(
                                        mainAxisAlignment:
                                            MainAxisAlignment.center,
                                        children: [
                                          Text(
                                              '${izinlerNesnesi.izinAlanAd} ${izinlerNesnesi.izinAlanSoyad}',
                                              style: FontStyles.instance
                                                  .bekleyenIzinYaziKalin),
                                          _emptyWidhtContainerSpace,
                                          Text('izin İstiyor',
                                              style: FontStyles
                                                  .instance.bekleyenIzinYazi),
                                        ],
                                      ),
                                    ),
                                  );
                                } else {
                                  return Center(
                                    child: Column(
                                      mainAxisAlignment:
                                          MainAxisAlignment.center,
                                      children: [
                                        const Icon(
                                            Icons.remove_circle_outline_sharp),
                                        const SizedBox(height: 12),
                                        Text(
                                          'Bekleyen İzin Yok',
                                          style:
                                              FontStyles.instance.activityYazi,
                                        ),
                                      ],
                                    ),
                                  );
                                }
                              }),
                        );
                      } else {
                        return Center(
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              const Icon(Icons.remove_circle_outline_sharp),
                              const SizedBox(height: 12),
                              Text(
                                'Bekleyen İzin Yok',
                                style: FontStyles.instance.activityYazi,
                              ),
                            ],
                          ),
                        );
                      }
                    }),
                  ),
                  _emptySpace(context),
                  _headLine('Cevaplanan İzinler'),
                  _emptySpace(context),
                  Container(
                    padding: EdgeInsets.symmetric(
                        horizontal: context.dynamicWidth(0.03)),
                    height: context.dynamicHeight(0.25),
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(
                            10), //cevaplanan izinler genel container kenar yuvarlaklığı
                        color: Colors.white,
                        border:
                            Border.all(color: Colors.grey.withOpacity(0.5))),
                    child: BlocBuilder<PermissionCubit, List<Izinler>>(
                        builder: (context, izinler) {
                      // izin_durum = 2 = izin onaylanmadı
                      // izin_durum = 3 = izin onaylandı
                      if (widget.cevaplananIzinler.isNotEmpty) {
                        return _scrollBar(
                          ListView.builder(
                              itemCount: widget.cevaplananIzinler.length,
                              itemBuilder: (context, indeks) {
                                var izinlerNesnesi =
                                    widget.cevaplananIzinler[indeks];
                                final DateFormat format = DateFormat.yMd('tr');
                                String baslamaTarihiTR = format.format(
                                    DateTime.parse(
                                        izinlerNesnesi.izinBaslamaTarihi != '0'
                                            ? izinlerNesnesi.izinBaslamaTarihi!
                                            : "2000-01-01 00:00:00"));
                                String isbasiTarihiTR = format.format(
                                    DateTime.parse(
                                        izinlerNesnesi.izinIsbasiTarihi != '0'
                                            ? izinlerNesnesi.izinIsbasiTarihi!
                                            : "2000-01-01 00:00:00"));
                                int ilkSayiDeneme1 =
                                    int.parse(baslamaTarihiTR.split(".")[0]);
                                int ilkSayiDeneme2 =
                                    int.parse(isbasiTarihiTR.split(".")[0]);
                                int fark = ilkSayiDeneme2 - ilkSayiDeneme1;
                                if (isFinish) {
                                  return InkWell(
                                    highlightColor: Colors.grey.shade50,
                                    onTap: () {
                                      Navigator.push(
                                          context,
                                          CustomPageRoute(
                                              child: PermissionsViewPage(
                                                  izinler: izinlerNesnesi)));
                                    },
                                    child: Stack(
                                      children: [
                                        Container(
                                          margin: _marginPaddingAll,
                                          height: context.dynamicHeight(0.045),
                                          decoration: BoxDecoration(
                                              border: Border.all(
                                                  color: Colors.grey
                                                      .withOpacity(0.5),
                                                  width: 1),
                                              borderRadius:
                                                  BorderRadius.circular(5)),
                                          child: Row(
                                            mainAxisAlignment:
                                                MainAxisAlignment.spaceEvenly,
                                            children: [
                                              Text(
                                                  '$baslamaTarihiTR - $isbasiTarihiTR',
                                                  style: FontStyles.instance
                                                      .cevaplananIzinYaziKalin),
                                              _emptyWidhtContainerSpace,
                                              Text(
                                                  '${izinlerNesnesi.izinAlanAd} ${izinlerNesnesi.izinAlanSoyad}',
                                                  style: FontStyles.instance
                                                      .cevaplananIzinYazi),
                                              _emptyWidhtContainerSpace,
                                              Text('$fark Günlük',
                                                  style: FontStyles.instance
                                                      .cevaplananIzinYaziKalin),
                                            ],
                                          ),
                                        ),
                                        Positioned(
                                          top: 0,
                                          right: 4,
                                          child: Container(
                                            height:
                                                context.dynamicHeight(0.023),
                                            width: context.dynamicWidth(0.035),
                                            decoration: const BoxDecoration(
                                                color: Colors.white),
                                            child: Icon(
                                              izinlerNesnesi.izinDurum == "2"
                                                  ? Icons.remove_circle_sharp
                                                  : Icons
                                                      .check_circle_rounded, // bu kısım gelen değere göre değişecek... 1 gelirse onaylanmış 0 gelirse onaylanmamış
                                              color: izinlerNesnesi.izinDurum ==
                                                      "2"
                                                  ? Colors.red
                                                  : Colors.green,
                                              size: context.dynamicWidth(0.033),
                                            ),
                                          ),
                                        ),
                                      ],
                                    ),
                                  );
                                } else {
                                  return null;
                                }
                              }),
                        );
                      } else {
                        return const Center(
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Icon(Icons.remove_circle_outline_rounded),
                              SizedBox(height: 12),
                              Text(
                                'Cevaplanmış İzin Yok',
                                style: TextStyle(fontSize: 15),
                              ),
                            ],
                          ),
                        );
                      }
                    }),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget get _emptyWidhtContainerSpace => SizedBox(
        width: context.dynamicWidth(0.01),
      );

  EdgeInsets get _marginPaddingAll =>
      EdgeInsets.all(context.dynamicHeight(0.012));
}

Widget _emptySpace(BuildContext context) {
  return SizedBox(
    height: context.dynamicHeight(0.02),
  );
}

Widget _headLine(String text) {
  return Row(
    mainAxisAlignment: MainAxisAlignment.start,
    children: [
      Text(text, style: FontStyles.instance.employeetbxBaslik),
      const Spacer(),
      const Text(
        'Tümünü Göster',
        style: TextStyle(color: Colors.blue, fontSize: 11),
      ),
    ],
  );
}

Widget _scrollBar(Widget child) {
  return Scrollbar(
    thickness: 6,
    radius: const Radius.circular(10),
    child: child,
  );
}
