import 'package:cached_network_image/cached_network_image.dart';
import 'package:file_picker/file_picker.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hamlemuhcrm/core/extensions/responsive_extension.dart';
import 'package:hamlemuhcrm/core/extensions/string_extension.dart';
import 'package:permission_handler/permission_handler.dart';

import '../../../core/constants/color_constants.dart';
import '../../../core/constants/url_services_constant.dart';
import '../../auth/login/cubit/login_cubit.dart';
import '../constant/message_constant.dart';
import '../cubit/message_cubit.dart';
import '../model/group_latest_message.dart';
import '../widget/web_view_chat.dart';
import 'group_detail_view.dart';
import 'mixin/chat_view_mixin.dart';
import 'mixin/shared_messaging_mixin.dart';

part '../widget/loading_indicator.dart';

class ChatView extends StatefulWidget {
  final MessageCubit cubit;
  final GroupLatestMessage? model;
  final String webView;

  const ChatView({
    Key? key,
    required this.cubit,
    required this.webView,
    this.model,
  }) : super(key: key);

  @override
  State<ChatView> createState() => _ChatViewState();
}

class _ChatViewState extends State<ChatView>
    with ChatViewMixin, SharedMessagingMixin {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      //normal widget arkaplan renk Colors.grey.shade300,
      appBar: buildAppBar(context),
      body: Column(
        children: [
          Expanded(flex: 7, child: _blocB),
          Expanded(
            flex: 1,
            child: Form(
              key: messageKey,
              child: (widget.model?.grupAktifMi ?? false) == false
                  ? _notPermissionChat
                  : Row(
                      children: [
                        _messageArea,
                        _messageSendButton,
                      ],
                    ),
            ),
          )
        ],
      ),
    );
  }

  AppBar buildAppBar(BuildContext appBarContext) {
    return AppBar(
      iconTheme: const IconThemeData(color: Colors.white),
      backgroundColor: ColorsConstants.instance.baseTheme,
      title: Row(
        children: [
          _streamCircleAvatar,
          const SizedBox(width: 15),
          Text(
            ''.shortNameExt(widget.model?.grupAdi ?? "Kisi", maxLength: 22),
            style: Theme.of(context)
                .textTheme
                .labelLarge
                ?.copyWith(color: Colors.white),
          ),
        ],
      ),
      actions: [
        isGroupType(widget.model!)
            ? IconButton(
                onPressed: () => navigateDetailView(widget.model!),
                icon: const Icon(Icons.more_horiz))
            : const SizedBox(
                height: 0,
              ),
      ],
    );
  }

  bool isGroupType(GroupLatestMessage model) {
    bool isManagement = false;

    // gelen modelin yoneticilerine bakıyoruz
    // bu grup eğer çoklu bir grup ise zaten grupYoneticileri kismi dolu olacak iki kisi arasında olan mesaj gruplarında null olur

    if (model.grupYoneticileri != null) {
      isManagement = model.grupYoneticileri!
          .split('h')
          .contains(context.read<LoginCubit>().id);
    }

    return isManagement;
  }

  void navigateDetailView(GroupLatestMessage model) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => GroupDetailView(
          cubit: widget.cubit,
          group: model,
        ),
      ),
    );
  }

  Widget get _streamCircleAvatar => StreamBuilder<RemoteMessage>(
        stream: homeCustomCubitInstance.messageStream,
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            fetchLastMessage();
            return CircleAvatar(
              radius: 22,
              backgroundColor: ColorsConstants.instance.appGreen,
              child: CircleAvatar(
                radius: 20,
                child: CachedNetworkImage(
                  height: context.dynamicHeight(0.08),
                  fit: BoxFit.fill,
                  imageUrl:
                      _groupImageCheck(widget.model ?? GroupLatestMessage()),
                  placeholder: (context, url) => CircleAvatar(
                    radius: 30,
                    backgroundColor: Colors.grey.shade200,
                  ),
                  imageBuilder: (context, imageProvider) {
                    return CircleAvatar(
                      radius: 32,
                      backgroundColor: Colors.grey,
                      child: CircleAvatar(
                        radius: 30,
                        backgroundImage: imageProvider,
                      ),
                    );
                  },
                ),
              ),
            );
          } else {
            return CircleAvatar(
              radius: 22,
              backgroundColor: ColorsConstants.instance.appBlue,
              child: CircleAvatar(
                radius: 20,
                child: CachedNetworkImage(
                  height: context.dynamicHeight(0.08),
                  fit: BoxFit.fill,
                  imageUrl:
                      _groupImageCheck(widget.model ?? GroupLatestMessage()),
                  placeholder: (context, url) => CircleAvatar(
                    radius: 30,
                    backgroundColor: Colors.grey.shade200,
                  ),
                  imageBuilder: (context, imageProvider) {
                    return CircleAvatar(
                      radius: 32,
                      backgroundColor: Colors.grey,
                      child: CircleAvatar(
                        radius: 30,
                        backgroundImage: imageProvider,
                      ),
                    );
                  },
                ),
              ),
            );
          }
        },
      );

  String _groupImageCheck(GroupLatestMessage model) {
    if (model.grupKullaniciSayisi != null && model.grupKullaniciSayisi! > 2) {
      return (model.kullaniciImage == null || model.kullaniciImage == "")
          ? URLAPIService.instance.defaultPhotoUrl
          : URLAPIService.instance.defaultPhotoUrl;
    }
    return (model.kullaniciImage == null || model.kullaniciImage == "")
        ? URLAPIService.instance.defaultPhotoUrl
        : '${URLAPIService.instance.fileBaseURL}/upload-user/${model.kullaniciImage}';
  }

  Widget get _notPermissionChat => Expanded(
        child: Container(
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(10),
                color: ColorsConstants.instance.appWhite,
                boxShadow: [
                  BoxShadow(
                      blurRadius: 7,
                      offset: const Offset(1.5, 1),
                      color: ColorsConstants.instance.appGrey)
                ]),
            alignment: Alignment.center,
            child: Text(
              MessageConstant.instance.notPermissionGroupTxt,
              style: Theme.of(context).textTheme.headlineSmall?.copyWith(
                  color: ColorsConstants.instance.containerBorderGreyColor),
            )),
      );

  Widget get _messageArea => Expanded(
        child: Container(
          padding: const EdgeInsets.symmetric(horizontal: 20),
          margin: const EdgeInsets.only(left: 10),
          decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(10),
              color: ColorsConstants.instance.appWhite,
              boxShadow: [
                BoxShadow(
                    blurRadius: 7,
                    offset: const Offset(1.5, 1),
                    color: ColorsConstants.instance.appGrey)
              ]),
          child: TextFormField(
            controller: messageController,
            maxLines: 2,
            onChanged: textAreaChanged,
            decoration: InputDecoration(
                border: const OutlineInputBorder(
                  borderSide: BorderSide.none,
                ),
                hintText: "Mesaj",
                contentPadding:
                    const EdgeInsets.symmetric(horizontal: 2, vertical: 2),
                suffixIcon: _selectedFile),
          ),
        ),
      );

  Widget get _messageSendButton => ValueListenableBuilder<String>(
        valueListenable: textChanged,
        builder: (context, value, child) => IconButton.filled(
          highlightColor: ColorsConstants.instance.containerBorderGreyColor,
          visualDensity: VisualDensity.adaptivePlatformDensity,
          padding: EdgeInsets.zero,
          onPressed: textChanged.value == "" ? null : sendMessage,
          style: ButtonStyle(
            backgroundColor:
                MaterialStatePropertyAll(ColorsConstants.instance.baseTheme),
          ),
          icon: const Icon(Icons.send),
        ),
      );

  Widget get _blocB => WebViewChatWidget(url: widget.webView);

  // YEDEK CHAT SAYFASI
  // Widget get _blocB => BlocBuilder<MessageCubit, MessageState>(
  //       bloc: messageCubitInstance
  //         ..fetchPaginationMessageList(ReqFetchMessage(
  //             loginuserid: context.read<LoginCubit>().id,
  //             token: context.read<LoginCubit>().token,
  //             userfirmid: context.read<LoginCubit>().userfirmId,
  //             grupId: widget.model!.grupId ?? "")),
  //       builder: (context, state) {
  //         switch (state.status) {
  //           case MessageStatus.error:
  //             return const Center(
  //               child: Text("Bir hata oldu"),
  //             );
  //           case MessageStatus.loaded:
  //             if (state.mesajListesi.isEmpty) {
  //               return Center(
  //                 child: Column(
  //                   mainAxisAlignment: MainAxisAlignment.center,
  //                   children: [
  //                     _newChatAnimation,
  //                     _notFoundMessage(context),
  //                   ],
  //                 ),
  //               );
  //             }
  //             return _scrollBar(_messageListV(state));
  //           case MessageStatus.loading:
  //             return _scrollBar(_messageListV(state));
  //           case MessageStatus.initial:
  //             return const Center(
  //               child: CircularProgressIndicator.adaptive(),
  //             );
  //           default:
  //             return const Center(
  //               child: Column(
  //                 children: [
  //                   Text("Lütfen bekleyiniz..."),
  //                   CircularProgressIndicator.adaptive(strokeWidth: 1.2)
  //                 ],
  //               ),
  //             );
  //         }
  //       },
  //     );

  // Widget _scrollBar(Widget child) {
  //   return Scrollbar(
  //     thickness: 6,
  //     controller: scrollController,
  //     radius: const Radius.circular(10),
  //     child: child,
  //   );
  // }

  // Widget _messageListV(MessageState state) => ListView.builder(
  //       controller: scrollController,
  //       // yukarı kaydırma işleminde istek atılacağı için reverse true olarak kullandım
  //       reverse: true,
  //       shrinkWrap: true,
  //       itemCount: state.hasReachedMax
  //           ? state.mesajListesi.length
  //           : state.mesajListesi.length > 10
  //               ? state.mesajListesi.length + 1
  //               : state.mesajListesi.length,
  //       itemBuilder: (context, index) {
  //         if (index >= state.mesajListesi.length) {
  //           return const LoadingIndicator();
  //         } else {
  //           if (state.mesajListesi[index].mesajGonderenId ==
  //               context.read<LoginCubit>().id) {
  //             // Kullanıcının attığı Mesajlar
  //             return OwnCardWidget(message: state.mesajListesi[index]);
  //           } else {
  //             // Karşı Tarafın Yazdığı Mesajlar
  //             return ReplyCardWidget(message: state.mesajListesi[index]);
  //           }
  //         }
  //       },
  //     );

  // Widget get _newChatAnimation {
  //   return SizedBox(
  //       height: context.dynamicHeight(0.3), child: const NewChatLottie());
  // }

  //   Widget _notFoundMessage(BuildContext context) =>
  //     Text("Hiç Sohbet Başlatmadınız",
  //         style: Theme.of(context)
  //             .textTheme
  //             .titleMedium
  //             ?.copyWith(color: ColorsConstants.instance.appGrey));

  Widget get _selectedFile => ValueListenableBuilder(
      valueListenable: fileName,
      builder: (context, value, child) => IconButton.filled(
          style: IconButton.styleFrom(
              backgroundColor:
                  result != null ? Colors.orange : Colors.transparent),
          onPressed: () {
            if (result != null) return customShowBottomSheet();
            pickFile().then((value) => customShowBottomSheet);
          },
          padding: EdgeInsets.zero,
          icon: Icon(
            Icons.attach_file_outlined,
            color: result != null ? Colors.white : Colors.black54,
          )));

  @override
  Future<void> pickFile() async {
    var status = await Permission.storage.status;
    if (status.isGranted) {
      result = await FilePicker.platform.pickFiles();

      if (result != null) {
        fileName.value = result!.files.single.name;
      }
    } else {
      // Kullanıcıdan izin iste
      if (await Permission.storage.request().isGranted) {
        pickFile();
      }
    }
    getFileIcon;
  }

  @override
  void customShowBottomSheet() {
    showModalBottomSheet<void>(
      context: context,
      builder: (BuildContext context) {
        return Container(
          height: MediaQuery.sizeOf(context).height / 2,
          padding: const EdgeInsets.all(16),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            mainAxisSize: MainAxisSize.min,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  IconButton(
                    icon: const Icon(Icons.close),
                    onPressed: () {
                      resetFile();
                      Navigator.of(context).pop();
                    },
                  ),
                ],
              ),
              Wrap(
                alignment: WrapAlignment.center,
                crossAxisAlignment: WrapCrossAlignment.center,
                direction: Axis.vertical,
                spacing: 10,
                children: [
                  Icon(
                    getFileIcon(),
                    size: 60,
                  ),
                  ValueListenableBuilder(
                      valueListenable: fileName,
                      builder: (context, value, child) => Text(fileName.value,
                          overflow: TextOverflow.ellipsis)),
                ],
              ),
              ValueListenableBuilder<double>(
                valueListenable: uploadProgress,
                builder: (context, value, child) => LinearProgressIndicator(
                    backgroundColor: ColorsConstants.instance.appGrey,
                    color: ColorsConstants.instance.baseTheme,
                    value: value),
              ),
              Row(
                crossAxisAlignment: CrossAxisAlignment.end,
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  FilledButton.icon(
                    style: FilledButton.styleFrom(
                        backgroundColor: ColorsConstants.instance.baseTheme),
                    label: const Text("Gönder"),
                    icon: const Icon(
                      Icons.send,
                    ),
                    onPressed: result != null
                        ? () async {
                            /// Burada sunucuya resim göndereceğimiz metot çalışacak.
                            await sendMessage().then((value) {
                              /// Dosyayı sıfırlıcaz ve bottom sheet kapanacak
                              resetFile();
                              Navigator.of(context).pop();
                            });
                          }
                        : null,
                  ),
                ],
              ),
            ],
          ),
        );
      },
    );
  }
}
