import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hamlemuhcrm/core/extensions/image_enum_extension.dart';
import 'package:hamlemuhcrm/core/constants/font_styles.dart';
import 'package:hamlemuhcrm/core/extensions/responsive_extension.dart';
import 'package:hamlemuhcrm/features/auth/login/cubit/login_cubit.dart';
import 'package:hamlemuhcrm/features/projects/animation/not_found_lottie.dart';
import 'package:hamlemuhcrm/features/projects/cubit/missions_cubit.dart';
import 'package:hamlemuhcrm/features/projects/cubit/missions_state.dart';
import 'package:hamlemuhcrm/features/projects/model/gorevler.dart';
import 'package:hamlemuhcrm/features/projects/view/missions_partial/project_add_task.dart';
import 'package:hamlemuhcrm/features/projects/widgets/task_card.dart';

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

class ProjectTaskViewPage extends StatefulWidget {
  final Gorevler gorevler;

  const ProjectTaskViewPage({super.key, required this.gorevler});

  @override
  State<ProjectTaskViewPage> createState() => _ProjectTaskViewPageState();
}

class _ProjectTaskViewPageState extends State<ProjectTaskViewPage> {
  final TextEditingController tfTaskName = TextEditingController();
  final TextEditingController tfTaskDescription = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        elevation: 0,
        title: Text(
            widget.gorevler.gorevAd!.length > 28
                ? widget.gorevler.gorevAd!.substring(0, 27)
                : widget.gorevler.gorevAd!,
            style: FontStyles.instance.appbarTitleStyle),
        centerTitle: true,
        leading: IconButton(
            onPressed: () {
              Navigator.pop(context, true);
            },
            icon: const Icon(
              Icons.arrow_back_ios_new,
              color: Colors.black54,
              size: 20,
            )),
      ),
      body: WillPopScope(
        onWillPop: () => backMission(context),
        child: Column(
          children: [
            Expanded(flex: 3, child: _pagePhoto),
            Expanded(flex: 1, child: _headline('Görev Açıklama')),
            Expanded(flex: 1, child: _taskDescription(widget.gorevler)),
            Expanded(flex: 1, child: _headline('Ek Görevler', isAddTask: true)),
            Expanded(flex: 7, child: _taskBlocBuilder),
          ],
        ),
      ),
    );
  }

  Future<bool> backMission(BuildContext context) async {
    Navigator.pop(context, true);
    return true;
  }

  Widget get _pagePhoto => ImageEnums.pstage.toPageImage;

  Widget _headline(String headlineText, {bool isAddTask = false}) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: _emptyHorizontalPaddingValue),
      child: Row(
        mainAxisAlignment: isAddTask
            ? MainAxisAlignment.spaceBetween
            : MainAxisAlignment.start,
        children: [
          Text(
            headlineText,
            style: FontStyles.instance.projectbxBaslik,
          ),
          isAddTask ? _addTaskButton : const SizedBox.shrink(),
        ],
      ),
    );
  }

  double get _emptyHorizontalPaddingValue => context.dynamicWidth(0.06);

  Widget _taskDescription(Gorevler gorevler) {
    return Container(
      height: context.dynamicHeight(0.085),
      width: context.dynamicWidth(0.88),
      alignment: Alignment.topLeft,
      padding: EdgeInsets.only(
          left: context.dynamicWidth(0.02), top: context.dynamicHeight(0.008)),
      decoration: BoxDecoration(
          color: Colors.white,
          border: Border.all(color: Colors.grey.shade400),
          borderRadius: BorderRadius.circular(10)),
      child: SingleChildScrollView(
        child: Text(
          widget.gorevler.gorevAciklama ?? 'Açıklama Girilmemiş',
          style: FontStyles.instance.projectbxDdyazi,
        ),
      ),
    );
  }

  Widget get _isEmptyTaskContainer => Container(
      margin: EdgeInsets.only(bottom: _emptyExpansionTileHeightSpace),
      width: context.dynamicWidth(0.88),
      alignment: Alignment.center,
      decoration: const BoxDecoration(
          color: Colors.transparent,
          borderRadius: BorderRadius.all(Radius.circular(8))),
      child: _isEmptyTaskColumn(_notFoundTaskLottie(context)));

  Widget _isEmptyTaskColumn(Widget child) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        _taskText,
        child,
      ],
    );
  }

  Widget get _addTaskButton => InkWell(
        onTap: navigateToAddTask,
        child: Container(
          width: context.dynamicWidth(0.23),
          height: context.dynamicHeight(0.032),
          decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(5),
              color: ColorsConstants.instance.baseTheme),
          alignment: Alignment.center,
          child: Text(
            'Yeni Ekle',
            style: Theme.of(context)
                .textTheme
                .bodySmall
                ?.copyWith(color: Colors.white, fontWeight: FontWeight.w600),
          ),
        ),
      );

  Widget get _taskText => Text(
        'Bu Ana Göreve Ait \n Ek Görev Yok !',
        textAlign: TextAlign.center,
        style: Theme.of(context)
            .textTheme
            .titleMedium
            ?.copyWith(color: ColorsConstants.instance.baseTheme),
      );

  Widget _notFoundTaskLottie(BuildContext context) {
    return SizedBox(
        height: context.dynamicHeight(0.3), child: const NotFoundLottie());
  }

  void navigateToAddTask() {
    Navigator.push(
        context,
        MaterialPageRoute(
            builder: (context) => ProjectAddTaskPage(
                  gorevliler: widget.gorevler.gorevliler!,
                  anaGorevId: widget.gorevler.gorevId!,
                  gorevProjeId: widget.gorevler.gorevProjeId ?? '0',
                )));
  }

  Widget get _taskBlocBuilder => BlocBuilder<MissionsCubit, MissionState>(
        bloc: MissionsCubit()
          ..anaGorevEkGorevListele(context.read<LoginCubit>().token,
              context.read<LoginCubit>().id, widget.gorevler.gorevId!),
        builder: (context, state) {
          if (state.status == MissionStatus.initial) {
            return const Center(
              child: Text('Bir Tarih Seçin'),
            );
          } else if (state.status == MissionStatus.loading) {
            return const Center(
              child: CircularProgressIndicator(),
            );
          } else if (state.status == MissionStatus.error) {
            return Center(
              child: Text(state.errorMessage),
            );
          } else if (state.status == MissionStatus.loaded &&
              state.gorevEkGorevListesi.isEmpty) {
            return _isEmptyTaskContainer;
          } else {
            return _additionalTaskListView(state.gorevEkGorevListesi);
          }
        },
      );

  Widget _additionalTaskListView(List<Gorevler> gorevler) => ListView.builder(
      padding: EdgeInsets.symmetric(
          horizontal: _emptyHorizontalPaddingValue), // yan paddingler
      itemCount: gorevler.length,
      itemBuilder: (context, indeks) {
        return TaskCard(gorev: gorevler[indeks]);
      });

  double get _emptyExpansionTileHeightSpace => context.dynamicHeight(0.03);

  // NOTE : Görev Adı gösterilmesi gizlendi - açılabilir

  // Widget _taskNameContainer(Gorevler gorevler) {
  //   return Container(
  //     height: context.dynamicHeight(0.048),
  //     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: SingleChildScrollView(
  //       scrollDirection: Axis.horizontal,
  //       child: Text(
  //         gorevler.gorevAd ?? 'Görev Adı Girilmemiş',
  //         style: FontStyles.instance.projectbxDdyazi,
  //       ),
  //     ),
  //   );
  // }

  // NOTE : Eski Ek Görev Listeleme Widget

  /*return _additionalTaskListViewContainer(
                    _taskContent(gorev), */

  // Widget _additionalTaskListViewContainer(Widget child) {
  //   return Container(
  //     margin: EdgeInsets.only(bottom: context.dynamicHeight(0.022)),
  //     padding: EdgeInsets.symmetric(
  //         horizontal: context.dynamicWidth(0.03)), //pano ic bosluk sag sol
  //     decoration: BoxDecoration(
  //       borderRadius: const BorderRadius.all(Radius.circular(10)),
  //       color: Colors.white,
  //       border: Border.all(color: Colors.grey.shade400, width: 1.1),
  //     ),
  //     height: context.dynamicHeight(0.08), //dış container yükseklik//
  //     alignment: Alignment.center,
  //     child: child,
  //   );
  // }

  // Widget _taskContent(Gorevler gorev) {
  //   return Row(
  //     mainAxisAlignment: MainAxisAlignment.spaceBetween,
  //     children: [
  //       Flexible(
  //         //flexible ile yazıyı containera sığdırmasını sağladık
  //         child: Text(
  //           gorev.gorevAd!,
  //           style:
  //               Theme.of(context).textTheme.bodySmall?.copyWith(color: ColorsConstants.instance.anatema),
  //         ),
  //       ),
  //       _checkbox(gorev),
  //     ],
  //   );
  // }

  // NOTE : ShowBottomSheet özelliği denendi

  // void _showDialogAddTask(BuildContext context) {
  //   showModalBottomSheet(
  //       context: context,
  //       shape: const RoundedRectangleBorder(
  //           borderRadius: BorderRadius.vertical(top: Radius.circular(20))),
  //       isScrollControlled: true,
  //       barrierColor: Colors.grey.withOpacity(0.5),
  //       builder: (context) {
  //         return SingleChildScrollView(
  //           child: AddTaskSheetTextField(
  //             tfTaskName: tfTaskName,
  //             tfTaskDescription: tfTaskDescription,
  //             onPressed: () {
  //               debugPrint(tfTaskName.text);
  //               //Navigator.pop(context);
  //             },
  //           ),
  //         );
  //       });
  // }
}
