import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import 'package:google_fonts/google_fonts.dart';
import 'package:hamlemuhcrm/core/constants/app_constants.dart';
import 'package:hamlemuhcrm/core/extensions/image_enum_extension.dart';
import 'package:hamlemuhcrm/features/projects/model/asamalar.dart';
import 'package:hamlemuhcrm/features/auth/login/cubit/login_cubit.dart';
import 'package:hamlemuhcrm/core/constants/font_styles.dart';
import 'package:hamlemuhcrm/core/extensions/responsive_extension.dart';
import 'package:hamlemuhcrm/features/projects/cubit/projects_stage_cubit.dart';

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

class ProjectStageDetailPage extends StatefulWidget {
  final Asamalar asama;
  final String projeAd;

  const ProjectStageDetailPage(
      {super.key, required this.asama, required this.projeAd});

  @override
  State<ProjectStageDetailPage> createState() => _ProjectStageDetailPageState();
}

class _ProjectStageDetailPageState extends State<ProjectStageDetailPage> {
  final tfAsamaAd = TextEditingController();

  @override
  void initState() {
    tfAsamaAd.text = widget.asama.asamaAd ?? 'Aşama Adı';
    widget.asama.olusturunaBildirim == '1'
        ? olusturunaBildirim = true
        : olusturunaBildirim = false;
    widget.asama.sorumluyaBildirim == '1'
        ? sorumluyaBildirim = true
        : sorumluyaBildirim = false;
    widget.asama.calisanaBildirim == '1'
        ? calisanaBildirim = true
        : calisanaBildirim = false;
    widget.asama.asamaArsiv == '1'
        ? otomatikArsivBildirim = true
        : otomatikArsivBildirim = false;
    isFinish = true;
    super.initState();
  }

  bool _isLoading = true;
  bool isFinish = false;
  bool isUpdated = false;
  bool? olusturunaBildirim = false;
  bool? sorumluyaBildirim = false;
  bool? calisanaBildirim = false;
  bool? otomatikArsivBildirim = false;

