import 'dart:math';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hamlemuhcrm/core/extensions/log_extension.dart';

import '../../../core/constants/color_constants.dart';
import '../../../core/constants/font_styles.dart';
import '../../../core/constants/url_services_constant.dart';
import '../../../core/extensions/image_enum_extension.dart';
import '../../../core/extensions/responsive_extension.dart';
import '../../auth/login/cubit/login_cubit.dart';
import '../../auth/splash/view/splash_view.dart';
import '../../customers/widgets/shimmer_container.dart';
import '../../permissions/cubit/permission_cubit.dart';
import '../../permissions/view/employee_permissions_page.dart';
import '../cubit/employee_cubit.dart';
import '../model/personel.dart';
import '../widgets/employee_navigate_button.dart';
import 'employee_add_page.dart';
import 'employee_archive_page.dart';
import 'employee_update_page.dart';

class EmployeePage extends StatefulWidget {
  const EmployeePage({super.key});

  @override
  State<EmployeePage> createState() => _EmployeePageState();
}

class _EmployeePageState extends State<EmployeePage> {
  final tcPersonelAra = TextEditingController();
  late bool isFinish;
  static final GlobalKey<FormState> _employeePageKey = GlobalKey();

  @override
  void initState() {
    'employee sayfası initstate çalıştı'.log();
    isFinish = false;
    context
        .read<EmployeeCubit>()
        .personelListele(context.read<LoginCubit>().userfirmId,
            context.read<LoginCubit>().token, context.read<LoginCubit>().id)
        .whenComplete(() {
      isFinish = true;
    });
    super.initState();
  }

  @override
  void didChangeDependencies() {
    context.read<EmployeeCubit>().personelListele(
        context.read<LoginCubit>().userfirmId,
        context.read<LoginCubit>().token,
        context.read<LoginCubit>().id);
    super.didChangeDependencies();
  }

