import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_colorpicker/flutter_colorpicker.dart';
import 'package:hamlemuhcrm/features/projects/view/missions_partial/project_update_main_mission_mixin.dart';

import '../../../../core/constants/app_constants.dart';
import '../../../../core/constants/color_constants.dart';
import '../../../../core/constants/font_styles.dart';
import '../../../../core/cubits/dropdown_cubit.dart';
import '../../../../core/extensions/image_enum_extension.dart';
import '../../../../core/extensions/responsive_extension.dart';
import '../../../../core/utility/toast_manager.dart';
import '../../../../data/dropdown_models/project_stage_api.dart';
import '../../../auth/login/cubit/login_cubit.dart';
import '../../cubit/missions_cubit.dart';
import '../../cubit/project_cubit.dart';
import '../../widgets/employee_type_headline.dart';
import '../../widgets/multiselect_widgets/selected_employee_chip.dart';
import '../../widgets/stage_dropdowns.dart';
import 'model/mission_update_model.dart';

class ProjectUpdateMainMission extends StatefulWidget {
  final MissionUpdateModel gorev;
  final List<AsamalarDD> asamalar;
  final String gelenGorevSorumluAdlar;
  final String gelenGorevliAdlar;

  const ProjectUpdateMainMission(
      {super.key,
      required this.gorev,
      required this.asamalar,
      required this.gelenGorevSorumluAdlar,
      required this.gelenGorevliAdlar});

  @override
  State<ProjectUpdateMainMission> createState() => _ProjectUpdateMainMission();
}

