import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hamlemuhcrm/features/message/model/query/req_fetch_group.dart';
import 'package:hamlemuhcrm/features/message/view/mixin/message_view_mixin.dart';

import '../../../core/constants/color_constants.dart';
import '../../../core/extensions/responsive_extension.dart';
import '../../../core/route/page_route.dart';
import '../../auth/login/cubit/login_cubit.dart';
import '../cubit/message_cubit.dart';
import '../model/group_latest_message.dart';
import '../model/group_not_message.dart';
import '../model/query/req_one_on_one_group.dart';
import '../widget/connected_container.dart';
import '../widget/latest_message_box_widget.dart';
import '../widget/message_orange_box_widget.dart';
import '../widget/not_message_box_widget.dart';
import 'chat_view.dart';
import 'mixin/shared_messaging_mixin.dart';

class MessageView extends StatefulWidget {
  const MessageView({super.key});

  @override
  State<MessageView> createState() => _MessageViewState();
}

class _MessageViewState extends State<MessageView>
    with MessageViewMixin, SharedMessagingMixin {
// Mesajlar modülü ana sayfa

  // TODO : En son messageview ve chatview sayfalarına timer eklendi bu timerlar ile sürekli istek attırılıyor.
  // Bundan sonra şuanki sürümün apk'sı ile mesajlaşma modülü test edilmeli, problemler çözülmeli ve en son dosya gönderme yapılacak.

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        height: context.dynamicHeight(1),
        padding: const EdgeInsets.symmetric(horizontal: 15),
        child: SingleChildScrollView(
          dragStartBehavior: DragStartBehavior.start,
          child: Column(
            children: [
              _streamCircleAvatar,
              MessageOrangeBox(
                  tfChanged: (value) {
                    messageCubitInstance.searchGroupList(
                        value,
                        ReqFetchGroup(
                            loginuserid: context.read<LoginCubit>().id,
                            token: context.read<LoginCubit>().token,
                            userfirmid: context.read<LoginCubit>().userfirmId));
                  },
                  cubit: messageCubitInstance),
              _headline("Son Görüştüklerim"),
              _gorusulenlerblocB,
              _headline("Çalışma Arkadaşlarım"),
              _firmaGorusulmeyenlerblocB,
              _headline("Diğer Firma Yetkilileri"),
              _digerGorusulmeyenlerblocB,
            ],
          ),
        ),
      ),
    );
  }

  Widget get _streamCircleAvatar => StreamBuilder<RemoteMessage>(
        stream: homeCustomCubitInstance.messageStream,
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            fetchGroup();
            return const ConnectedStatus(isConnected: true);
          } else {
            return const ConnectedStatus(isConnected: false);
          }
        },
      );

  Widget get _gorusulenlerblocB => BlocBuilder<MessageCubit, MessageState>(
      bloc: messageCubitInstance,
      builder: (context, state) {
        switch (state.status) {
          case MessageStatus.loading:
            return _gorusulenlerListVBox(context, state.gorusulenler);

          case MessageStatus.loaded:
            if (state.gorusulenler.isNotEmpty) {
              return _gorusulenlerListVBox(context, state.gorusulenler);
            }
            return const Center(
              child: Text("Başlatılmış Sohbet Yok"),
            );
          case MessageStatus.error:
            return Center(
              child: Text(state.errorMessage),
            );
          default:
            return const Center(
              child: Column(
                children: [
                  Text("Lütfen bekleyiniz..."),
                  CircularProgressIndicator.adaptive(strokeWidth: 1.2)
                ],
              ),
            );
        }
      });

  Widget _gorusulenlerListVBox(
          BuildContext context, List<GroupLatestMessage> gorusulenlerListesi) =>
      ListView.builder(
        shrinkWrap: true,
        itemCount: gorusulenlerListesi.length,
        physics: const NeverScrollableScrollPhysics(),
        itemBuilder: (context, index) {
          return LatestMessageBox(
              model: gorusulenlerListesi[index],
              onpressed: () {
                navigateChatView(gorusulenlerListesi[index]);
              });
        },
      );

  Widget get _firmaGorusulmeyenlerblocB =>
      BlocBuilder<MessageCubit, MessageState>(
        bloc: messageCubitInstance,
        builder: (context, state) {
          if (state.status == MessageStatus.loading) {
            return _firmaGorusulmeyenlerListVBox(
                context, state.firmaGorusulmeyenler);
          }
          if (state.status == MessageStatus.loaded &&
              state.firmaGorusulmeyenler.isNotEmpty) {
            return _firmaGorusulmeyenlerListVBox(
                context, state.firmaGorusulmeyenler);
          }
          if (state.status == MessageStatus.error) {
            return Center(
              child: Text(state.errorMessage),
            );
          }
          return Container();
        },
      );

  Widget _firmaGorusulmeyenlerListVBox(BuildContext context,
          List<GroupNotMessage> firmaGorusulmeyenlerListesi) =>
      ListView.builder(
        itemCount: firmaGorusulmeyenlerListesi.length,
        physics: const NeverScrollableScrollPhysics(),
        shrinkWrap: true,
        itemBuilder: (context, index) {
          return NotMessageBox(
              model: firmaGorusulmeyenlerListesi[index],
              onpressed: () async {
                final ReqOneOnOneGroup model = ReqOneOnOneGroup(
                    loginuserid: context.read<LoginCubit>().id,
                    token: context.read<LoginCubit>().token,
                    userfirmid: context.read<LoginCubit>().userfirmId,
                    karsiUserId:
                        firmaGorusulmeyenlerListesi[index].kullaniciId ?? "");
                await context
                    .read<MessageCubit>()
                    .makeOneOnOneGroup(model)
                    .then((value) => navigateChatView(value));

                // Burada ilk olarak o kişi için grup oluşturulacak ve sonrasında gelen grupid ye göre chat view ekranına yönlendirme yapılacak.
              });
        },
      );

  Widget get _digerGorusulmeyenlerblocB =>
      BlocBuilder<MessageCubit, MessageState>(
        bloc: messageCubitInstance,
        builder: (context, state) {
          if (state.status == MessageStatus.loading) {
            return _digerGorusulmeyenlerListVBox(state.digerGorusulmeyenler);
          }
          if (state.status == MessageStatus.loaded &&
              state.digerGorusulmeyenler.isNotEmpty) {
            return _digerGorusulmeyenlerListVBox(state.digerGorusulmeyenler);
          }
          if (state.status == MessageStatus.error) {
            return Center(
              child: Text(state.errorMessage),
            );
          }
          return Container();
        },
      );

  Widget _digerGorusulmeyenlerListVBox(
          List<GroupNotMessage> digerGorusulmeyenlerListesi) =>
      ListView.builder(
        shrinkWrap: true,
        itemCount: digerGorusulmeyenlerListesi.length,
        physics: const NeverScrollableScrollPhysics(),
        itemBuilder: (context, index) {
          return NotMessageBox(
              model: digerGorusulmeyenlerListesi[index],
              onpressed: () async {
                final ReqOneOnOneGroup model = ReqOneOnOneGroup(
                    loginuserid: context.read<LoginCubit>().id,
                    token: context.read<LoginCubit>().token,
                    userfirmid: context.read<LoginCubit>().userfirmId,
                    karsiUserId:
                        digerGorusulmeyenlerListesi[index].kullaniciId ?? "");
                await context
                    .read<MessageCubit>()
                    .makeOneOnOneGroup(model)
                    .then((value) => navigateChatView(value));
                // Burada ilk olarak o kişi için grup oluşturulacak ve sonrasında gelen grupid ye göre chat view ekranına yönlendirme yapılacak.
              });
        },
      );

  Widget _headline(String txt) => Padding(
        padding: const EdgeInsets.all(8.0),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.start,
          mainAxisSize: MainAxisSize.max,
          children: [
            Text(
              txt,
              style: Theme.of(context).textTheme.headlineSmall?.copyWith(
                  color: ColorsConstants.instance.selectedDateCalendar),
            )
          ],
        ),
      );

  @override
  Future<void> navigateChatView(GroupLatestMessage model) async {
    await callPageKeySetInitialValue(model.grupIdUniq ?? '');
    if (!mounted) return;
    Navigator.of(context).push(CustomPageRoute(
        child: ChatView(
      cubit: messageCubitInstance,
      webView: webViewUrl,
      model: model,
    )));
  }
}
