import 'dart:async';
import 'dart:io';
import 'package:auto_size_text/auto_size_text.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:road24_mobile/data/repository/ChatRepository.dart';
import 'package:road24_mobile/model/models/ChatMessage.dart';
import 'package:road24_mobile/model/models/rocket_chat_state.dart';
import 'package:road24_mobile/model/utils/styles/AppColors.dart';
import 'package:road24_mobile/model/utils/styles/AppStyles.dart';
import 'package:road24_mobile/utils/frequent_widgets.dart';
import 'package:road24_mobile/view/built/i18n.dart';
import 'package:sizer/sizer.dart';
import 'package:url_launcher/url_launcher.dart';

import '../../my_app.dart';
import '../firebase.dart';
import 'message/chat_input.dart';
import 'message/message.dart';

class SupportChatPage extends StatefulWidget {
  final String? phoneNumber;

  final bool isChat;

  const SupportChatPage({Key? key, this.phoneNumber, this.isChat = false})
      : super(key: key);

  @override
  _SupportChatPageState createState() => _SupportChatPageState();
}

class _SupportChatPageState extends State<SupportChatPage> {
  var repository = ChatRepository();

  late bool isChat;

  @override
  void initState() {
    super.initState();

    isChat = widget.isChat;

    if (isChat) {
      initRocketChat();
    }
    // if (widget.phoneNumber != null &&
    //     MyApp.preferences?.getPhoneNumber() != "" &&
    //     widget.phoneNumber != MyApp.preferences?.getPhoneNumber()) {
    //   MyApp.preferences?.setRoomId(null);
    // }
  }

  @override
  void dispose() {
    // FCMWrapper.onSupportPage = false;
    repository.saveLastVisit();
    super.dispose();
  }