class _ProjectUpdateMainMission extends State<ProjectUpdateMainMission>
    with ProjectUpdateMainMissionMixin {
  @override
  Widget build(BuildContext context) {
    return isFinish
        ? Scaffold(
            appBar: AppBar(
              backgroundColor: Colors.transparent,
              elevation: 0,
              title: Text(widget.gorev.gorevAd,
                  style: FontStyles.instance.appbarTitleStyle),
              centerTitle: true,
              leading: IconButton(
                  onPressed: () {
                    Navigator.pop(context, true);
                    //Navigator.of(context).popUntil((route) => route.isFirst);
                  },
                  icon: const Icon(
                    Icons.arrow_back_ios_new,
                    color: Colors.black54,
                    size: 20,
                  )),
            ),
            body: SingleChildScrollView(
              child: Column(
                children: [
                  SizedBox(
                      height: context.dynamicHeight(0.23),
                      child: ImageEnums.umission.toPageImage),
                  _emptyWidgetSpace(context),
                  Padding(
                    padding: EdgeInsets.symmetric(
                        horizontal: context.dynamicWidth(0.07)),
                    child: Column(
                      children: [
                        Column(
                          children: [
                            _headLine('Görev Adı'),
                            _emptyMiddleHeightSpace(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: 7),
                                  border: OutlineInputBorder(
                                      borderSide: BorderSide.none),
                                ),
                              ),
                            ),
                          ],
                        ),
                        _emptyWidgetSpace(context),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                _headLine('Başlangıç Tarihi'),
                                _emptyMiddleHeightSpace(context),
                                _dateStartContainer,
                              ],
                            ),
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                _headLine('Bitiş Tarihi'),
                                _emptyMiddleHeightSpace(context),
                                _dateEndContainer,
                              ],
                            ),
                          ],
                        ),
                        _emptyWidgetSpace(context),
                        Column(
                          children: [
                            _headLine('Görev Aşama'),
                            StageDropdowns(
                                asamalar: widget.asamalar,
                                projeId: widget.gorev.projeId,
                                asamaId: widget.gorev.asamaId)
                          ],
                        ),
                        _emptyWidgetSpace(context),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                _headLine('Sorumlular'),
                                _emptySpace(context),
                                _sorumlularContainer,
                              ],
                            ),
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                _headLine('Görevliler'),
                                _emptySpace(context),
                                _gorevlilerContainer
                              ],
                            ),
                          ],
                        ),
                        _emptyWidgetSpace(context),
                        context.read<ProjectCubit>().secilenAmirIdler.isNotEmpty
                            ? Column(children: [
                                const EmployeeTypeHeadline(
                                    employeeType: "Sorumlular"),
                                SelectedEmployeeWidget(
                                    selectedLeaders: context
                                        .read<ProjectCubit>()
                                        .secilenAmirAdlar)
                              ])
                            : const SizedBox.shrink(),
                        context
                                .read<ProjectCubit>()
                                .secilenPersonelIdler
                                .isNotEmpty
                            ? Column(children: [
                                const EmployeeTypeHeadline(
                                    employeeType: "Görevliler"),
                                SelectedEmployeeWidget(
                                    selectedLeaders: context
                                        .read<ProjectCubit>()
                                        .secilenPersonelAdlar),
                              ])
                            : const SizedBox.shrink(),
                        _emptyWidgetSpace(context),
                        Column(
                          children: [
                            _headLine('Açıklama'),
                            _emptyMiddleHeightSpace(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),
                                ),
                              ),
                            ),
                          ],
                        ),
                        _emptyWidgetSpace(context),
                        _emptySpace(context),
                        Row(
                          children: [
                            _showColorContainer,
                            SizedBox(width: context.dynamicWidth(0.03)),
                            _customSeperator,
                            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 ?? Colors.blue,
                                              colorHistory: colorhistory,
                                              enableAlpha: false,
                                              paletteType:
                                                  PaletteType.rgbWithBlue,
                                              onHistoryChanged: (value) {},
                                              onColorChanged: (color) {
                                                selectedcolor = color;
                                                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: 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,
                                ),
                              ),
                            ),
                            const Spacer(),
                            _updateMissionButton,
                          ],
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          )
        : const Scaffold();
  }

  Widget get _sorumlularContainer => 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,
                ))
          ],
        ),
      );

  Widget get _gorevlilerContainer => 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,
                ))
          ],
        ),
      );

  Widget get _showColorContainer => Container(
        height: 25,
        width: 25,
        decoration: BoxDecoration(
            color: selectedcolor, borderRadius: BorderRadius.circular(2)),
      );

  Widget get _customSeperator => const Text(
        '|',
        style: TextStyle(
            color: Colors.grey, fontSize: 30, fontWeight: FontWeight.w200),
      );

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

  Widget get _dateStartContainer => Container(
      height: context.dynamicHeight(0.055),
      width: context.dynamicWidth(0.42),
      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,
              )),
        ],
      ));

  Widget get _dateEndContainer => Container(
        height: context.dynamicHeight(0.055),
        width: context.dynamicWidth(0.42),
        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,
                    ))
          ],
        ),
      );
  Widget get _updateMissionButton => Row(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          TextButton(
            onPressed: () {
              gonderilecekAmirIdler =
                  context.read<ProjectCubit>().secilenAmirIdler.join(",");
              String safAmirIdler =
                  gonderilecekAmirIdler.replaceAll(RegExp(',+'), ',');
              gonderilecekPersonelIdler =
                  context.read<ProjectCubit>().secilenPersonelIdler.join(",");
              String safPersonelIdler =
                  gonderilecekPersonelIdler.replaceAll(RegExp(',+,'), ',');

              if (tfGorevAd.text != '' &&
                  dbSaatbaslangic != '' &&
                  dbSaatbitis != '' &&
                  tfAciklama.text != '') {
                MissionUpdateModel gonderilecekNesne = MissionUpdateModel(
                    gorevSorumlular: safAmirIdler,
                    gorevliler: safPersonelIdler,
                    loginuserID: context.read<LoginCubit>().id,
                    token: context.read<LoginCubit>().token,
                    userType: context.read<LoginCubit>().tip,
                    gorevID: widget.gorev.gorevID,
                    gorevUserFirmId: widget.gorev.gorevUserFirmId,
                    projeId: widget.gorev.projeId,
                    gorevAd: tfGorevAd.text,
                    gorevAciklama: tfAciklama.text,
                    dbSaatbaslangic: dbSaatbaslangic,
                    dbSaatbitis: dbSaatbitis,
                    renkKodu:
                        'rgb(${selectedcolor?.red},${selectedcolor?.green},${selectedcolor?.blue})',
                    asamaId: context.read<DropdownCubit>().isStageChange
                        ? context.read<DropdownCubit>().selectedStage
                        : widget.gorev.asamaId);
                context
                    .read<MissionsCubit>()
                    .anaGorevGuncelle(gonderilecekNesne)
                    .whenComplete(() {
                  _snackBarMessage('Görev Güncellendi');
                  Future.delayed(const Duration(milliseconds: 1500), () {
                    Navigator.pop(context, true);
                  });
                });
              }
            },
            style: TextButton.styleFrom(
              backgroundColor: ColorsConstants.instance.baseTheme,
            ),
            child: Text(
              ApplicationConstants.instance.moduleUpdateTxt,
              style: const TextStyle(color: Colors.white),
            ),
          ),
        ],
      );
}

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

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

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

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