  @override //View
  Widget build(BuildContext context) {
    return isFinish
        ? Scaffold(
            resizeToAvoidBottomInset: false,
            appBar: _appBar(context),
            body: WillPopScope(
              onWillPop: () async {
                _geriDon(context, isUpdated);
                return true;
              },
              child: SingleChildScrollView(
                child: Column(
                  children: [
                    _pagePhoto,
                    _emptySpace,
                    Padding(
                      padding: EdgeInsets.symmetric(
                          horizontal: context.dynamicWidth(0.07)),
                      child: Column(
                        children: [
                          _headLine('Proje Adı'),
                          _emptySpace,
                          _constContainer,
                          _emptySpace,
                          _headLine('Aşama Adı'),
                          _emptySpace,
                          _tfContainer,
                          _emptyTabSpace,
                          _notificationCheckboxContainer(
                              'Bu Aşamaya Gelen Görevi Oluşturana Bildirim Gönderilsin mi ?',
                              olusturunaBildirim!, (bool? olusturanBoolean) {
                            setState(() {
                              olusturunaBildirim = olusturanBoolean!;
                            });
                          }),
                          _notificationCheckboxEmptySpace,
                          _notificationCheckboxContainer(
                              'Bu Aşamaya Gelen Görevin Sorumlularına Bildirim Gönderilsin mi ?',
                              sorumluyaBildirim!, (bool? sorumluBoolean) {
                            setState(() {
                              sorumluyaBildirim = sorumluBoolean!;
                            });
                          }),
                          _notificationCheckboxEmptySpace,
                          _notificationCheckboxContainer(
                              'Bu Aşamaya Gelen Görevin Çalışanlarına Bildirim Gönderilsin mi ?',
                              calisanaBildirim!, (bool? calisanBoolean) {
                            setState(() {
                              calisanaBildirim = calisanBoolean!;
                            });
                          }),
                          _notificationCheckboxEmptySpace,
                          _notificationCheckboxContainer(
                              'Bu Aşamaya Gelen Görevler otomatik olarak arşivlensin mi ?',
                              otomatikArsivBildirim!,
                              (bool? otomatikArsivBoolean) {
                            setState(() {
                              otomatikArsivBildirim = otomatikArsivBoolean!;
                            });
                          }),
                          _notificationCheckboxEmptySpace,
                          _buttonRow,
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          )
        : const Scaffold();
  }

  AppBar _appBar(BuildContext context) {
    return AppBar(
      backgroundColor: Colors.transparent,
      elevation: 0,
      title: Text(widget.asama.asamaAd!,
          style: GoogleFonts.inter(
              color: Colors.black, fontWeight: FontWeight.w400, fontSize: 16)),
      centerTitle: true,
      actions: [
        IconButton(
            onPressed: () {},
            icon: const Icon(
              Icons.notifications_none_outlined,
              color: Colors.black,
            )),
      ],
      leading: IconButton(
          onPressed: () {
            Navigator.pop(context, isUpdated);
          },
          icon: const Icon(
            Icons.arrow_back_ios_new,
            color: Colors.black54,
            size: 20,
          )),
    );
  }

  Widget get _emptySpace => SizedBox(
        height: context.dynamicHeight(0.015),
      );

  Widget _headLine(text) {
    return Row(
      children: [
        Text(
          text,
          style: FontStyles.instance.projectbxBaslik,
        ),
      ],
    );
  }

  Widget get _constContainer => Container(
        height: context.dynamicHeight(0.05),
        width: context.dynamicWidth(0.88),
        padding: EdgeInsets.only(
          left: context.dynamicWidth(0.02),
        ),
        alignment: Alignment.centerLeft,
        decoration: BoxDecoration(
            color: Colors.white,
            border: Border.all(color: Colors.grey.shade400),
            borderRadius: BorderRadius.circular(10)),
        child: Text(
          widget.projeAd,
          style: FontStyles.instance.projectbxDdyazi,
        ),
      );

  Widget get _tfContainer => Container(
        height: context.dynamicHeight(0.05),
        width: context.dynamicWidth(0.88),
        alignment: Alignment.center,
        decoration: BoxDecoration(
            color: Colors.white,
            border: Border.all(color: Colors.grey.shade400),
            borderRadius: BorderRadius.circular(10)),
        child: TextFormField(
          inputFormatters: [
            LengthLimitingTextInputFormatter(50) //yazı uzunluğu kısıtla
          ],
          style: FontStyles.instance.projectbxDdyazi,
          magnifierConfiguration: TextMagnifierConfiguration.disabled,
          textInputAction: TextInputAction.done,
          cursorColor: ColorsConstants.instance.baseTheme,
          controller: tfAsamaAd,
          decoration: InputDecoration(
              border: const OutlineInputBorder(borderSide: BorderSide.none),
              contentPadding:
                  EdgeInsets.symmetric(horizontal: context.dynamicWidth(0.02))),
        ),
      );

  Widget get _emptyTabSpace => SizedBox(
        height: context.dynamicHeight(0.025),
      );

  Widget get _pagePhoto => Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          SizedBox(
              height: context.dynamicHeight(0.2),
              child: ImageEnums.pstage.toPageImage),
        ],
      );

  Widget get _notificationCheckboxEmptySpace => SizedBox(
        height: context.dynamicHeight(0.025),
      );

  Widget get _checkboxContainerWidthSpace =>
      SizedBox(width: context.dynamicWidth(0.04));

  Widget _notificationCheckboxContainer(
      String text, bool booleanValue, Function(bool?) onChanged) {
    return Container(
      height: context.dynamicHeight(0.065),
      decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: const BorderRadius.all(Radius.circular(5)),
          border: Border.all(color: Colors.grey.shade400, width: 1.6)),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Container(
            width: context.dynamicWidth(0.01),
            decoration: BoxDecoration(
              borderRadius: const BorderRadius.only(
                  bottomLeft: Radius.circular(3), topLeft: Radius.circular(3)),
              color: ColorsConstants.instance.baseTheme,
            ),
          ),
          _checkboxContainerWidthSpace,
          Flexible(
            child: Text(
              text,
              style: TextStyle(color: Colors.grey.shade500, fontSize: 11),
            ),
          ),
          _checkboxContainerWidthSpace,
          Checkbox(
            shape: const CircleBorder(),
            checkColor: Colors.white,
            activeColor: Colors.green,
            splashRadius: 0.5,
            value: (booleanValue),
            onChanged: onChanged,
          ),
        ],
      ),
    );
  }

  Widget get _updatedButton => _isLoading
      ? SizedBox(
          height: context.dynamicHeight(0.045),
          width: context.dynamicWidth(0.25),
          child: TextButton(
            onPressed: () {
              if (tfAsamaAd.text != '') {
                isUpdated = true;
                context
                    .read<ProjectStageCubit>()
                    .asamaGuncelle(
                        widget.asama.asamaId!,
                        tfAsamaAd.text,
                        olusturunaBildirim! ? "1" : "0",
                        sorumluyaBildirim! ? "1" : "0",
                        calisanaBildirim! ? "1" : "0",
                        otomatikArsivBildirim! ? "1" : "0",
                        context.read<LoginCubit>().token,
                        context.read<LoginCubit>().id)
                    .whenComplete(() {
                  _snackBarMessage('Aşama Güncellendi');
                  _loadingEffect();
                });
              } else {
                _snackBarMessage('Eksik alanlar var!');
              }
            },
            style: TextButton.styleFrom(
                backgroundColor: ColorsConstants.instance.baseTheme),
            child: Text(
              ApplicationConstants.instance.moduleUpdateTxt,
              style: const TextStyle(fontSize: 12, color: Colors.white),
            ),
          ),
        )
      : _centerCircularProgress;

  Widget get _centerCircularProgress =>
      const Center(child: CircularProgressIndicator());

  Widget get _buttonRow => Row(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          //_archiveButton,
          //_buttonEmptySpace,
          _updatedButton,
        ],
      );

  void _snackBarMessage(String text) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(
          text,
        ),
        behavior: SnackBarBehavior.floating,
        backgroundColor: ColorsConstants.instance.baseTheme,
        action: SnackBarAction(
            label: 'Tamam', textColor: Colors.white, onPressed: () {}),
      ),
    );
  }

  Future<void> _loadingEffect() async {
    setState(() {
      _isLoading = true;
    });
    await Future.delayed(const Duration(seconds: 2), () {
      setState(() {
        _isLoading = false;
      });
      Navigator.pop(context, true);
    });
  }
}

void _geriDon(BuildContext context, bool isUpdated) {
  Navigator.pop(context, isUpdated);
  //eger guncelleme yapıldıysa geriye dönüldüğünde .then ile gonderdigim isUpdated degiskeni true olduğu için RefreshScreen ile login olan kullanıcının bilgileri güncellenecek navigasyon tuşuna müdahale ettim
}