  initRocketChat() {
    WidgetsBinding.instance!.addPostFrameCallback((_) async {
      await repository.initRocketLivechat(widget.phoneNumber);

      if (MyApp.preferences?.getChatToken() == null)
        FirebaseNotifications().firebaseCloudMessagingListeners(isChat: true);
    });
  }

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<RocketChatState>(
      initialData: repository.initialState,
      stream: repository.state,
      builder: (context, snapshot) {
        final state = snapshot.data;
        print("onlayn....${state?.config?.config?.online.toString()}");
        // final agentOnline = false;
        // final agentOnline = state?.config?.config?.online;

        // print("online..." + agentOnline.toString());

        return GestureDetector(
          onPanUpdate: (direction) {
            if (direction.delta.dy > 0) {
              // swiping in down direction
              if (Platform.isIOS)
                WidgetsBinding.instance?.focusManager.primaryFocus?.unfocus();
            }
          },
          child: Scaffold(
            backgroundColor: AppColors.appPrimaryColor,
            appBar: AppBar(
              automaticallyImplyLeading: false,
              leading: FrequentWidgets.appBarBackButton(context),
              elevation: 0.0,
              backgroundColor: Colors.transparent,
              iconTheme: const IconThemeData(color: Colors.black),
              centerTitle: true,
              title: Column(
                children: <Widget>[
                  Text(
                    S.of(context).support,
                    style: const TextStyle(
                        fontWeight: FontWeight.w600,
                        color: Colors.black,
                        fontSize: 19.0),
                  ),
                  // _agentStatus(agentOnline),
                ],
              ),
            ),
            body: AnimatedSwitcher(
              duration: Duration(milliseconds: 300),
              child: !isChat
                  ? _offlineBody()
                  : Builder(
                      builder: (context) {
                        final loadingIndicator = const Center(
                          child: CircularProgressIndicator(
                            valueColor:
                                AlwaysStoppedAnimation<Color>(Colors.blue),
                          ),
                        );

                        if (state == null) return loadingIndicator;

                        if (state.isLoading!) return loadingIndicator;

                        // if (agentOnline ?? false)
                        return OnlineBody(
                          state: state,
                          repo: repository,
                        );
                        // else
                        //   return _offlineBody();
                      },
                    ),
            ),
          ),
        );
      },
    );
  }

  _offlineBody() {
    return Stack(
      children: [
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 12),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              // AutoSizeText(
              //   S.of(context).chat_offline_title,
              //   textAlign: TextAlign.center,
              //   style: TextStyle(fontSize: 18, fontWeight: FontWeight.w700),
              // ),
              // SizedBox(
              //   height: 30,
              // ),
              Container(
                width: double.infinity,
                padding:
                    const EdgeInsets.symmetric(horizontal: 16.0, vertical: 32),
                decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(16)),
                child: Column(
                  children: [
                    chatRowTitleText(S.of(context).chat_working_time_title),
                    SizedBox(
                      height: 10,
                    ),
                    chatRowDaysAndHours(S.of(context).chat_working_days,
                        S.of(context).chat_working_time),
                    SizedBox(
                      height: 4,
                    ),
                    chatRowDaysAndHours(S.of(context).chat_nonworking_days,
                        S.of(context).chat_nonworking_time),
                    SizedBox(
                      height: 12,
                    ),
                    chatRowTitleText(S.of(context).chat_holiday_title),
                    SizedBox(
                      height: 10,
                    ),
                    chatRowDaysAndHours(S.of(context).chat_holiday_days,
                        S.of(context).chat_nonworking_time),
                  ],
                ),
              ),
              SizedBox(
                height: 30,
              ),
              AutoSizeText(
                S.of(context).chat_if_needed_text,
                textAlign: TextAlign.center,
                style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600),
              ),

              // SizedBox(
              //   height: 6,
              // ),
              // InkWell(
              //     splashColor: Colors.transparent,
              //     highlightColor: Colors.transparent,
              //     onTap: () {
              //       launch("tel://951931312");
              //     },
              //     child: Row(
              //       mainAxisAlignment: MainAxisAlignment.center,
              //       crossAxisAlignment: CrossAxisAlignment.center,
              //       children: [
              //         Icon(
              //           Icons.phone,
              //           color: Colors.black,
              //           size: 17,
              //         ),
              //         SizedBox(
              //           width: 8,
              //         ),
              //         chatRowTitleText("+998 95 193 13 12", fontSize: 16),
              //       ],
              //     )),
              // SizedBox(
              //   height: 6,
              // ),
              // Text(S.of(context).or_tg_bot,
              //     textAlign: TextAlign.center,
              //     style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600)),
              SizedBox(
                height: 8,
              ),
              InkWell(
                onTap: () {
                  launch(
                    "https://t.me/road24uz_feedback_bot",
                    forceSafariVC: false,
                  );
                },
                child: Text("@road24uz_feedback_bot",
                    style: TextStyle(
                        decoration: TextDecoration.underline,
                        color: Colors.blue,
                        fontSize: 15)),
              ),

              // SizedBox(height: 80),

              // ElevatedButton(
              //     style: ElevatedButton.styleFrom(
              //         side: BorderSide(width: 0.6),
              //         primary: Colors.transparent,
              //         padding: EdgeInsets.symmetric(horizontal: 20, vertical: 8),
              //         elevation: 0),
              //     onPressed: () {
              //       // launch("tel://951931312");
              //     },
              //     child: Row(
              //       mainAxisSize: MainAxisSize.min,
              //       mainAxisAlignment: MainAxisAlignment.center,
              //       crossAxisAlignment: CrossAxisAlignment.center,
              //       children: [
              //         Image.asset(
              //           "assets/customer-service.png",
              //           width: 30,
              //           height: 30,
              //           color: Colors.white,
              //         ),
              //         SizedBox(
              //           width: 8,
              //         ),
              //         chatRowTitleText("Chatni boshlash"),
              //       ],
              //     )),
            ],
          ),
        ),
        Positioned(
          bottom: 20,
          right: 12,
          left: 12,
          child: ElevatedButton(
            onPressed: () {
              setState(() {
                isChat = true;
              });
              initRocketChat();
            },
            style: ElevatedButton.styleFrom(
                padding: EdgeInsets.all(3.0.w),
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(12)),
                primary: Color(0xff333333)

                // color: Colors.black87,
                ),
            child: Center(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Icon(
                    Icons.add_circle_outline,
                    color: Colors.white,
                    size: 20.0.sp,
                  ),
                  SizedBox(
                    width: 3.0.w,
                  ),
                  Container(
                    height: 10.0.w,
                    child: Center(
                      child: Text(
                        S.of(context).start_chat,
                        style: AppStyle.textStyle().copyWith(
                            color: Colors.white,
                            fontWeight: FontWeight.w600,
                            fontSize: 16.0),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ],
    );
  }

  chatRowTitleText(String text, {double fontSize = 18}) {
    return AutoSizeText(
      text,
      textAlign: TextAlign.center,
      style: TextStyle(
          fontSize: fontSize, fontWeight: FontWeight.w600, color: Colors.red),
    );
  }

  chatRowDaysAndHours(String day, String time) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Flexible(
          child: AutoSizeText(
            day,
            textAlign: TextAlign.start,
            style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.w500,
                color: Colors.black.withOpacity(0.5)),
          ),
        ),
        AutoSizeText(
          time,
          textAlign: TextAlign.end,
          style: TextStyle(
              fontSize: 18, fontWeight: FontWeight.w600, color: Colors.black),
        ),
      ],
    );
  }
}

