import 'dart:io';
import 'dart:ui';

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/flutter_svg.dart';
import 'package:get/get.dart' hide MultipartFile, FormData;
import 'package:glassmorphism/glassmorphism.dart';
import 'package:traderscircuit/Utils/Common/CommonAppbar.dart';
import 'package:traderscircuit/Utils/Common/CustomTextFormField.dart';
import 'package:traderscircuit/Utils/Common/commonBotton.dart';
import 'package:traderscircuit/Utils/base_manager.dart';
import 'package:traderscircuit/Utils/text.dart';
import 'package:traderscircuit/Utils/utils.dart';
import 'package:traderscircuit/resources/routes/route_name.dart';
import 'package:traderscircuit/view/onBoarding/splashScreen1.dart';
import 'package:traderscircuit/view_model/Login/add_kyc_api.dart';

import '../../controller/kyc_controller.dart';
import '../../view_model/RiskProfileApi/risk_profile_api.dart';

import 'package:path/path.dart' as path;

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

  @override
  State<Kyc> createState() => _KycState();
}

class _KycState extends State<Kyc> {
  final GlobalKey<FormState> _addkycform = GlobalKey<FormState>();
  TextEditingController pannumber = TextEditingController();
  TextEditingController aadhaarnumber = TextEditingController();
  Color primaryColor = Colors.transparent.withOpacity(0.2);
  Color secondaryColor = Colors.grey.shade800;

  KYCController kycController = Get.put(KYCController());

  var panFMulti;
  var panBMulti;
  var aadFMulti;
  var aadBMulti;