  @override
  Widget build(BuildContext context) {
    debugPrint('employee page buildcontext tetiklendi');
    return context.read<LoginCubit>().tip == '1' ||
            context.read<LoginCubit>().tip == '33'
        ? Scaffold(
            body: Center(
              child: Column(
                children: [
                  _pageImage,
                  SizedBox(height: context.dynamicHeight(0.03)),
                  Form(
                    key: _employeePageKey,
                    child: Container(
                      height: context.dynamicHeight(0.0564),
                      width: context.dynamicWidth(0.8),
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(8),
                          color: ColorsConstants.instance.backgroundColor,
                          boxShadow: [
                            BoxShadow(
                                color: Colors.grey.withOpacity(0.4),
                                blurRadius: 6,
                                offset: const Offset(1, 1)),
                          ],
                          border:
                              Border.all(color: Colors.grey.withOpacity(0.3))),
                      child: Row(
                        children: [
                          Flexible(
                            flex: 2,
                            child: TextFormField(
                              controller: tcPersonelAra,
                              textAlign: TextAlign.left,
                              cursorColor: ColorsConstants.instance.baseTheme,
                              onChanged: (aramakelimesi) {
                                context
                                    .read<EmployeeCubit>()
                                    .personelAra(aramakelimesi);
                              },
                              magnifierConfiguration:
                                  TextMagnifierConfiguration.disabled,
                              style: const TextStyle(
                                  color: Colors.grey, fontSize: 16.0),
                              decoration: InputDecoration(
                                  focusedBorder: InputBorder.none,
                                  border: InputBorder.none,
                                  prefixIcon: Icon(
                                    Icons.search,
                                    color: Colors.grey,
                                    size: context.dynamicWidth(0.062),
                                  ),
                                  hintText: 'Personel Ara',
                                  hintStyle: const TextStyle(
                                      fontSize: 15.0, color: Colors.grey)),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                  SizedBox(height: context.dynamicHeight(0.03)),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      SizedBox(width: context.dynamicWidth(0.055)),
                      EmployeeNavigateButton(
                        buttonTxt: 'Yeni Ekle',
                        withOnPressed: () {
                          Navigator.push(
                              context,
                              MaterialPageRoute(
                                  builder: (context) =>
                                      const EmployeeAddPage()));
                        },
                      ),
                      SizedBox(width: context.dynamicWidth(0.055)),
                      EmployeeNavigateButton(
                        buttonTxt: 'Arşivler',
                        withOnPressed: () {
                          context
                              .read<EmployeeCubit>()
                              .personelArsivListele(
                                  context.read<LoginCubit>().userfirmId,
                                  context.read<LoginCubit>().token,
                                  context.read<LoginCubit>().id)
                              .whenComplete(() => Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                      builder: (context) =>
                                          const EmployeeArchivePage())));
                        },
                      ),
                      SizedBox(width: context.dynamicWidth(0.055)),
                      EmployeeNavigateButton(
                        buttonTxt: 'İzinler',
                        withOnPressed: () {
                          context
                              .read<PermissionCubit>()
                              .izinListesi(
                                  context.read<LoginCubit>().token,
                                  context.read<LoginCubit>().id,
                                  context.read<LoginCubit>().tip)
                              .whenComplete(() => Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                      builder: (context) =>
                                          EmployeePermissionPage(
                                              cevapBekleyenler: context
                                                  .read<PermissionCubit>()
                                                  .cevapBekleyenler,
                                              cevaplananIzinler: context
                                                  .read<PermissionCubit>()
                                                  .cevaplananIzinler))));
                        },
                      ),
                      SizedBox(width: context.dynamicWidth(0.055)),
                    ],
                  ),
                  SizedBox(height: context.dynamicHeight(0.02)),
                  Expanded(
                    flex: 3,
                    child: BlocBuilder<EmployeeCubit, List<Personel>>(
                        builder: (context, personel) {
                      if (personel.isNotEmpty) {
                        return _scrollBar(
                          ListView.builder(
                            itemCount: personel.length,
                            itemBuilder: (context, indeks) {
                              final fpersonel = personel[indeks];
                              return isFinish
                                  ? InkWell(
                                      highlightColor: Colors.grey.shade50,
                                      onTap: () {
                                        Navigator.push(
                                                context,
                                                MaterialPageRoute(
                                                    builder: (context) =>
                                                        EmployeeUpdatePage(
                                                            personel:
                                                                fpersonel)))
                                            .then((value) {
                                          if (value) {
                                            //eger guncelleme varsa giris bilgileri yeniden alınıyor refreshscreen ile güncelleme yoksa eski hali geliyor..isUpdated gönderdiğim için.
                                            Navigator.pushReplacement(
                                                context,
                                                MaterialPageRoute(
                                                    builder: (context) =>
                                                        const SplashView()));
                                          }
                                        });
                                      },
                                      child: Container(
                                        height: context.dynamicHeight(0.09),
                                        margin: EdgeInsets.symmetric(
                                            vertical:
                                                context.dynamicHeight(0.01),
                                            horizontal:
                                                context.dynamicWidth(0.04)),
                                        decoration: BoxDecoration(
                                          borderRadius:
                                              BorderRadius.circular(5),
                                          boxShadow: [
                                            BoxShadow(
                                                color: Colors.grey
                                                    .withOpacity(0.4),
                                                blurRadius: 7,
                                                offset: const Offset(1, 5))
                                          ],
                                          color: Colors.white,
                                        ),
                                        child: Row(
                                          children: [
                                            Container(
                                              width: 5,
                                              height:
                                                  context.dynamicHeight(0.09),
                                              decoration: BoxDecoration(
                                                borderRadius:
                                                    const BorderRadius.only(
                                                        topLeft:
                                                            Radius.circular(5),
                                                        bottomLeft:
                                                            Radius.circular(5)),
                                                color: Color(
                                                        (Random().nextDouble() *
                                                                0xFFFFFF)
                                                            .toInt())
                                                    .withOpacity(
                                                        1.0), //Colors.primaries[Random().nextInt(Colors.primaries.length)],
                                              ),
                                            ),
                                            const SizedBox(width: 10),
                                            Text(
                                                '${fpersonel.firstName!} ${fpersonel.lastName!}',
                                                style: FontStyles
                                                    .instance.ortaYazi),
                                            const Spacer(),
                                            Container(
                                              margin: EdgeInsets.only(
                                                  right: context
                                                      .dynamicWidth(0.08)),
                                              child: CircleAvatar(
                                                radius: 20,
                                                backgroundColor:
                                                    Colors.grey.shade400,
                                                child: CachedNetworkImage(
                                                  imageUrl:
                                                      _imageCheck(fpersonel),
                                                  imageBuilder: (context,
                                                          imageProvider) =>
                                                      Container(
                                                    decoration: BoxDecoration(
                                                      shape: BoxShape.circle,
                                                      image: DecorationImage(
                                                        image: imageProvider,
                                                        fit: BoxFit.cover,
                                                      ),
                                                    ),
                                                  ),
                                                  maxHeightDiskCache: 200,
                                                  // placeholder: (context, url) =>
                                                  //     const CircularProgressIndicator
                                                  //         .adaptive(),
                                                  errorWidget:
                                                      (context, url, error) =>
                                                          const Icon(
                                                    Icons
                                                        .image_not_supported_rounded,
                                                    color: Colors.grey,
                                                  ),
                                                  fadeOutDuration:
                                                      const Duration(
                                                          seconds: 1),
                                                  fadeInDuration:
                                                      const Duration(
                                                          seconds: 2),
                                                ),
                                              ),
                                            ),
                                          ],
                                        ),
                                      ),
                                    )
                                  : ShimmerContainer(
                                      color: Colors.grey,
                                      opacity: 0.4,
                                      marginYukseklik:
                                          context.dynamicHeight(0.01),
                                      height: context.dynamicHeight(0.09),
                                    );
                            },
                          ),
                        );
                      } else {
                        return const Center(
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: [
                              SizedBox(height: 25),
                              Text(
                                'Kişi Bulunamadı',
                                style: TextStyle(fontSize: 17),
                              ),
                            ],
                          ),
                        );
                      }
                    }),
                  )
                ],
              ),
            ),
          )
        : _notPermissionPage;
  }

  Widget get _notPermissionPage => const Scaffold(
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(
                Icons.not_accessible_rounded,
                color: Colors.black38,
                size: 30,
              ),
              SizedBox(height: 20),
              Text(
                'Bu Sayfayı Görüntüleme Yetkiniz Yok !',
                style: TextStyle(color: Colors.black38, fontSize: 18),
              ),
            ],
          ),
        ),
      );

  String _imageCheck(Personel model) {
    if (model.image == null) return URLAPIService.instance.defaultPhotoUrl;

    if (model.image != null && model.image!.isNotEmpty) {
      return '${URLAPIService.instance.fileBaseURL}/upload-user/${model.image}';
    }

    return URLAPIService.instance.defaultPhotoUrl;
  }

  Widget get _pageImage => SizedBox(
      height: context.dynamicHeight(0.2),
      child: ImageEnums.employee.toPageImage);

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