class OnlineBody extends StatefulWidget {
  final RocketChatState state;
  final ChatRepository repo;

  const OnlineBody({Key? key, required this.state, required this.repo})
      : super(key: key);

  @override
  _OnlineBodyState createState() => _OnlineBodyState();
}

class _OnlineBodyState extends State<OnlineBody>
    with SingleTickerProviderStateMixin {
  // FlutterLocalNotificationsPlugin? flutterLocalNotificationsPlugin;

  TextEditingController controller = TextEditingController();
  ScrollController scrollController = ScrollController();
  bool ignoreWidget = true;
  bool flagDueNotificationIssue = true;
  String language = 'ru';
  var repo = ChatRepository();

  void _scrollToTheEnd() {
    Future.delayed(const Duration(milliseconds: 200)).then((_) {
      scrollController.jumpTo(scrollController.position.maxScrollExtent);
    });
  }

  @override
  void dispose() {
    controller.dispose();
    scrollController.dispose();
    // _animationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: <Widget>[
        StreamBuilder<RocketChatState>(
          initialData: widget.repo.lastState,
          stream: widget.repo.state,
          builder: (context, snapshot) {
            final state = snapshot.data;

            if (state == null) {
              return const Center(
                child: CircularProgressIndicator(),
              );
            }
            return LayoutBuilder(
              builder: (context, constraints) => ConstrainedBox(
                constraints: BoxConstraints(
                    minWidth: constraints.maxWidth,
                    minHeight: constraints.maxHeight),
                child: IntrinsicHeight(
                  child: ListView.builder(
                    shrinkWrap: true,
                    padding: EdgeInsets.only(
                        left: 14.0, right: 14.0, top: 5.0, bottom: 15.0.h),
                    controller: scrollController,
                    itemCount: state.history?.length,
                    itemBuilder: (context, index) {
                      final LivechatMessage? message = state.history?[index];
                      if (state.history?.length == 0)
                        flagDueNotificationIssue = false;
                      if (message != null) {
                        if (message.t == 'command') {
                          if (message.msg == 'promptTranscript') {
                            // MainRouter.navigator.popUntil(
                            //     ModalRoute.withName(MainRouter.homePage));
                            widget.repo.unsubscribeFromRoomUpdates();
                            // Navigator.of(context).pop();
                          }
                          return MessageBubble(
                            repo: repo,
                            messageParameters: message,
                            message: message.msg == null || message.msg!.isEmpty
                                ? message.file
                                : message.msg,
                            fileType:
                                message.msg == null || message.msg!.isEmpty
                                    ? AttachmentType.image
                                    : AttachmentType.text,
                            color: Colors.grey.shade300,
                            textColor: Colors.grey.shade600,
                            fontSize: 9.0.sp,
                          );
                        } else if (message.t == 'ul') {
                          return MessageBubble(
                            repo: repo,
                            messageParameters: message,
                            message: "${message.msg} ${'left.chat'.toString()}",
                            fileType: AttachmentType.text,
                            color: Colors.grey.shade300,
                            textColor: Colors.grey.shade600,
                            fontSize: 9.0.sp,
                          );
                        } else if (message.t == 'uj') {
                          return MessageBubble(
                            repo: repo,
                            messageParameters: message,
                            message: "${message.msg} ${'joined.chat'}",
                            fileType: AttachmentType.text,
                            color: Colors.grey.shade300,
                            textColor: Colors.grey.shade600,
                            fontSize: 9.0.sp,
                          );
                        }

                        // if (message?.t == 'livechat_transfer_history') {
                        //   return MessageBubble(
                        //     messageParameters: message,
                        //     message: language == 'ru'
                        //         ? "Новый чат-трансфер: ${state.name} перенаправил чат в другой департамент"
                        //         : '${state.name} ${'chat.department.changed'.toString()}',
                        //     fileType: AttachmentType.text,
                        //     color: Colors.grey.shade300,
                        //     textColor: Colors.grey.shade600,
                        //     fontSize: 9.0.sp,
                        //   );
                        // }

                        else if (message.alias == null) {
                          return MessageBubble(
                            repo: repo,
                            side: MessageBubbleSide.left,
                            messageParameters: message,
                            message: message.msg == null || message.msg!.isEmpty
                                ? message.attachments![0].titleLink
                                : message.msg,
                            fileType:
                                message.msg == null || message.msg!.isEmpty
                                    ? AttachmentType.file
                                    : AttachmentType.text,
                            color: Color(0xffF7F7F9),
                            textColor: Colors.black,
                            fontSize: 12.0.sp,
                            // showNotification: _showNotification,
                          );
                        } else if (message.alias == widget.state.name) {
                          return MessageBubble(
                            repo: repo,
                            side: MessageBubbleSide.right,
                            messageParameters: message,
                            message: message.msg == null || message.msg!.isEmpty
                                ? message.attachments![0].titleLink
                                : message.msg,
                            fileType:
                                message.msg == null || message.msg!.isEmpty
                                    ? AttachmentType.file
                                    : AttachmentType.text,
                            color: Color(0xff8A2BE2),
                            textColor: Colors.white,
                            fontSize: 12.0.sp,
                            // showNotification: _showNotification,
                          );
                        } else {
                          return Text(message.msg ?? message.file?.name ?? '');
                        }
                      } else
                        return Text('');
                    },
                  ),
                ),
              ),
            );
          },
        ),

        Visibility(
          visible: uploadingNow,
          child: Positioned(
            right: 0.0,
            left: 0.0,
            bottom: 12.0.h,
            child: LinearProgressIndicator(
              backgroundColor: Colors.grey[350],
              valueColor: AlwaysStoppedAnimation<Color>(Color(0xff8A2BE2)),
              value: /* double.parse(*/ uploadedPercent /*.split('%').first)*/,
            ),
          ),
        ),

        // input
        Align(
          alignment: Alignment.bottomCenter,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              Divider(),
              ChatInput(
                  onTextfieldTap: _scrollToTheEnd,
                  sendTextMessage: _sendLiveTextMessage,
                  sendFileMessage: _sendFileMessage),
            ],
          ),
        ),
      ],
    );
  }

  void _sendLiveTextMessage(String text) {
    // widget.bloc.add(SendTextEvent(text));
    repo.sendTextMessage(text);

    _scrollToTheEnd();
  }

  void _sendFileMessage(File file) {
    repo.sendFileMessage(file, showUploadPercent);

    _scrollToTheEnd();
  }

  String? uploadingFileName;
  double? uploadedPercent;
  bool uploadingNow = false;

  void showUploadPercent(double percent, String filename, bool? isUploading) {
    setState(() {
      uploadingFileName = filename;
      uploadedPercent = percent;
      uploadingNow = true;
    });
  }

  // Future<void> _showNotification(Map<String, dynamic> downloadStatus) async {
  //   final android = AndroidNotificationDetails(
  //       'channel id', 'channel name', 'channel description',
  //       priority: Priority.high, importance: Importance.max);
  //   final iOS = IOSNotificationDetails();
  //   final platform = NotificationDetails(android: android, iOS: iOS);
  //   final json = jsonEncode(downloadStatus);
  //   final isSuccess = downloadStatus['isSuccess'];

  //   await MyApp.flutterLocalNotificationsPlugin.show(
  //       0, // notification id

  //       isSuccess ? 'download.finished'.toString() : 'error'.toString(),
  //       isSuccess
  //           ? 'file.downloaded'.toString()
  //           : 'downloading.error'.toString(),
  //       platform,
  //       payload: json);
  // }

  // Future<void> _onSelectNotification(String? json) async {
  //   if (Platform.isAndroid && flagDueNotificationIssue) {
  //     flagDueNotificationIssue = false;
  //     return;
  //   }

  //   if (json != null) {
  //     final obj = jsonDecode(json);
  //     if (obj['isSuccess']) {
  //       OpenFile.open(obj['filePath']);
  //     } else {
  //       showDialog(
  //         context: context,
  //         builder: (_) => AlertDialog(
  //           title: Text('error'.toString()),
  //           content: Text('error.while.downloading'.toString()),
  //         ),
  //       );
  //     }
  //   }
  // }
}
