import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hamlemuhcrm/core/constants/app_constants.dart';
import 'package:hamlemuhcrm/core/constants/font_styles.dart';
import 'package:hamlemuhcrm/core/extensions/image_enum_extension.dart';
import 'package:hamlemuhcrm/core/extensions/responsive_extension.dart';
import 'package:hamlemuhcrm/features/auth/login/cubit/login_cubit.dart';
import 'package:hamlemuhcrm/features/projects/cubit/missions_cubit.dart';
import 'package:hamlemuhcrm/features/projects/cubit/project_cubit.dart';
import 'package:flutter_colorpicker/flutter_colorpicker.dart';
import 'package:hamlemuhcrm/features/projects/model/initial_id_values_model.dart';
import 'package:hamlemuhcrm/features/projects/widgets/employee_type_headline.dart';

import '../../../../core/constants/color_constants.dart';
import '../../../../core/utility/toast_manager.dart';
import '../../widgets/multiselect_widgets/selected_employee_chip.dart';
import 'project_add_main_mission_mixin.dart';

class ProjectAddMainMission extends StatefulWidget {
  final String projeId;
  final String asamaId;
  final InitialIdValuesModel initialModel;

  const ProjectAddMainMission(
      {super.key,
      required this.projeId,
      required this.asamaId,
      required this.initialModel});

  @override
  State<ProjectAddMainMission> createState() => _ProjectAddMainMission();
}