  _addKyc() async {
    panFMulti = await MultipartFile.fromFile(
      kycController.panFrontImage.value,
      filename: path.basename(kycController.panFrontImage.value),
    );
    panBMulti = await MultipartFile.fromFile(
      kycController.panBackImage.value,
      filename: path.basename(kycController.panBackImage.value),
    );
    aadBMulti = await MultipartFile.fromFile(
      kycController.aadharBackImage.value,
      filename: path.basename(kycController.aadharBackImage.value),
    );
    aadFMulti = await MultipartFile.fromFile(
      kycController.aadharFrontImage.value,
      filename: path.basename(kycController.aadharFrontImage.value),
    );
    final isValid = _addkycform.currentState?.validate();
    if (isValid!) {
      Utils.loader();
      FormData formdata = FormData.fromMap({
        "pan_front_image": panFMulti,
        "pan_back_image": panBMulti,
        "adhar_number": aadhaarnumber.text,
        "pan_number": pannumber.text,
        "adhar_front_image": aadFMulti,
        "adhar_back_image": aadBMulti,
      });

      final resp = await AddKycAPI(formdata).addkycApi();
      if (resp.status == ResponseStatus.SUCCESS) {
        Get.back();
        Get.toNamed(RouteName.updateriskprofile);
      } else if (resp.status == ResponseStatus.PRIVATE) {
        Get.back();
        String? message = resp.data['message'];
        Utils.showToast("$message");
      } else if (resp.status == ResponseStatus.ERROR) {
        Get.back();
        String? message = resp.data['message'];
        Utils.showToast("$message");
      } else {
        Get.back();
        String? message = resp.data['message'];
        Utils.showToast("$message");
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Obx(
      () => WillPopScope(
        onWillPop: () async {
          _onBackButtonPressed(context);
          return true; // Return true to allow the pop action
        },
        child: Scaffold(
          appBar: CommonAppbar(
            titleTxt: "KYC",
            customActionWidget: text16W400(""),
          ),
          backgroundColor: Colors.black,
          extendBody: true,
          body: Stack(
            children: [
              const CommonBlurLeft(),
              const CommonBlurRight(),
              Stack(
                children: [
                  Padding(
                    padding: const EdgeInsets.symmetric(
                        horizontal: 16, vertical: 16),
                    child: Form(
                      key: _addkycform,
                      child: ListView(
                        physics: const BouncingScrollPhysics(),
                        children: [
                          Row(
                            children: [
                              text18W500("Step 1 : Personal Information"),
                            ],
                          ),
                          SizedBox(
                            height: 30.h,
                          ),
                          Row(
                            children: [
                              text18W400("Upload pan card image"),
                            ],
                          ),
                          SizedBox(
                            height: 15.h,
                          ),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              InkWell(
                                onTap: () {
                                  if (kycController.panFrontImage.isEmpty) {
                                    Get.toNamed(RouteName.kycImage, arguments: {
                                      "type": "pan front",
                                    });
                                  }
                                },
                                child: GlassmorphicContainer(
                                  width: 170.w,
                                  height: 105.h,
                                  borderRadius: 8,
                                  linearGradient: LinearGradient(
                                      begin: Alignment.topLeft,
                                      end: Alignment.bottomRight,
                                      colors: [
                                        const Color(0xFFffffff)
                                            .withOpacity(0.1),
                                        const Color(0xFFFFFFFF)
                                            .withOpacity(0.05),
                                      ],
                                      stops: const [
                                        0.1,
                                        1,
                                      ]),
                                  border: 0.8,
                                  blur: 10,
                                  borderGradient: LinearGradient(
                                    begin: Alignment.topLeft,
                                    end: Alignment.bottomRight,
                                    colors: [
                                      const Color(0xff9A0000).withOpacity(0.5),
                                      const Color(0xFFffffff).withOpacity(0.5),
                                    ],
                                  ),
                                  child: (kycController
                                          .panFrontImage.isNotEmpty)
                                      ? Stack(
                                          children: [
                                            Padding(
                                              padding:
                                                  const EdgeInsets.symmetric(
                                                      vertical: 20,
                                                      horizontal: 40),
                                              child: Image(
                                                image: FileImage(
                                                  File(
                                                    kycController
                                                        .panFrontImage.value,
                                                  ),
                                                ),
                                                fit: BoxFit.cover,
                                                width: Get.width,
                                                height: 50.h,
                                              ),
                                            ),
                                            Positioned(
                                              top: 6,
                                              right: 10,
                                              child: InkWell(
                                                onTap: () {
                                                  kycController
                                                      .panFrontImage.value = "";
                                                },
                                                child: SvgPicture.asset(
                                                  "assets/images/svg/cancel.svg",
                                                  width: 18,
                                                  height: 18,
                                                ),
                                              ),
                                            )
                                          ],
                                        )
                                      : Center(
                                          child: Column(
                                            mainAxisAlignment:
                                                MainAxisAlignment.center,
                                            children: [
                                              const Icon(
                                                Icons.file_upload_outlined,
                                                size: 42,
                                                color: Colors.white,
                                              ),
                                              SizedBox(
                                                height: 10.h,
                                              ),
                                              text14W400("Front Side")
                                            ],
                                          ),
                                        ),
                                ),
                              ),
                              InkWell(
                                onTap: () {
                                  if (kycController.panBackImage.isEmpty) {
                                    Get.toNamed(RouteName.kycImage, arguments: {
                                      "type": "pan back",
                                    });
                                  }
                                },
                                child: GlassmorphicContainer(
                                  width: 170.w,
                                  height: 105.h,
                                  borderRadius: 8,
                                  linearGradient: LinearGradient(
                                      begin: Alignment.topLeft,
                                      end: Alignment.bottomRight,
                                      colors: [
                                        const Color(0xFFffffff)
                                            .withOpacity(0.1),
                                        const Color(0xFFFFFFFF)
                                            .withOpacity(0.05),
                                      ],
                                      stops: const [
                                        0.1,
                                        1,
                                      ]),
                                  border: 0.8,
                                  blur: 10,
                                  borderGradient: LinearGradient(
                                    begin: Alignment.topLeft,
                                    end: Alignment.bottomRight,
                                    colors: [
                                      const Color(0xff9A0000).withOpacity(0.5),
                                      const Color(0xFFffffff).withOpacity(0.5),
                                    ],
                                  ),
                                  child: (kycController.panBackImage.isNotEmpty)
                                      ? Stack(
                                          children: [
                                            Padding(
                                              padding:
                                                  const EdgeInsets.symmetric(
                                                      vertical: 20,
                                                      horizontal: 40),
                                              child: Image(
                                                image: FileImage(
                                                  File(
                                                    kycController
                                                        .panBackImage.value,
                                                  ),
                                                ),
                                                fit: BoxFit.cover,
                                                width: Get.width,
                                                height: 50.h,
                                              ),
                                            ),
                                            Positioned(
                                              top: 6,
                                              right: 10,
                                              child: InkWell(
                                                onTap: () {
                                                  kycController
                                                      .panBackImage.value = "";
                                                },
                                                child: SvgPicture.asset(
                                                  "assets/images/svg/cancel.svg",
                                                  width: 18,
                                                  height: 18,
                                                ),
                                              ),
                                            )
                                          ],
                                        )
                                      : Center(
                                          child: Column(
                                            mainAxisAlignment:
                                                MainAxisAlignment.center,
                                            children: [
                                              const Icon(
                                                Icons.file_upload_outlined,
                                                size: 42,
                                                color: Colors.white,
                                              ),
                                              SizedBox(
                                                height: 10.h,
                                              ),
                                              text14W400("Back Side")
                                            ],
                                          ),
                                        ),
                                ),
                              )
                            ],
                          ),
                          SizedBox(
                            height: 30.h,
                          ),
                          Row(
                            children: [
                              text18W400("Pan Card"),
                            ],
                          ),
                          SizedBox(
                            height: 15.h,
                          ),
                          CustomTextFormField(
                            textEditingController: pannumber,
                          ),
                          SizedBox(
                            height: 15.h,
                          ),
                          Row(
                            children: [
                              text18W400("Aadhar Number"),
                            ],
                          ),
                          SizedBox(
                            height: 15.h,
                          ),
                          CustomTextFormField(
                            textEditingController: aadhaarnumber,
                            texttype: TextInputType.phone,
                          ),
                          SizedBox(
                            height: 30.h,
                          ),
                          Row(
                            children: [
                              text18W400("Upload Aadhar card image"),
                            ],
                          ),
                          SizedBox(
                            height: 15.h,
                          ),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              InkWell(
                                onTap: () {
                                  if (kycController.aadharFrontImage.isEmpty) {
                                    Get.toNamed(RouteName.kycImage, arguments: {
                                      "type": "aadhar front",
                                    });
                                  }
                                },
                                child: GlassmorphicContainer(
                                  width: 170.w,
                                  height: 105.h,
                                  borderRadius: 8,
                                  linearGradient: LinearGradient(
                                      begin: Alignment.topLeft,
                                      end: Alignment.bottomRight,
                                      colors: [
                                        const Color(0xFFffffff)
                                            .withOpacity(0.1),
                                        const Color(0xFFFFFFFF)
                                            .withOpacity(0.05),
                                      ],
                                      stops: const [
                                        0.1,
                                        1,
                                      ]),
                                  border: 0.8,
                                  blur: 10,
                                  borderGradient: LinearGradient(
                                    begin: Alignment.topLeft,
                                    end: Alignment.bottomRight,
                                    colors: [
                                      const Color(0xff9A0000).withOpacity(0.5),
                                      const Color(0xFFffffff).withOpacity(0.5),
                                    ],
                                  ),
                                  child: (kycController
                                          .aadharFrontImage.isNotEmpty)
                                      ? Stack(
                                          children: [
                                            Padding(
                                              padding:
                                                  const EdgeInsets.symmetric(
                                                      vertical: 20,
                                                      horizontal: 40),
                                              child: Image(
                                                image: FileImage(
                                                  File(
                                                    kycController
                                                        .aadharFrontImage.value,
                                                  ),
                                                ),
                                                fit: BoxFit.cover,
                                                width: Get.width,
                                                height: 50.h,
                                              ),
                                            ),
                                            Positioned(
                                              top: 6,
                                              right: 10,
                                              child: InkWell(
                                                onTap: () {
                                                  kycController.aadharFrontImage
                                                      .value = "";
                                                },
                                                child: SvgPicture.asset(
                                                  "assets/images/svg/cancel.svg",
                                                  width: 18,
                                                  height: 18,
                                                ),
                                              ),
                                            )
                                          ],
                                        )
                                      : Center(
                                          child: Column(
                                            mainAxisAlignment:
                                                MainAxisAlignment.center,
                                            children: [
                                              const Icon(
                                                Icons.file_upload_outlined,
                                                size: 42,
                                                color: Colors.white,
                                              ),
                                              SizedBox(
                                                height: 10.h,
                                              ),
                                              text14W400("Front Side")
                                            ],
                                          ),
                                        ),
                                ),
                              ),
                              InkWell(
                                onTap: () {
                                  if (kycController.aadharBackImage.isEmpty) {
                                    Get.toNamed(RouteName.kycImage, arguments: {
                                      "type": "aadhar back",
                                    });
                                  }
                                },
                                child: GlassmorphicContainer(
                                  width: 170.w,
                                  height: 105.h,
                                  borderRadius: 8,
                                  linearGradient: LinearGradient(
                                      begin: Alignment.topLeft,
                                      end: Alignment.bottomRight,
                                      colors: [
                                        const Color(0xFFffffff)
                                            .withOpacity(0.1),
                                        const Color(0xFFFFFFFF)
                                            .withOpacity(0.05),
                                      ],
                                      stops: const [
                                        0.1,
                                        1,
                                      ]),
                                  border: 0.8,
                                  blur: 10,
                                  borderGradient: LinearGradient(
                                    begin: Alignment.topLeft,
                                    end: Alignment.bottomRight,
                                    colors: [
                                      const Color(0xff9A0000).withOpacity(0.5),
                                      const Color(0xFFffffff).withOpacity(0.5),
                                    ],
                                  ),
                                  child: (kycController
                                          .aadharBackImage.isNotEmpty)
                                      ? Stack(
                                          children: [
                                            Padding(
                                              padding:
                                                  const EdgeInsets.symmetric(
                                                      vertical: 20,
                                                      horizontal: 40),
                                              child: Image(
                                                image: FileImage(
                                                  File(
                                                    kycController
                                                        .aadharBackImage.value,
                                                  ),
                                                ),
                                                fit: BoxFit.cover,
                                                width: Get.width,
                                                height: 50.h,
                                              ),
                                            ),
                                            Positioned(
                                              top: 6,
                                              right: 10,
                                              child: InkWell(
                                                onTap: () {
                                                  kycController.aadharBackImage
                                                      .value = "";
                                                },
                                                child: SvgPicture.asset(
                                                  "assets/images/svg/cancel.svg",
                                                  width: 18,
                                                  height: 18,
                                                ),
                                              ),
                                            )
                                          ],
                                        )
                                      : Center(
                                          child: Column(
                                            mainAxisAlignment:
                                                MainAxisAlignment.center,
                                            children: [
                                              const Icon(
                                                Icons.file_upload_outlined,
                                                size: 42,
                                                color: Colors.white,
                                              ),
                                              SizedBox(
                                                height: 10.h,
                                              ),
                                              text14W400("Back Side")
                                            ],
                                          ),
                                        ),
                                ),
                              )
                            ],
                          ),
                          SizedBox(
                            height: 70.h,
                          ),
                          CommonBtn(
                            text: "Next",
                            onTap: () {
                              _addKyc();
                              // Get.toNamed(RouteName.updateriskprofile);
                            },
                          ),
                          SizedBox(
                            height: 10.h,
                          ),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  Future<bool> _onBackButtonPressed(BuildContext context) async {
    bool? exitApp = await showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            backgroundColor: const Color(0xFFFFF3E4),
            title: const Text('Exit App'),
            content: const Text('Do you really want to close the app?'),
            actions: [
              TextButton(
                onPressed: () {
                  Navigator.of(context).pop(false);
                },
                child: const Text(
                  'No',
                  style: TextStyle(
                    color: Color(0xff1B243D),
                  ),
                ),
              ),
              TextButton(
                onPressed: () {
                  SystemNavigator.pop();
                  Navigator.pop(context);
                },
                child: const Text(
                  'Yes',
                  style: TextStyle(
                    color: Color(0xff1B243D),
                  ),
                ),
              )
            ],
          );
        });
    return exitApp ?? false;
  }
}
