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/projeler.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 ProjectStageCreatePage extends StatefulWidget {
  final Projeler proje;

  const ProjectStageCreatePage({
    super.key,
    required this.proje,
  });

  @override
  State<ProjectStageCreatePage> createState() => _ProjectStageCreatePageState();
}

class _ProjectStageCreatePageState extends State<ProjectStageCreatePage> {
  final tfAsamaAd = TextEditingController();

  @override
  void initState() {
    super.initState();
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        elevation: 0,
        title: Text('Yeni Aşama Ekle',
            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, true);
            },
            icon: const Icon(
              Icons.arrow_back_ios_new,
              color: Colors.black54,
              size: 20,
            )),
      ),
      body: 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,
                  _addStageButton,
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

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

  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.proje.projeAd!,
          style: FontStyles.instance.projectbxDdyazi,
        ),
      );

  Widget get _tfContainer => Container(
        height: context.dynamicHeight(0.05),
        width: context.dynamicWidth(0.88),
        alignment: Alignment.centerLeft,
        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,
          validator: (value) {
            if (value!.isEmpty ||
                !RegExp(r"^[a-zA-Z]+(([',. -][a-zA-Z ])?[a-zA-Z]*)*$")
                    .hasMatch(value)) {
              tfAsamaAd.text = 'geçersiz';
              ScaffoldMessenger.of(context).showSnackBar(
                SnackBar(
                  backgroundColor: ColorsConstants.instance.baseTheme,
                  content: const Text(
                    'Geçerli bir aşama adı girin..',
                  ),
                  behavior: SnackBarBehavior.floating,
                  action: SnackBarAction(
                    label: "Tamam",
                    textColor: Colors.white,
                    onPressed: () {},
                  ),
                ),
              );
            }
            return null;
          },
          textInputAction: TextInputAction.done,
          cursorColor: ColorsConstants.instance.baseTheme,
          controller: tfAsamaAd,
          decoration: InputDecoration(
              contentPadding:
                  EdgeInsets.symmetric(horizontal: context.dynamicWidth(0.02)),
              border: const OutlineInputBorder(borderSide: BorderSide.none)),
        ),
      );

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

  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 _notificationCheckboxEmptySpace => SizedBox(
        height: context.dynamicHeight(0.025),
      );

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

  Widget get _addStageButton => Row(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          _isLoading
              ? _centerCircularProgress
              : SizedBox(
                  height: context.dynamicHeight(0.045),
                  width: context.dynamicWidth(0.25),
                  child: TextButton(
                    onPressed: () {
                      if (tfAsamaAd.text != '') {
                        context
                            .read<ProjectStageCubit>()
                            .asamaEkle(
                                widget.proje.projeId!,
                                context.read<LoginCubit>().userfirmId,
                                tfAsamaAd.text,
                                olusturunaBildirim! ? "1" : "0",
                                sorumluyaBildirim! ? "1" : "0",
                                calisanaBildirim! ? "1" : "0",
                                otomatikArsivBildirim! ? "1" : "0",
                                context.read<LoginCubit>().token,
                                context.read<LoginCubit>().id)
                            .whenComplete(() async {
                          _snackBarMessage('Aşama eklendi');
                          _loadingEffect();
                        });
                      } else {
                        _snackBarMessage('Eksik alanlar var!');
                      }
                    },
                    style: TextButton.styleFrom(
                        backgroundColor: ColorsConstants.instance.baseTheme),
                    child: Text(
                      ApplicationConstants.instance.moduleSaveTxt,
                      style: const TextStyle(fontSize: 12, color: Colors.white),
                    ),
                  ),
                ),
        ],
      );

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

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

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