import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/svg.dart';
import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:traderscircuit/Utils/Common/CommonAppBar.dart';
import 'package:traderscircuit/Utils/Common/CustomTextFormField.dart';
import 'package:traderscircuit/Utils/Common/comonGlassmorphicContainer.dart';
import 'package:traderscircuit/Utils/Common/sized_box.dart';
import 'package:traderscircuit/Utils/text.dart';
import 'package:traderscircuit/model/FAQModel/faq_model.dart';
import 'package:traderscircuit/view/onBoarding/splashScreen1.dart';
import 'package:traderscircuit/view_model/FaqApi/faq_api.dart';

Rx<FAQModel> faqModel = FAQModel().obs;

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

  @override
  State<FaqScreen> createState() => _FaqScreenState();
}

class _FaqScreenState extends State<FaqScreen> {
  List<String> categoryList = [];

  RxBool isLoading = true.obs;

  @override
  void initState() {
    getData();
    FAQApi().getFAQData().then((value) {
      faqModel.value = FAQModel.fromJson(value.data);
      for (var a in faqModel.value.data!) {
        categoryList.add(a.categoryName!);
      }
      isExpandedList = RxList.generate(
          faqModel.value.data![selectedIndex.value].faqQueAns!.length,
          (index) => index == 0);
      isLoading.value = false;
    });
    super.initState();
  }

