import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hamlemuhcrm/core/constants/app_constants.dart';
import 'package:hamlemuhcrm/core/constants/color_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/core/extensions/string_extension.dart';
import 'package:hamlemuhcrm/core/init/theme/app_theme.dart';
import 'package:hamlemuhcrm/features/calendar/constants/suggestion_constant.dart';
import 'package:hamlemuhcrm/features/calendar/cubit/suggestion_cubit.dart';
import 'package:hamlemuhcrm/features/calendar/model/suggestion_model.dart';
import 'package:hamlemuhcrm/features/calendar/view_mixin/approval_list_agenda_suggestion_view_mixin.dart';
import 'package:hamlemuhcrm/features/calendar/widgets/suggestion_card_item.dart';

import '../../../core/utility/toast_manager.dart';
import '../../auth/login/cubit/login_cubit.dart';
import '../utility/calendar_textfield_input.dart';

/// Gündem Önerme Sayfası

class ApprovalListAgendaSuggestionView extends StatefulWidget {
  final String toplantiID;
  final String toplantiAd;
  const ApprovalListAgendaSuggestionView(
      {super.key, required this.toplantiID, required this.toplantiAd});

  @override
  State<ApprovalListAgendaSuggestionView> createState() =>
      _ApprovalListAgendaSuggestionViewState();
}

