import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/svg.dart';
import 'package:gap/gap.dart';
import 'package:get/get.dart' hide FormData;
import 'package:traderscircuit/Utils/dialogs.dart';
import 'package:traderscircuit/Utils/image_preview_screen.dart';
import 'package:traderscircuit/controller/contact_us_controller.dart';
import 'package:traderscircuit/model/ContactUsModel/ticket_details_model.dart';
import 'package:traderscircuit/view_model/ContactUsApi/contact_us_api.dart';

import '../../../Utils/Common/CommonAppbar.dart';
import '../../../Utils/Common/CustomTextFormField.dart';
import '../../../Utils/Common/commonBotton.dart';
import '../../../Utils/text.dart';
import '../../onBoarding/splashScreen1.dart';
import 'cancel_ticket_bottom_sheet.dart';

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

  @override
  State<ContactUsDetailsScreen> createState() => _ContactUsDetailsScreenState();
}

class _ContactUsDetailsScreenState extends State<ContactUsDetailsScreen> {
  ContactUsController contactUsController = Get.put(ContactUsController());
  TextEditingController queriesTextController = TextEditingController();
  String id = Get.arguments["id"];
  RxBool isLoading = true.obs;
  TicketDetailsModel? ticketDetailsModel;
  @override
  void initState() {
    contactUsController.contactUsDetailsChatContent.clear();
    ContactUsApi().getContactUsDetailsData(id).then((value) {
      ticketDetailsModel = TicketDetailsModel.fromJson(value.data);
      for (var a in ticketDetailsModel!.data![0].ticketResponses!) {
        contactUsController.contactUsDetailsChatContent.add({
          "initial_name": "TS",
          "date": contactUsController.formatedDateTimeMethod(a.createdAt!),
          "content": a.response,
        });
      }
      isLoading.value = false;
    });

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    final GlobalKey<FormState> queriesForm = GlobalKey<FormState>();
    return Obx(
      () => Form(
        key: queriesForm,
        child: Scaffold(
          appBar: CommonAppbar(
            height: 75,
            titleTxt: "",
            customActionWidget: text16W400(""),
          ),
          backgroundColor: Colors.black,
          extendBody: true,
          body: Stack(
            children: [
              const CommonBlurLeft(),
              const CommonBlurRight(),
              isLoading.value
                  ? const Center(
                      child:
                          CircularProgressIndicator(color: Color(0xFF9A0000)),
                    )
                  : Stack(children: [
                      SingleChildScrollView(
                        child: Padding(
                          padding: const EdgeInsets.symmetric(
                              horizontal: 18, vertical: 16),
                          child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              //physics: const NeverScrollableScrollPhysics(),
                              children: [
                                text25W600("Contact Us"),
                                const Gap(20),
                                Row(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceBetween,
                                  children: [
                                    Column(
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      children: [
                                        text22W600(
                                            "#${ticketDetailsModel!.data![0].uniqueTicketId}"),
                                        const Gap(10),
                                        text16W500(
                                          ticketDetailsModel!.data![0].status ==
                                                  1
                                              ? "OPEN"
                                              : ticketDetailsModel!
                                                          .data![0].status ==
                                                      2
                                                  ? "CLOSED"
                                                  : "RESOLVED",
                                          clr: ticketDetailsModel!
                                                      .data![0].status ==
                                                  1
                                              ? const Color(0xFFFFAD31)
                                              : ticketDetailsModel!
                                                          .data![0].status ==
                                                      2
                                                  ? const Color(0xFF95CCFF)
                                                  : const Color(0xFF34C759),
                                        ),
                                      ],
                                    ),
                                    text16W400(contactUsController
                                        .formatedDateTimeMethod(
                                            ticketDetailsModel!
                                                .data![0].createdAt!)),
                                  ],
                                ),
                                const Gap(15),
                                const Divider(
                                  thickness: 1,
                                  color: Color(0xFF242424),
                                ),
                                const Gap(20),
                                text16W600(ticketDetailsModel!
                                    .data![0].ticketCategory!.name!),
                                const Gap(10),
                                text16W400(
                                    ticketDetailsModel!.data![0].description!),
                                ListView.builder(
                                    shrinkWrap: true,
                                    itemCount: ticketDetailsModel!
                                        .data![0].ticketFiles!.length,
                                    itemBuilder: (ctx, index) {
                                      return InkWell(
                                        onTap: () {
                                          Get.to(const ImagePreviewScreen(),
                                              arguments: {
                                                "image": ticketDetailsModel!
                                                    .data![0]
                                                    .ticketFiles![index]
                                                    .file,
                                              });
                                        },
                                        child: Container(
                                          width: 1.sw,
                                          height: 42.h,
                                          margin: const EdgeInsets.symmetric(
                                            vertical: 6,
                                          ),
                                          decoration: BoxDecoration(
                                              color: const Color(0xFF0C0C0C),
                                              borderRadius:
                                                  BorderRadius.circular(4),
                                              border: Border.all(
                                                  width: 1,
                                                  color:
                                                      const Color(0xFF3A3A3A))),
                                          child: Row(
                                            mainAxisAlignment:
                                                MainAxisAlignment.spaceBetween,
                                            children: [
                                              Row(
                                                children: [
                                                  const Gap(6),
                                                  SvgPicture.asset(
                                                      "assets/images/svg/attachment_pin.svg"),
                                                  const Gap(6),
                                                  text12W400(
                                                      "Attachment ${index + 1}"),
                                                ],
                                              ),
                                            ],
                                          ),
                                        ),
                                      );
                                    }),
                                contactUsController
                                        .attachmentPathNameDetailsList.isEmpty
                                    ? const SizedBox()
                                    : const Gap(15),
                                contactUsController
                                        .attachmentPathNameDetailsList.isEmpty
                                    ? const SizedBox()
                                    : ListView.builder(
                                        physics:
                                            const NeverScrollableScrollPhysics(),
                                        shrinkWrap: true,
                                        itemCount: contactUsController
                                            .attachmentPathNameDetailsList
                                            .length,
                                        itemBuilder: (ctx, index) {
                                          return Container(
                                            width: 1.sw,
                                            height: 42.h,
                                            margin: const EdgeInsets.symmetric(
                                              vertical: 6,
                                            ),
                                            decoration: BoxDecoration(
                                                color: const Color(0xFF0C0C0C),
                                                borderRadius:
                                                    BorderRadius.circular(4),
                                                border: Border.all(
                                                    width: 1,
                                                    color: const Color(
                                                        0xFF3A3A3A))),
                                            child: Row(
                                              mainAxisAlignment:
                                                  MainAxisAlignment
                                                      .spaceBetween,
                                              children: [
                                                Row(
                                                  children: [
                                                    const Gap(6),
                                                    SvgPicture.asset(
                                                        "assets/images/svg/attachment_pin.svg"),
                                                    const Gap(6),
                                                    Container(
                                                      width: 0.7.sw,
                                                      child: FittedBox(
                                                        child: text12W400(
                                                            contactUsController
                                                                    .attachmentPathNameDetailsList[
                                                                index]),
                                                      ),
                                                    ),
                                                  ],
                                                ),
                                                GestureDetector(
                                                    onTap: () {
                                                      contactUsController
                                                          .attachmentPathNameDetailsList
                                                          .removeAt(index);
                                                      contactUsController
                                                          .attachmentFileDetailsList
                                                          .removeAt(index);
                                                    },
                                                    child: Container(
                                                      margin:
                                                          const EdgeInsets.only(
                                                              right: 20),
                                                      child: SvgPicture.asset(
                                                        "assets/images/svg/cross_cancel.svg",
                                                        color: const Color(
                                                            0xFF818181),
                                                        width: 10,
                                                        height: 10,
                                                      ),
                                                    )),
                                              ],
                                            ),
                                          );
                                        }),
                                contactUsController
                                        .contactUsDetailsChatContent.isEmpty
                                    ? const SizedBox()
                                    : const Gap(18),
                                ListView.builder(
                                    physics:
                                        const NeverScrollableScrollPhysics(),
                                    shrinkWrap: true,
                                    itemCount: contactUsController
                                            .contactUsDetailsChatContent
                                            .length +
                                        1,
                                    itemBuilder: (ctx, index) {
                                      return index ==
                                              contactUsController
                                                  .contactUsDetailsChatContent
                                                  .length
                                          ? Container(
                                              margin: EdgeInsets.only(top: 20),
                                              child: Column(
                                                crossAxisAlignment:
                                                    CrossAxisAlignment.end,
                                                mainAxisSize: MainAxisSize.min,
                                                children: [
                                                  Stack(
                                                    children: [
                                                      CustomTextFormField3(
                                                        texttype: TextInputType
                                                            .multiline,
                                                        hintText:
                                                            "Enter some text...",
                                                        textEditingController:
                                                            queriesTextController,
                                                        maxlines: 8,
                                                        validator: (value) {
                                                          if (value.isEmpty) {
                                                            return 'Enter your Content';
                                                          } else if (value
                                                                  .toString()
                                                                  .length <
                                                              30) {
                                                            return 'Content should be minimum 30 characters';
                                                          }
                                                          return null;
                                                        },
                                                        inputFormatters: [
                                                          LengthLimitingTextInputFormatter(
                                                              200),
                                                        ],
                                                      ),
                                                      Positioned(
                                                        bottom: 15,
                                                        left: 37,
                                                        right: 37,
                                                        child: SizedBox(
                                                          width: 200.w,
                                                          child: kycBtn(
                                                            text:
                                                                "Close Ticket",
                                                            onTap: () {
                                                              CancelTicketBottomSheet()
                                                                  .bottomSheet(
                                                                      context);
                                                            },
                                                            bgClr: const Color(
                                                                0xFF111313),
                                                            borderClr:
                                                                const Color(
                                                                    0xFF990000),
                                                          ),
                                                        ),
                                                      )
                                                    ],
                                                  ),
                                                  // contactUsController
                                                  //             .attachmentPathNameDetailsList
                                                  //             .length >=
                                                  //         3
                                                  //     ? const SizedBox()
                                                  //     : const Gap(10),
                                                  // contactUsController
                                                  //             .attachmentPathNameDetailsList
                                                  //             .length >=
                                                  //         3
                                                  //     ? const SizedBox()
                                                  //     : InkWell(
                                                  //         onTap: () async {
                                                  //           var result =
                                                  //               await FilePickerMethod()
                                                  //                   .pickFile();
                                                  //           if (result !=
                                                  //               null) {
                                                  //             contactUsController
                                                  //                 .attachmentPathNameDetailsList
                                                  //                 .clear();

                                                  //             for (var a
                                                  //                 in result) {
                                                  //               contactUsController
                                                  //                   .attachmentFileDetailsList
                                                  //                   .add(a);
                                                  //             }

                                                  //             for (var a
                                                  //                 in contactUsController
                                                  //                     .attachmentFileDetailsList) {
                                                  //               contactUsController
                                                  //                   .attachmentPathNameDetailsList
                                                  //                   .add(FilePickerMethod().extractFileName(
                                                  //                       a?.path ??
                                                  //                           ''));
                                                  //             }
                                                  //           }
                                                  //         },
                                                  //         child: Row(
                                                  //           mainAxisAlignment:
                                                  //               MainAxisAlignment
                                                  //                   .end,
                                                  //           children: [
                                                  //             SvgPicture.asset(
                                                  //                 "assets/images/svg/attachment_pin.svg"),
                                                  //             const Gap(6),
                                                  //             text12W400(
                                                  //                 "Add Attachment (Max 32MB / Optional)"),
                                                  //           ],
                                                  //         ),
                                                  //       ),
                                                  const Gap(20),
                                                  Padding(
                                                    padding: const EdgeInsets
                                                        .symmetric(
                                                        //  horizontal: 10,
                                                        vertical: 20),
                                                    child: SizedBox(
                                                      width: Get.width,
                                                      child: kycBtn(
                                                        text: "Submit",
                                                        onTap: () {
                                                          if (queriesTextController
                                                              .text.isEmpty) {
                                                            utils.showToast(
                                                                "Text is required");
                                                          } else {
                                                            ContactUsApi()
                                                                .addTicketMessageApi(
                                                                    FormData
                                                                        .fromMap({
                                                              "description":
                                                                  queriesTextController
                                                                      .text,
                                                              "ticket_xid":
                                                                  ticketDetailsModel!
                                                                      .data![0]
                                                                      .id
                                                            }))
                                                                .then((value) {
                                                              Map<String,
                                                                      dynamic>
                                                                  responseData =
                                                                  Map<String,
                                                                          dynamic>.from(
                                                                      value
                                                                          .data);
                                                              utils.showToast(
                                                                  responseData[
                                                                      "message"]);
                                                              contactUsController
                                                                  .contactUsDetailsChatContent
                                                                  .add({
                                                                "initial_name":
                                                                    "TS",
                                                                "date": contactUsController
                                                                    .formatedDateTimeMethod(
                                                                        responseData["data"]
                                                                            [
                                                                            "created_at"]),
                                                                "content": responseData[
                                                                        "data"][
                                                                    "response"],
                                                              });
                                                              queriesTextController
                                                                  .clear();
                                                            });
                                                          }
                                                        },
                                                        bgClr: const Color(
                                                            0xFF6C0000),
                                                        borderClr: const Color(
                                                            0xFF990000),
                                                      ),
                                                    ),
                                                  ),
                                                ],
                                              ),
                                            )
                                          : Container(
                                              width: 1.sw,
                                              margin:
                                                  const EdgeInsets.symmetric(
                                                vertical: 5,
                                              ),
                                              decoration: BoxDecoration(
                                                  color:
                                                      const Color(0xFF0C0C0C),
                                                  borderRadius:
                                                      BorderRadius.circular(8),
                                                  gradient: LinearGradient(
                                                    begin: const Alignment(
                                                        0.98, -0.21),
                                                    end: const Alignment(
                                                        -0.98, 0.21),
                                                    colors: [
                                                      Colors.white.withOpacity(
                                                          0.03999999910593033),
                                                      Colors.white.withOpacity(
                                                          0.05999999865889549)
                                                    ],
                                                  ),
                                                  border: Border.all(
                                                      width: 1,
                                                      color: const Color(
                                                          0xFF3A3A3A))),
                                              child: Padding(
                                                padding:
                                                    const EdgeInsets.all(12.0),
                                                child: Column(
                                                  crossAxisAlignment:
                                                      CrossAxisAlignment.start,
                                                  mainAxisSize:
                                                      MainAxisSize.min,
                                                  children: [
                                                    Row(
                                                      mainAxisAlignment:
                                                          MainAxisAlignment
                                                              .spaceBetween,
                                                      children: [
                                                        CircleAvatar(
                                                          radius: 18,
                                                          backgroundColor:
                                                              Colors.white,
                                                          child: Center(
                                                            child: text16W600(
                                                                contactUsController
                                                                            .contactUsDetailsChatContent[
                                                                        index][
                                                                    "initial_name"],
                                                                clr: const Color(
                                                                    0xFF535353)),
                                                          ),
                                                        ),
                                                        text14W500(
                                                          contactUsController
                                                                  .contactUsDetailsChatContent[
                                                              index]["date"],
                                                        ),
                                                      ],
                                                    ),
                                                    const Gap(18),
                                                    text16W400(
                                                      contactUsController
                                                              .contactUsDetailsChatContent[
                                                          index]["content"],
                                                    )
                                                  ],
                                                ),
                                              ));
                                    }),
                              ]),
                        ),
                      )
                    ]),
            ],
          ),
        ),
      ),
    );
  }
}