  String? token;
  getData() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    token = prefs.getString('accessToken');
  }

  final selectedIndex = 0.obs;
  late RxList<bool> isExpandedList;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: const CommonAppbar(
          titleTxt: "",
        ),
        backgroundColor: Colors.black,
        extendBody: true,
        body: Obx(
          () => Stack(children: [
            const CommonBlurLeft(),
            const CommonBlurRight(),
            isLoading.value
                ? const Center(
                    child: CircularProgressIndicator(
                      color: Color(0xFF9A0000),
                    ),
                  )
                : Stack(children: [
                    Padding(
                        padding: const EdgeInsets.symmetric(horizontal: 16),
                        child: ListView(
                            physics: const BouncingScrollPhysics(),
                            children: [
                              text25W600('FAQ'),
                              sizedBoxHeight(20),
                              CustomTextFormField1(
                                hintText: 'Search Chats',
                                leadingIcon: SizedBox(
                                  height: 20,
                                  width: 20,
                                  child: Center(
                                    child: SvgPicture.asset(
                                      'assets/images/svg/search-svgrepo-com.svg',
                                    ),
                                  ),
                                ),
                              ),
                              sizedBoxHeight(20.h),
                              SizedBox(
                                height: 60,
                                width: double.infinity,
                                // color: Colors.amber,
                                child: ListView.builder(
                                    shrinkWrap: true,
                                    scrollDirection: Axis.horizontal,
                                    itemCount: categoryList.length,
                                    itemBuilder: (context, index) {
                                      return GestureDetector(
                                        onTap: () {
                                          selectedIndex.value = index;
                                          isExpandedList = RxList.generate(
                                              faqModel
                                                  .value
                                                  .data![selectedIndex.value]
                                                  .faqQueAns!
                                                  .length,
                                              (index) => index == 0);
                                        },
                                        child: Row(
                                          children: [
                                            topContainer(
                                                categoryList[index], index),
                                            sizedBoxWidth(10.w)
                                          ],
                                        ),
                                      );
                                    }),
                              ),
                              sizedBoxHeight(20.h),
                              Obx(() {
                                return Column(
                                    children: List.generate(
                                        faqModel
                                            .value
                                            .data![selectedIndex.value]
                                            .faqQueAns!
                                            .length, (index) {
                                  return customExpandableItem(
                                    index: index,
                                    selectedIndex: selectedIndex.value,
                                    faqModel1: faqModel.value,
                                    isExpanded: isExpandedList[index],
                                    title: faqModel
                                        .value
                                        .data![selectedIndex.value]
                                        .faqQueAns![index]
                                        .faqQuestion!,
                                    content: faqModel
                                        .value
                                        .data![selectedIndex.value]
                                        .faqQueAns![index]
                                        .faqAnswer!,
                                    toggleExpansion: () =>
                                        toggleExpansion(index),
                                    faqId: faqModel
                                        .value
                                        .data![selectedIndex.value]
                                        .faqQueAns![index]
                                        .id!,
                                  );
                                }));
                              }),
                              sizedBoxHeight(30.h),
                            ]))
                  ])
          ]),
        ));
  }

  Widget topContainer(String text, int index) {
    return Obx(() {
      return selectedIndex.value == index
          ? Container(
              height: 38.h,
              width: 136.w,
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(5),
                  color: const Color(0XFF3F0502),
                  border: Border.all(color: const Color(0xFF9A0000), width: 1)),
              child: Center(
                  child: Padding(
                padding: const EdgeInsets.symmetric(vertical: 8),
                child: FittedBox(child: text16W500(text)),
              )),
            )
          : commonGlassContainer(
              width: 136.w,
              height: 38.h,
              borderradius: 5,
              customWidget: Center(
                  child: Padding(
                padding: const EdgeInsets.symmetric(vertical: 9),
                child: FittedBox(child: text16W400(text)),
              )),
            );
    });
  }

  void toggleExpansion(int index) {
    // isExpandedList[index] = !isExpandedList[index];
    for (int i = 0; i < isExpandedList.length; i++) {
      if (i != index) {
        isExpandedList[i] = false;
      }
    }
    // Toggle the expansion state of the container being toggled
    isExpandedList[index] = !isExpandedList[index];
  }

  Widget customExpandableItem({
    required bool isExpanded,
    required String title,
    required String content,
    required VoidCallback toggleExpansion,
    required int faqId,
    required FAQModel faqModel1,
    required int selectedIndex,
    required int index,
  }) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        GestureDetector(
          onTap: toggleExpansion,
          child: commonGlassContainer(
            width: double.infinity,
            height: isExpanded ? 55.h : 65.h,
            borderradius: 8,
            customWidget: Padding(
              padding: EdgeInsets.only(right: 13.w, left: 13.w),
              child: Center(
                child: Row(
                  children: [
                    Text(
                      title,
                      style: TextStyle(
                        fontFamily: 'hiragino',
                        fontSize: 16.sp,
                        fontWeight: FontWeight.w500,
                        color: Colors.white,
                      ),
                    ),
                    const Spacer(),
                    Icon(
                      isExpanded
                          ? Icons.keyboard_arrow_up_outlined
                          : Icons.keyboard_arrow_down_outlined,
                      color: Colors.white,
                      size: 25.sp,
                    ),
                  ],
                ),
              ),
            ),
          ),
        ),
        Visibility(
          visible: isExpanded,
          child: Column(
            children: [
              Container(
                height: 198.h,
                width: double.infinity,
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.only(
                      bottomLeft: Radius.circular(8.r),
                      bottomRight: Radius.circular(8.r),
                    ),
                    color: Colors.black,
                    border:
                        Border.all(color: const Color(0xFF3A3A3A), width: 0.5)),
                child: Padding(
                  padding: EdgeInsets.only(
                      top: 11.h, left: 14.w, bottom: 25.h, right: 28.w),
                  child: Text(
                    content,
                    style: TextStyle(
                      color: const Color(0xFFFFFFFF),
                      fontFamily: 'hiragino',
                      fontSize: 14.sp,
                      fontWeight: FontWeight.w400,
                    ),
                  ),
                ),
              ),
              token == null || token!.isEmpty
                  ? const SizedBox()
                  : sizedBoxHeight(12.h),
              token == null || token!.isEmpty
                  ? const SizedBox()
                  : commonGlassContainer(
                      width: double.infinity,
                      height: 65.h,
                      borderradius: 8,
                      customWidget: Padding(
                          padding: EdgeInsets.only(right: 8.w, left: 13.w),
                          child: Center(
                            child: Row(children: [
                              Text(
                                'Was this answer helpful?',
                                style: TextStyle(
                                  fontFamily: 'hiragino',
                                  fontSize: 16.sp,
                                  fontWeight: FontWeight.w500,
                                  color: Colors.white,
                                ),
                              ),
                              const Spacer(),
                              Row(
                                crossAxisAlignment: CrossAxisAlignment.center,
                                children: [
                                  InkWell(
                                    onTap: () {
                                      FAQApi()
                                          .updaeFAQLikeDisklikeData(faqId, 1)
                                          .then((value) {
                                        FAQApi().getFAQData().then((value) {
                                          faqModel.value =
                                              FAQModel.fromJson(value.data);

                                          setState(() {});
                                        });
                                      });
                                    },
                                    child: Row(
                                      children: [
                                        text16W500('Yes'),
                                        sizedBoxWidth(2.w),
                                        (faqModel
                                                    .value
                                                    .data![selectedIndex]
                                                    .faqQueAns![index]
                                                    .userLikes!
                                                    .isNotEmpty &&
                                                faqModel
                                                        .value
                                                        .data![selectedIndex]
                                                        .faqQueAns![index]
                                                        .userLikes![0]
                                                        .status! ==
                                                    1)
                                            ? SvgPicture.asset(
                                                'assets/images/svg/filled_thumb_up.svg')
                                            : SvgPicture.asset(
                                                'assets/images/svg/thumbs-up.svg'),
                                      ],
                                    ),
                                  ),
                                  sizedBoxWidth(8.w),
                                  InkWell(
                                    onTap: () {
                                      FAQApi()
                                          .updaeFAQLikeDisklikeData(faqId, 0)
                                          .then((value) {
                                        FAQApi().getFAQData().then((value) {
                                          faqModel.value =
                                              FAQModel.fromJson(value.data);
                                        });
                                      });
                                    },
                                    child: Row(
                                      children: [
                                        text16W500('No'),
                                        sizedBoxWidth(2.w),
                                        Column(
                                          mainAxisAlignment:
                                              MainAxisAlignment.center,
                                          children: [
                                            sizedBoxHeight(5.h),
                                            (faqModel
                                                        .value
                                                        .data![selectedIndex]
                                                        .faqQueAns![index]
                                                        .userLikes!
                                                        .isNotEmpty &&
                                                    faqModel
                                                            .value
                                                            .data![
                                                                selectedIndex]
                                                            .faqQueAns![index]
                                                            .userLikes![0]
                                                            .status! ==
                                                        0)
                                                ? SvgPicture.asset(
                                                    'assets/images/svg/filled_thumb_down.svg')
                                                : SvgPicture.asset(
                                                    'assets/images/svg/thumbs-down.svg'),
                                          ],
                                        )
                                      ],
                                    ),
                                  )
                                ],
                              ),
                            ]),
                          )))
            ],
          ),
        ),
        isExpanded ? sizedBoxHeight(40.h) : sizedBoxHeight(18.h),
      ],
    );
  }
}
