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/responsive_extension.dart';
import 'package:hamlemuhcrm/core/extensions/string_extension.dart';
import 'package:hamlemuhcrm/features/auth/login/cubit/login_cubit.dart';
import 'package:hamlemuhcrm/features/calendar/cubit/suggestion_cubit.dart';
import 'package:hamlemuhcrm/features/calendar/model/suggestion_model.dart';
import 'package:hamlemuhcrm/features/calendar/widgets/suggestion_card_item.dart';
import '../view_mixin/moderator_list_agenda_suggestion_view_mixin.dart';

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

  @override
  State<ModeratorListAgendaSuggestionView> createState() =>
      _ModeratorListAgendaSuggestionViewState();
}

class _ModeratorListAgendaSuggestionViewState
    extends State<ModeratorListAgendaSuggestionView>
    with ModeratorListAgendaSuggestionMixin {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: _appBar(),
      body: SingleChildScrollView(
        child: Padding(
          padding: _pagePaddingHorizontal,
          child: Column(
            children: [
              _tfContainer('Onay Bekleyen Gündem Önerileri'),
              _emptyHeightSpaceNormal,
              _mainContainer,
              _emptyHeightSpaceNormal,
              _tfContainer('Onaylanmış Gündem Önerileri'),
              _emptyHeightSpaceNormal,
              _mainConfirmSugListContainer,
            ],
          ),
        ),
      ),
    );
  }

  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 > 32
          ? toplantiBaslik.substring(0, 31)
          : toplantiBaslik;

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

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

  Widget _tfContainer(String headline) => Container(
        height: context.dynamicHeight(0.05),
        decoration: BoxDecoration(
            color: ColorsConstants.instance.baseTheme,
            borderRadius: BorderRadius.circular(6)),
        child: Center(
          child: Text(headline,
              style: FontStyles.instance.girisBtnYazi.copyWith(fontSize: 16)),
        ),
      );

  Widget get _mainContainer => Container(
        height: context.dynamicHeight(0.35),
        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.bekleyenGundemler.isEmpty &&
            !state.isCompleted &&
            !state.isLoading &&
            !state.isError &&
            !state.isLoaded) {
          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.bekleyenGundemler;
          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,
                durumVeOnay:
                    '${gundemIndex.togundemDurum} - ${gundemIndex.togundemOnay}',
                date: ''.toTrTypeNoHour(
                    gundemIndex.togundemEklenmeTarihi ?? '2023-01-01'),
                profileImage: gundemIndex.userImage ?? 'bosresimyok.jpg',
                meetTitle: gundemIndex.togundemMetin ?? '',
                suggestedName:
                    '${gundemIndex.firstName ?? ''} ${gundemIndex.lastName ?? ''}',
                onPressedConfirm: () {
                  context.read<SuggestionCubit>().acceptSuggestion(
                      context.read<LoginCubit>().id,
                      context.read<LoginCubit>().token,
                      gundemIndex.togundemId ?? "",
                      "1", // Confirm
                      widget.toplantiID);
                },
                onPressedDeleted: () {
                  context.read<SuggestionCubit>().acceptSuggestion(
                      context.read<LoginCubit>().id,
                      context.read<LoginCubit>().token,
                      gundemIndex.togundemId ?? "",
                      "0", // Delete
                      widget.toplantiID);
                },
              );
            });
      });

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

  Widget _confirmSuggestionCubit(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 _listViewConfirmSuggestions(gundemList);
        } else {
          return const Center(
            child: Text('Hata Oluştu'),
          );
        }
      },
    );
  }

  Widget _listViewConfirmSuggestions(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,
                durumVeOnay:
                    '${gundemIndex.togundemDurum} - ${gundemIndex.togundemOnay}',
                date: ''.toTrTypeNoHour(
                    gundemIndex.togundemEklenmeTarihi ?? '2023-01-01'),
                profileImage: gundemIndex.userImage ?? 'bosresimyok.jpg',
                meetTitle: gundemIndex.togundemMetin ?? '',
                suggestedName:
                    '${gundemIndex.firstName ?? ''} ${gundemIndex.lastName ?? ''}',
                onPressedConfirm: () {
                  context.read<SuggestionCubit>().acceptSuggestion(
                      context.read<LoginCubit>().id,
                      context.read<LoginCubit>().token,
                      gundemIndex.togundemId ?? "",
                      "1", // Confirm
                      widget.toplantiID);
                },
                onPressedDeleted: () {
                  context.read<SuggestionCubit>().acceptSuggestion(
                      context.read<LoginCubit>().id,
                      context.read<LoginCubit>().token,
                      gundemIndex.togundemId ?? "",
                      "0", // Delete
                      widget.toplantiID);
                },
              );
            });
      });
}