class _ProjectAddMainMission extends State<ProjectAddMainMission>
    with ProjectAddMainMissionMixin {
  @override
  Widget build(BuildContext context) {
    return isFinish
        ? Scaffold(
            appBar: AppBar(
              backgroundColor: Colors.transparent,
              elevation: 0,
              title: Text('Yeni Görev Ekle',
                  style: FontStyles.instance.appbarTitleStyle),
              centerTitle: true,
              leading: IconButton(
                  onPressed: () {
                    Navigator.pop(context, false);
                  },
                  icon: const Icon(
                    Icons.arrow_back_ios_new,
                    color: Colors.black54,
                    size: 20,
                  )),
            ),
            body: SingleChildScrollView(
              child: Column(
                children: [
                  SizedBox(
                      height: context.dynamicHeight(0.2),
                      child: ImageEnums.cproject.toPageImage),
                  _emptySpace(context),
                  Padding(
                    padding: EdgeInsets.symmetric(
                        horizontal: context.dynamicWidth(0.07)),
                    child: Column(
                      children: [
                        _headLine('Görev Adı'),
                        _emptySpace(context),
                        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(100)
                            ],
                            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)) {
                                tfGorevAd.text = 'geçersiz';
                                ScaffoldMessenger.of(context).showSnackBar(
                                  SnackBar(
                                    backgroundColor: ColorsConstants
                                        .instance.backgroundColor,
                                    content: const Text(
                                      'Geçerli bir görev adı girin..',
                                    ),
                                    behavior: SnackBarBehavior.floating,
                                    action: SnackBarAction(
                                      label: "Tamam",
                                      textColor: Colors.white,
                                      onPressed: () {},
                                    ),
                                  ),
                                );
                              }
                              return null;
                            },
                            textInputAction: TextInputAction.done,
                            cursorColor: ColorsConstants.instance.baseTheme,
                            controller: tfGorevAd,
                            decoration: const InputDecoration(
                              contentPadding:
                                  EdgeInsets.symmetric(horizontal: 5),
                              border: OutlineInputBorder(
                                  borderSide: BorderSide.none),
                            ),
                          ),
                        ),
                        SizedBox(height: context.dynamicHeight(0.02)),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                _headLine('Başlangıç Tarihi'),
                                _emptySpace(context),
                                Container(
                                    height: context.dynamicHeight(0.055),
                                    width: context.dynamicWidth(0.4),
                                    decoration: BoxDecoration(
                                      borderRadius: BorderRadius.circular(10),
                                      color: Colors.white,
                                      border: Border.all(
                                          color: Colors.grey.withOpacity(0.6)),
                                    ),
                                    child: Row(
                                      children: [
                                        const SizedBox(width: 10),
                                        Text(
                                          gosterilenSaatbaslangic,
                                          style: FontStyles
                                              .instance.projectbxDdyazi,
                                        ),
                                        const Spacer(),
                                        IconButton(
                                            padding: EdgeInsets.zero,
                                            onPressed: () {
                                              dateTimePickerWidget1(context);
                                            },
                                            tooltip: 'Tarih Seç',
                                            icon: Icon(
                                              Icons.calendar_month_outlined,
                                              size: 23,
                                              color: ColorsConstants
                                                  .instance.baseTheme,
                                            )),
                                      ],
                                    )),
                              ],
                            ),
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                _headLine('Bitiş Tarihi'),
                                _emptySpace(context),
                                Container(
                                  height: context.dynamicHeight(0.055),
                                  width: context.dynamicWidth(0.4),
                                  decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(10),
                                    color: Colors.white,
                                    border: Border.all(
                                      color: Colors.grey.withOpacity(0.6),
                                    ),
                                  ),
                                  child: Row(
                                    children: [
                                      const SizedBox(width: 10),
                                      Text(
                                        gosterilenSaatbitis,
                                        style:
                                            FontStyles.instance.projectbxDdyazi,
                                      ),
                                      const Spacer(),
                                      baslangicSecildi
                                          ? IconButton(
                                              padding: EdgeInsets.zero,
                                              onPressed: () {
                                                dateTimePickerWidget2(context);
                                              },
                                              tooltip: 'Bitiş Tarihi Seç',
                                              icon: Icon(
                                                Icons.calendar_month_outlined,
                                                size: 23,
                                                color: ColorsConstants
                                                    .instance.baseTheme,
                                              ))
                                          : IconButton(
                                              padding: EdgeInsets.zero,
                                              onPressed: () {
                                                ToastManager.instance
                                                    .toastMessageService(
                                                        "Başlangıç tarihini seçin..");
                                              },
                                              tooltip: 'Bitiş Tarihi Seç',
                                              icon: Icon(
                                                Icons.calendar_month_outlined,
                                                size: 23,
                                                color: ColorsConstants
                                                    .instance.baseTheme,
                                              ))
                                    ],
                                  ),
                                ),
                              ],
                            ),
                          ],
                        ),
                        const SizedBox(height: 15),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                _headLine('Sorumlular'),
                                _emptySpace(context),
                                Container(
                                  height: context.dynamicHeight(0.055),
                                  width: context.dynamicWidth(0.40),
                                  decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(10),
                                    color: secilenAmirList.isNotEmpty
                                        ? Colors.grey.shade200
                                        : Colors.white,
                                    border: Border.all(
                                      color: Colors.grey.withOpacity(0.6),
                                    ),
                                  ),
                                  child: Row(
                                    children: [
                                      SizedBox(
                                          width: context.dynamicWidth(0.04)),
                                      Text(
                                        secilenAmirList.isNotEmpty
                                            ? 'Seçildi'
                                            : '',
                                        style: const TextStyle(fontSize: 13.5),
                                      ),
                                      const Spacer(),
                                      IconButton(
                                          padding: EdgeInsets.zero,
                                          onPressed: () {
                                            isFinish = false;
                                            showMultiSelectLeaders();
                                            isFinish = true;
                                          },
                                          tooltip: 'Sorumlu Seç',
                                          icon: Icon(
                                            Icons.arrow_drop_down_sharp,
                                            size: 23,
                                            color: ColorsConstants
                                                .instance.baseTheme,
                                          ))
                                    ],
                                  ),
                                ),
                              ],
                            ),
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                _headLine('Görevliler'),
                                _emptySpace(context),
                                Container(
                                  height: context.dynamicHeight(0.055),
                                  width: context.dynamicWidth(0.40),
                                  decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(10),
                                    color: secilenPersonelList.isNotEmpty
                                        ? Colors.grey.shade200
                                        : Colors.white,
                                    border: Border.all(
                                      color: Colors.grey.withOpacity(0.6),
                                    ),
                                  ),
                                  child: Row(
                                    children: [
                                      SizedBox(
                                          width: context.dynamicWidth(0.04)),
                                      Text(
                                        secilenPersonelList.isNotEmpty
                                            ? 'Seçildi'
                                            : '',
                                        style: const TextStyle(fontSize: 13.5),
                                      ),
                                      const Spacer(),
                                      IconButton(
                                          padding: EdgeInsets.zero,
                                          onPressed: () {
                                            isFinish = false;
                                            showMultiSelectEmployee();
                                            isFinish = true;
                                          },
                                          tooltip: 'Görevli Seç',
                                          icon: Icon(
                                            Icons.arrow_drop_down_sharp,
                                            size: 23,
                                            color: ColorsConstants
                                                .instance.baseTheme,
                                          ))
                                    ],
                                  ),
                                ),
                              ],
                            ),
                          ],
                        ),
                        context.read<ProjectCubit>().secilenAmirIdler.isNotEmpty
                            ? Column(children: [
                                const EmployeeTypeHeadline(
                                    employeeType: "Sorumlular"),
                                SelectedEmployeeWidget(
                                    selectedLeaders: context
                                        .read<ProjectCubit>()
                                        .secilenAmirAdlar),
                              ])
                            : SizedBox(height: context.dynamicHeight(0.02)),
                        context
                                .read<ProjectCubit>()
                                .secilenPersonelIdler
                                .isNotEmpty
                            ? Column(children: [
                                const EmployeeTypeHeadline(
                                    employeeType: "Görevliler"),
                                SelectedEmployeeWidget(
                                    selectedLeaders: context
                                        .read<ProjectCubit>()
                                        .secilenPersonelAdlar),
                                context
                                        .read<ProjectCubit>()
                                        .secilenAmirIdler
                                        .isNotEmpty
                                    ? const SizedBox()
                                    : const Divider(
                                        height: 20,
                                      ),
                              ])
                            : SizedBox(height: context.dynamicHeight(0.02)),
                        Column(
                          children: [
                            _headLine('Açıklama'),
                            _emptySpace(context),
                            Container(
                              padding: const EdgeInsets.all(5),
                              height: context.dynamicHeight(0.11),
                              width: context.dynamicWidth(1),
                              decoration: BoxDecoration(
                                color: Colors.white,
                                borderRadius: BorderRadius.circular(10),
                                border: Border.all(
                                  color: Colors.grey.withOpacity(0.6),
                                ),
                              ),
                              child: TextFormField(
                                textInputAction: TextInputAction.done,
                                maxLines: 3,
                                cursorColor: ColorsConstants.instance.baseTheme,
                                style: FontStyles.instance.projectbxDdyazi,
                                controller: tfAciklama,
                                decoration: const InputDecoration(
                                  border: InputBorder.none,
                                  contentPadding:
                                      EdgeInsets.symmetric(horizontal: 2),
                                ),
                              ),
                            ),
                          ],
                        ),
                        Row(
                          children: [
                            Container(
                              height: 25,
                              width: 25,
                              decoration: BoxDecoration(
                                  color: selectedcolor,
                                  borderRadius: BorderRadius.circular(2)),
                            ),
                            SizedBox(width: context.dynamicWidth(0.03)),
                            const Text(
                              '|',
                              style: TextStyle(
                                  color: Colors.grey,
                                  fontSize: 30,
                                  fontWeight: FontWeight.w200),
                            ),
                            MaterialButton(
                              minWidth: 0,
                              padding: EdgeInsets.zero,
                              onPressed: () {
                                showDialog(
                                    barrierDismissible: false,
                                    context: context,
                                    builder: (context) {
                                      return SimpleDialog(
                                        title: const Text(
                                          'Renk Paleti',
                                          style: TextStyle(
                                              fontSize: 15,
                                              fontWeight: FontWeight.bold),
                                        ),
                                        children: [
                                          ColorPicker(
                                              pickerColor: selectedcolor,
                                              colorHistory: colorhistory,
                                              enableAlpha: false,
                                              paletteType:
                                                  PaletteType.rgbWithBlue,
                                              onHistoryChanged: (value) {},
                                              onColorChanged: (color) {
                                                selectedcolor = color;
                                                rgbConvert(
                                                    selectedcolor.red
                                                        .toString(),
                                                    selectedcolor.green
                                                        .toString(),
                                                    selectedcolor.blue
                                                        .toString());
                                                setState(() {});
                                              }),
                                          Padding(
                                            padding: const EdgeInsets.all(8.0),
                                            child: MaterialButton(
                                              onPressed: () {
                                                Navigator.pop(context);
                                              },
                                              color: Colors.deepOrange,
                                              child: const Text(
                                                'Renk Seç',
                                                style: TextStyle(
                                                    fontSize: 20,
                                                    fontWeight: FontWeight.bold,
                                                    color: Colors.white),
                                              ),
                                            ),
                                          )
                                        ],
                                      );
                                    });
                              },
                              child: _colorPickerContainer,
                            ),
                          ],
                        ),
                        _emptySpace(context),
                        _addMissionButton,
                      ],
                    ),
                  ),
                ],
              ),
            ),
          )
        : const Scaffold();
  }

  Widget get _colorPickerContainer => Container(
        height: 25,
        width: 25,
        decoration: BoxDecoration(
            color: Colors.white,
            border: Border.all(color: Colors.grey.withOpacity(0.6))),
        child: Icon(
          Icons.colorize_rounded,
          color: ColorsConstants.instance.baseTheme,
          size: 16,
        ),
      );

  Widget get _addMissionButton => Row(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          TextButton(
            onPressed: () {
              gonderilecekPersonelIdler =
                  context.read<ProjectCubit>().secilenPersonelIdler.join(",");
              String safgorevliIdler =
                  gonderilecekPersonelIdler.replaceAll(RegExp(',+,'), ',');
              gonderilecekAmirIdler =
                  context.read<ProjectCubit>().secilenAmirIdler.join(",");
              String safgorevSorumluIdler =
                  gonderilecekAmirIdler.replaceAll(RegExp(',+'), ',');
              debugPrint('_gonderilecekPERSONEL IDLER : $safgorevSorumluIdler');
              debugPrint('_gonderilecekSORUMLU IDLER : $safgorevliIdler');
              if (tfGorevAd.text != '' &&
                  dbSaatbaslangic != '' &&
                  dbSaatbitis != '' &&
                  safgorevliIdler != '' &&
                  safgorevSorumluIdler != '' &&
                  tfAciklama.text != '' &&
                  secilenRenkKodu != '') {
                context
                    .read<MissionsCubit>()
                    .anaGorevEkle(
                        context.read<LoginCubit>().id,
                        context.read<LoginCubit>().token,
                        context.read<LoginCubit>().userfirmId,
                        safgorevliIdler,
                        safgorevSorumluIdler,
                        widget.projeId,
                        tfGorevAd.text,
                        tfAciklama.text,
                        dbSaatbaslangic,
                        dbSaatbitis,
                        secilenRenkKodu,
                        widget.asamaId)
                    .whenComplete(() {
                  _showSnackbarMessage(context, 'Görev Eklendi');
                  Future.delayed(const Duration(milliseconds: 1500), () {
                    Navigator.pop(context, true);
                  });
                });
              } else {
                ToastManager.instance
                    .toastMessageService("Eksik alanları doldurun");
              }
            },
            style: TextButton.styleFrom(
              backgroundColor: ColorsConstants.instance.baseTheme,
            ),
            child: Text(
              ApplicationConstants.instance.moduleSaveTxt,
              style: const TextStyle(color: Colors.white),
            ),
          ),
        ],
      );
}

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

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

void _showSnackbarMessage(BuildContext context, String msg) {
  ScaffoldMessenger.of(context).showSnackBar(
    SnackBar(
      content: Text(msg),
      behavior: SnackBarBehavior.floating,
      backgroundColor: ColorsConstants.instance.baseTheme,
    ),
  );
}
