import 'dart:convert';
import 'dart:developer';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart' hide FormData;
import 'package:traderscircuit/Utils/Common/CommonAppbar.dart';
import 'package:traderscircuit/Utils/dialogs.dart';
import 'package:traderscircuit/Utils/text.dart';
import 'package:traderscircuit/controller/risk_profile_controller.dart';
import 'package:traderscircuit/model/RiskProfileModel/risk_profile_ques_answer_model.dart';
import 'package:traderscircuit/view/onBoarding/splashScreen1.dart';

import '../../Utils/Common/commonBotton.dart';
import '../../Utils/Common/custom_drop_down.dart';
import '../../resources/routes/route_name.dart';
import '../../view_model/RiskProfileApi/risk_profile_api.dart';

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

  @override
  State<UpdateRiskProfile> createState() => _UpdateRiskProfileState();
}

class _UpdateRiskProfileState extends State<UpdateRiskProfile> {
  RxBool isLoading = true.obs;
  RiskProfileController riskProfileController =
      Get.put(RiskProfileController());
  List<int> questionIdList = [];
  List<int> answerIdList = [];
  List<Map<String, List<String>>> dropHeader = [];

  @override
  void initState() {
    RiskProfileApi().getRiskProfileData().then((value) {
      riskProfileController.riskProfileQuestionAnswerModel =
          RiskProfileQuestionAnswerModel.fromJson(value.data);
      for (var a
          in riskProfileController.riskProfileQuestionAnswerModel.data!) {
        List<String> titleTxt = [];
        titleTxt.clear();
        for (var b in a.answer!) {
          titleTxt.add(b.answer!);
        }
        dropHeader.add({a.question!: titleTxt});
      }

      log(dropHeader.toString());
      isLoading.value = false;
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CommonAppbar(
        titleTxt: "Update Risk Profile",
        customActionWidget: text16W400(""),
      ),
      backgroundColor: Colors.black,
      extendBody: true,
      body: Obx(
        () => isLoading.value
            ? const Center(
                child: CircularProgressIndicator(
                  color: Color(0xFF9A0000),
                ),
              )
            : Stack(
                children: [
                  const CommonBlurLeft(),
                  const CommonBlurRight(),
                  Stack(
                    children: [
                      Padding(
                          padding: const EdgeInsets.symmetric(
                              horizontal: 16, vertical: 16),
                          child: ListView.builder(
                              itemCount: riskProfileController
                                      .riskProfileQuestionAnswerModel
                                      .data!
                                      .length +
                                  1,
                              itemBuilder: (ctx, index) {
                                return riskProfileController
                                            .riskProfileQuestionAnswerModel
                                            .data!
                                            .length <=
                                        index
                                    ? Column(
                                        children: [
                                          SizedBox(
                                            height: 70.h,
                                          ),
                                          CommonBtn(
                                            text: "Submit",
                                            onTap: () {
                                              questionIdList.clear();
                                              answerIdList.clear();
                                              if (riskProfileController
                                                      .riskProfileQuestionAnswerModel
                                                      .data!
                                                      .length !=
                                                  riskProfileController
                                                      .selectedData.length) {
                                                utils.showToast(
                                                    "All Fields Required");
                                              } else {
                                                // Iterate through selected data and match with provided data
                                                for (var entry
                                                    in riskProfileController
                                                        .selectedData) {
                                                  String question =
                                                      entry.keys.first;
                                                  String answer =
                                                      entry.values.first;

                                                  // Find matching question
                                                  var questionMatch =
                                                      riskProfileController
                                                          .riskProfileQuestionAnswerModel
                                                          .data!
                                                          .firstWhere(
                                                    (item) =>
                                                        item.question ==
                                                        question,
                                                  );
                                                  if (questionMatch != null) {
                                                    questionIdList
                                                        .add(questionMatch.id!);
                                                  }

                                                  // Find matching answer
                                                  if (questionMatch != null) {
                                                    var answerMatch =
                                                        questionMatch.answer!
                                                            .firstWhere(
                                                      (ans) =>
                                                          ans.answer == answer,
                                                    );
                                                    if (answerMatch != null) {
                                                      answerIdList
                                                          .add(answerMatch.id!);
                                                    }
                                                  }
                                                }

                                                RiskProfileApi()
                                                    .addRiskProfileData(
                                                        FormData.fromMap({
                                                  "question_ids": jsonEncode(
                                                      questionIdList),
                                                  "answer_ids":
                                                      jsonEncode(answerIdList),
                                                }))
                                                    .then((value) {
                                                  Map<String, dynamic>
                                                      responseData =
                                                      Map<String, dynamic>.from(
                                                          value.data);
                                                  utils.showToast(
                                                      responseData["message"]);
                                                  Get.toNamed(
                                                      RouteName.mainscreen);
                                                });
                                              }
                                            },
                                          ),
                                          SizedBox(
                                            height: 10.h,
                                          ),
                                        ],
                                      )
                                    : updateRiskProfileData(
                                        riskProfileController
                                            .riskProfileQuestionAnswerModel
                                            .data![index]
                                            .question!,
                                        "Select your goal",
                                        index);
                              })),
                    ],
                  ),
                ],
              ),
      ),
    );
  }

  Widget updateRiskProfileData(String tilte, String headerText, int index) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        text18W400(tilte),
        SizedBox(
          height: 15.h,
        ),
        CustomDropDownWidget(
          header: headerText,
          listData: dropHeader[index][tilte]!,
          title: tilte,
          type: "risk",
        ),
        SizedBox(
          height: 35.h,
        ),
      ],
    );
  }
}