class _ApprovalListAgendaSuggestionViewState
    extends State<ApprovalListAgendaSuggestionView>
    with ApprovalListAgendaSuggestionMixin {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: _appBar(),
      body: SingleChildScrollView(
        child: Padding(
          padding: _pagePaddingHorizontal,
          child: Column(
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  _tfContainer(controller, isLongInput: true),
                  _addSuggestionButton(controller),
                ],
              ),
              _emptyHeightSpaceNormal,
              _mainContainer,
            ],
          ),
        ),
      ),
    );
  }

  AppBar _appBar() {
    return AppBar(
      backgroundColor: Colors.transparent,
      elevation: 0,
      title: Text(
          '${toplantiBaslikKucult(widget.toplantiAd)} tplnt id: ${widget.toplantiID}',
          style: FontStyles.instance.appbarTitleStyle),
      centerTitle: true,
      iconTheme: const IconThemeData(color: Colors.black87),
    );
  }

  String toplantiBaslikKucult(String toplantiBaslik) =>
      toplantiBaslik.length > 35
          ? '${toplantiBaslik.substring(0, 34)}..'
          : toplantiBaslik;

  EdgeInsets get _pagePaddingHorizontal =>
      EdgeInsets.symmetric(horizontal: context.dynamicWidth(0.06));

  Widget get _emptyHeightSpaceNormal => SizedBox(
        height: context.dynamicHeight(0.03),
      );

  Widget get _emptyHeightSpaceLow => SizedBox(
        height: context.dynamicHeight(0.01),
      );

  Widget _tfContainer(TextEditingController tf, {bool isLongInput = false}) =>
      Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Text(SuggestionConstants.instance.suggestionsHeadLineTxt,
                  style: FontStyles.instance.employeetbxBaslik)
            ],
          ),
          _emptyHeightSpaceLow,
          Container(
              height: context.dynamicHeight(isLongInput ? 0.1 : 0.05),
              width: context.dynamicWidth(0.55),
              alignment: Alignment.center,
              decoration: BoxDecoration(
                  color: Colors.white,
                  border: Border.all(color: Colors.grey.shade400),
                  borderRadius: BorderRadius.circular(10)),
              child:
                  _textFormField(tf, isLongInput: isLongInput ? true : false)),
        ],
      );

  Widget _textFormField(TextEditingController tfcontroller,
          {bool isLongInput = false}) =>
      TextFormField(
        controller: tfcontroller,
        focusNode: suggestionNode,
        magnifierConfiguration: TextMagnifierConfiguration.disabled,
        decoration: CalendarTextFieldInput(context,
            hintTxt: SuggestionConstants.instance.addSuggestionsTfHintTxt,
            isLongInput: isLongInput ? true : false),
        maxLines: isLongInput ? 10 : 1,
        cursorColor: ColorsConstants.instance.baseTheme,
      );

  Widget _addSuggestionButton(TextEditingController tfcontroller) => TextButton(
      onPressed: () {
        if (tfcontroller.text.isNotEmpty) {
          context.read<SuggestionCubit>().addNewSuggestion(
              context.read<LoginCubit>().id,
              context.read<LoginCubit>().token,
              context.read<LoginCubit>().userfirmId,
              widget.toplantiID,
              controller.text);
          _suggestionApprovalShowDialog(context);
          suggestionNode.unfocus();
          controller.clear();
        } else {
          ToastManager.instance
              .toastMessageService('Boş Öneri Ekleyemezsiniz !');
        }
      },
      style: AppTheme.mainColorRoundedButton,
      child: Text(
        SuggestionConstants.instance.addSuggestionsButtonTxt,
        style: Theme.of(context)
            .textTheme
            .labelMedium
            ?.copyWith(color: Colors.white),
      ));

  Widget get _mainContainer => Container(
        height: context.dynamicHeight(0.55),
        decoration: BoxDecoration(
          color: ColorsConstants.instance.appWhite,
          borderRadius: BorderRadius.circular(
              ApplicationConstants.instance.kBorderRadius),
          border:
              Border.all(color: ColorsConstants.instance.iconColor, width: 1.2),
        ),
        child: _suggestionCubit(context),
      );

  Widget _suggestionCubit(BuildContext context) {
    return BlocBuilder<SuggestionCubit, SuggestionState>(
      builder: (context, state) {
        if (state.onaylananGundemler.isEmpty & !state.isCompleted &&
            !state.isLoading &&
            !state.isError) {
          return Center(
            child: Text(
              'Boş Liste',
              style: Theme.of(context).textTheme.headlineSmall,
            ),
          );
        } else if (state.isLoading & !state.isCompleted &&
            !state.isLoaded &&
            !state.isError) {
          return const Center(
            child: CircularProgressIndicator(),
          );
        } else if (state.isCompleted & !state.isLoading && !state.isError) {
          final gundemList = state.onaylananGundemler;
          return _listViewSuggestions(gundemList);
        } else {
          return const Center(
            child: Text('Hata Oluştu'),
          );
        }
      },
    );
  }

  Widget _listViewSuggestions(List<SuggestionModel> gundemList) =>
      BlocBuilder<SuggestionCubit, SuggestionState>(builder: (context, state) {
        return ListView.builder(
            itemCount: gundemList.length,
            itemBuilder: (context, index) {
              var gundemIndex = gundemList[index];
              return SuggestionCardItem(
                isVerified: gundemIndex.togundemOnay == "1" &&
                        gundemIndex.togundemDurum == "1"
                    ? true
                    : false,
                date: ''.toTrTypeNoHour(
                    gundemIndex.togundemEklenmeTarihi ?? '2023-01-01'),
                profileImage: gundemIndex.userImage ?? 'bosresimyok.jpg',
                meetTitle: gundemIndex.togundemMetin ?? '',
                suggestedName:
                    '${gundemIndex.firstName ?? ''} ${gundemIndex.lastName ?? ''}',
                durumVeOnay:
                    '${gundemIndex.togundemDurum} - ${gundemIndex.togundemOnay}',
              );
            });
      });

  void _suggestionApprovalShowDialog(BuildContext context) {
    showDialog(
      context: context,
      barrierDismissible:
          false, // Dışarı tıklandığında diyalogu kapatma engelleme
      builder: (BuildContext context) {
        // Diyalog 4 saniye sonra otomatik olarak kapanacak
        Future.delayed(const Duration(seconds: 4), () {
          Navigator.of(context).pop(true);
        });

        return Dialog(
          insetAnimationCurve: Curves.bounceOut,
          insetAnimationDuration: const Duration(milliseconds: 1500),
          backgroundColor: ColorsConstants.instance.appWaterGreen,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(20.0),
          ), // Bu satır border radius'u ayarlar
          child: SizedBox(
            height: context.dynamicHeight(0.4),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                const Spacer(),
                Expanded(child: ImageEnums.meeting.toPageImage),
                SizedBox(
                  height: context.dynamicHeight(0.03),
                ),
                Text(
                  suggestionApprovalText,
                  style: Theme.of(context).textTheme.titleMedium?.copyWith(
                      fontWeight: FontWeight.bold, color: Colors.white),
                  textAlign: TextAlign.center,
                ),
                const Spacer()
              ],
            ),
          ),
        );
      },
    );
  }
}
