import 'package:flutter/material.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:form_builder_validators/form_builder_validators.dart';

import 'package:get/get.dart';
import 'package:IQ/app/modules/home/models/support_model.dart'
    as support_model;
import 'package:IQ/app/modules/single_ticket/controllers/single_ticket_controller.dart';

import 'package:flutter_svg/flutter_svg.dart';
import 'package:IQ/app/global/static_informs.dart';
import 'package:IQ/app/global/text_widget.dart';
import 'package:IQ/app/modules/drawerSide/views/drawer_side_view.dart';
import 'package:IQ/app/modules/home/providers/user.dart';

class SingleTicketView extends GetView<SingleTicketController> {
  SingleTicketView({Key? key}) : super(key: key);
  final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey();

  @override
  Widget build(BuildContext context) {
    var stackedContainer = Container(
      height: 250,
      decoration: BoxDecoration(
        color: brandColor,
        image: const DecorationImage(
          image: AssetImage('assets/background.png'),
          fit: BoxFit.fill,
        ),
      ),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          SizedBox(height: MediaQuery.of(context).viewPadding.top),
          Container(
            margin: const EdgeInsets.symmetric(
              horizontal: 15,
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Container(
                  margin: const EdgeInsets.only(
                    top: 5,
                    right: 15,
                  ),
                  child: Row(
                    children: [
                      SvgPicture.asset(
                        "assets/2/icon.svg",
                        height: 20,
                        width: 71.16,
                      ),
                      const SizedBox(width: 10),
                      Image.asset("assets/logo.png"),
                    ],
                  ),
                ),
                const SizedBox(width: 10),
                Row(
                  children: [
                    Text(
                      user?.data?.firstname ?? ' . . . ',
                      style: const TextStyle(
                        fontSize: 20,
                        color: Colors.white,
                        fontWeight: FontWeight.normal,
                      ),
                    ),
                    IconButton(
                      onPressed: () {
                        scaffoldKey.currentState?.openEndDrawer();
                      },
                      icon: const Icon(
                        Icons.menu,
                        color: Colors.white,
                        size: 40,
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
          Container(
            margin: const EdgeInsets.only(top: 10),
            child: Align(
              alignment: Alignment.bottomCenter,
              child: Column(
                children: [
                  SvgPicture.asset(
                    'assets/support_icon.svg',
                    color: Colors.white,
                    height: 90,
                    width: 90,
                  ),
                  const SizedBox(height: 15),
                  TextWidget(
                    text: 'support'.tr,
                    color: Colors.white,
                    fontSize: 24,
                    fontWeight: FontWeight.w300,
                    textAlign: TextAlign.center,
                  ),
                  const SizedBox(height: 10),
                ],
              ),
            ),
          )
        ],
      ),
    );
    return Directionality(
      textDirection:
          defaultLocale == "en" ? TextDirection.rtl : TextDirection.ltr,
      child: Scaffold(
        backgroundColor: backgroundColor,
        drawerScrimColor: Colors.black.withOpacity(0.7),
        key: scaffoldKey,
        endDrawer: const DrawerSideView(),
        drawerEdgeDragWidth: widthSize(context),
        body: GetBuilder(
          init: SingleTicketController(),
          builder: (SingleTicketController singleTicketController) {
            return RefreshIndicator(
              onRefresh: controller.onRefresh,
              triggerMode: RefreshIndicatorTriggerMode.anywhere,
              backgroundColor: Colors.white,
              color: brandColor,
              child: singleTicketController.fetchTicketsMessagesData
                  ? Stack(
                      children: [
                        Align(
                          alignment: Alignment.bottomCenter,
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.end,
                            children: [
                              Container(
                                height: 100,
                                margin: const EdgeInsets.only(
                                  right: 20.0,
                                  left: 20.0,
                                  top: 25,
                                ),
                                child: FormBuilder(
                                  key: controller.formKey,
                                  child: FormBuilderTextField(
                                    textDirection: textDirection,
                                    autovalidateMode:
                                        AutovalidateMode.onUserInteraction,
                                    textAlign: defaultLocale == "en"
                                        ? TextAlign.left
                                        : TextAlign.right,
                                    textAlignVertical: TextAlignVertical.top,
                                    onChanged: controller.onChangeTicketReply,
                                    name: 'ticket_message',
                                    onEditingComplete: () {
                                      FocusScope.of(context).unfocus();
                                    },
                                    validator: FormBuilderValidators.compose(
                                      [
                                        FormBuilderValidators.required(
                                          errorText: 'message_input_error'.tr,
                                        ),
                                      ],
                                    ),
                                    expands: true,
                                    minLines: null,
                                    maxLines: null,
                                    style: buildTextStyle(
                                      fontSize: 20,
                                      color: Colors.black,
                                    ),
                                    keyboardType: TextInputType.multiline,
                                    textInputAction: TextInputAction.newline,
                                    decoration: InputDecoration(
                                      hintTextDirection: defaultLocale == "en"
                                          ? TextDirection.ltr
                                          : TextDirection.rtl,
                                      fillColor: Colors.white,
                                      hintText: 'message'.tr,
                                      border: OutlineInputBorder(
                                        borderRadius: BorderRadius.circular(15),
                                        borderSide: const BorderSide(
                                          color: Colors.black,
                                        ),
                                      ),
                                      filled: true,
                                      hintStyle: buildTextStyle(
                                        color: const Color.fromARGB(
                                            255, 184, 184, 184),
                                        fontSize: 19,
                                      ),
                                      errorMaxLines: 2,
                                      isDense: true,
                                      errorStyle: buildTextStyle(
                                        fontSize: 12,
                                        color: const Color.fromARGB(
                                            255, 184, 184, 184),
                                      ),
                                    ),
                                  ),
                                ),
                              ),
                              const SizedBox(height: 12),
                              Container(
                                width: widthSize(context),
                                height: 60,
                                margin: const EdgeInsets.symmetric(
                                    horizontal: 20, vertical: 20),
                                child: TextButton(
                                  onPressed: () {
                                    FocusScope.of(context).unfocus();
                                    singleTicketController.sendTicketReply();
                                  },
                                  style: ButtonStyle(
                                    shape: MaterialStateProperty.all(
                                      const RoundedRectangleBorder(
                                        borderRadius: BorderRadius.all(
                                          Radius.circular(15),
                                        ),
                                      ),
                                    ),
                                    backgroundColor: MaterialStateProperty.all(
                                      brandColor,
                                    ),
                                  ),
                                  child: !singleTicketController.inputsEntered
                                      ? TextWidget(
                                          text: "send".tr,
                                          fontSize: 18,
                                          fontWeight: FontWeight.normal,
                                          color: Colors.white,
                                        )
                                      : const CircularProgressIndicator(
                                          color: Colors.white,
                                        ),
                                ),
                              ),
                            ],
                          ),
                        ),
                        Container(
                          margin: const EdgeInsets.only(top: 250),
                          padding: const EdgeInsets.only(
                            left: 20,
                            right: 20,
                            top: 18,
                          ),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              _getTicketStatus(singleTicketController.ticket),
                              TextWidget(
                                text: singleTicketController.ticket.subject,
                                fontSize: 22,
                                fontWeight: FontWeight.w500,
                                textAlign: TextAlign.right,
                              ),
                            ],
                          ),
                        ),
                        Container(
                          margin: const EdgeInsets.only(
                            top: 320,
                            bottom: 215,
                          ),
                          child: SingleChildScrollView(
                            physics: const AlwaysScrollableScrollPhysics(),
                            controller: singleTicketController.scrollController,
                            child: Column(
                              children: singleTicketController.messages?.map(
                                (message) {
                                  if (message.managerDetails == null) {
                                    return Container(
                                      margin: const EdgeInsets.symmetric(
                                        horizontal: 18,
                                      ),
                                      child: Column(
                                        crossAxisAlignment:
                                            CrossAxisAlignment.end,
                                        children: [
                                          TextWidget(
                                            text:
                                                "${message.userDetails?.username}",
                                            fontSize: 20,
                                            textAlign: TextAlign.right,
                                            fontWeight: FontWeight.w500,
                                            color: brandColor,
                                          ),
                                          const SizedBox(height: 2),
                                          Container(
                                            width: widthSize(context) * 0.8,
                                            padding: const EdgeInsets.symmetric(
                                              horizontal: 16,
                                              vertical: 10,
                                            ),
                                            color: const Color(0xffCCEAC7),
                                            child: TextWidget(
                                              text: "${message.message}",
                                              fontSize: 18,
                                              fontWeight: FontWeight.w500,
                                              softWrap: true,
                                              textAlign: TextAlign.end,
                                              color: Colors.black,
                                            ),
                                          ),
                                          const SizedBox(height: 3),
                                          Container(
                                            margin: const EdgeInsets.symmetric(
                                              horizontal: 60,
                                            ),
                                            alignment: defaultLocale == "en"
                                                ? Alignment.centerRight
                                                : Alignment.centerLeft,
                                            child: TextWidget(
                                              text: defaultLocale != "en"
                                                  ? "${message.createdAt?.split(" ")[0]} ${message.createdAt?.split(" ")[1]}"
                                                  : "${message.createdAt?.split(" ")[1]} ${message.createdAt?.split(" ")[0]}",
                                              fontSize: 18,
                                              fontWeight: FontWeight.w500,
                                              color: Colors.black,
                                            ),
                                          ),
                                          const SizedBox(height: 22),
                                        ],
                                      ),
                                    );
                                  } else {
                                    return Container(
                                      margin: const EdgeInsets.symmetric(
                                        horizontal: 18,
                                      ),
                                      child: Column(
                                        crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                        children: [
                                          TextWidget(
                                            text:
                                                "${message.managerDetails?.username}",
                                            fontSize: 20,
                                            textAlign: TextAlign.right,
                                            fontWeight: FontWeight.w500,
                                            color: brandColor,
                                          ),
                                          const SizedBox(height: 2),
                                          Container(
                                            width: widthSize(context) * 0.8,
                                            padding: const EdgeInsets.symmetric(
                                              horizontal: 16,
                                              vertical: 10,
                                            ),
                                            color: const Color(0xffC7DBEA),
                                            child: TextWidget(
                                              text: "${message.message}",
                                              fontSize: 18,
                                              fontWeight: FontWeight.w500,
                                              softWrap: true,
                                              textAlign: TextAlign.end,
                                              color: Colors.black,
                                            ),
                                          ),
                                          const SizedBox(height: 3),
                                          Container(
                                            margin: const EdgeInsets.symmetric(
                                              horizontal: 60,
                                            ),
                                            alignment: defaultLocale == "en"
                                                ? Alignment.centerLeft
                                                : Alignment.centerRight,
                                            child: TextWidget(
                                              text: defaultLocale != "en"
                                                  ? "${message.createdAt?.split(" ")[0]} ${message.createdAt?.split(" ")[1]}"
                                                  : "${message.createdAt?.split(" ")[1]} ${message.createdAt?.split(" ")[0]}",
                                              fontSize: 18,
                                              fontWeight: FontWeight.w400,
                                              color: Colors.black,
                                            ),
                                          ),
                                          const SizedBox(height: 22),
                                        ],
                                      ),
                                    );
                                  }
                                },
                              ).toList() as List<Widget>,
                            ),
                          ),
                        ),
                        stackedContainer,
                      ],
                    )
                  : Stack(
                      children: [
                        Center(
                          child: CircularProgressIndicator(
                            color: brandColor,
                          ),
                        ),
                        stackedContainer,
                      ],
                    ),
            );
          },
        ),
      ),
    );
  }

  Widget _getTicketStatus(support_model.Data e) {
    String? statusString;
    Color? statusColor;
    if (e.closed == 0) {
      statusString = "ticket_status_waiting".tr;
      statusColor = const Color(0xffEB7923);
    } else {
      if (e.solved == 1) {
        statusString = "ticket_status_solved".tr;
        statusColor = brandColor;
      }
      if (e.solved == 0) {
        statusString = "ticket_status_closed".tr;
        statusColor = Colors.green;
      }
    }
    return TextWidget(
      text: statusString!,
      fontSize: 20,
      fontWeight: FontWeight.w700,
      color: statusColor,
    );
  }
}
