import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:gap/gap.dart';
import 'package:get/get.dart' hide MultipartFile, FormData;
import 'package:traderscircuit/Utils/Common/Helper.dart';
import 'package:traderscircuit/Utils/base_manager.dart';
import 'package:traderscircuit/Utils/utils.dart';
import 'package:traderscircuit/model/ProfileModel/GetProfileModel.dart';
import 'package:traderscircuit/view_model/ProfileAPI/GetProfileApi.dart';
import 'package:path/path.dart' as path;
import 'package:traderscircuit/view_model/ProfileAPI/PostProfileApi.dart';
import '../../../Utils/Common/CommonAppbar.dart';
import '../../../Utils/Common/CustomTextFormField.dart';
import '../../../Utils/Common/ImageUpload.dart';
import '../../../Utils/Common/commonBotton.dart';
import '../../../Utils/text.dart';
import '../../../controller/profile_image_controller.dart';
import '../../onBoarding/splashScreen1.dart';

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

  @override
  State<MyProfileScreen> createState() => _MyProfileScreenState();
}

class _MyProfileScreenState extends State<MyProfileScreen> {
  RxBool isLoading = true.obs;
  final ProfileImageController editProfileImage =
      Get.put(ProfileImageController());
  RxBool isEdit = false.obs;
  final GlobalKey<FormState> formK = GlobalKey<FormState>();
  TextEditingController fullNameController = TextEditingController();
  TextEditingController emailController = TextEditingController();
  TextEditingController phoneNoController = TextEditingController();
  TextEditingController dobController = TextEditingController();
  TextEditingController cityController = TextEditingController();

  late Future myfuture;
  ProfileModel profileModel = ProfileModel();

  @override
  void initState() {
    // TODO: implement initState
    myfuture = GetProfile().GetProfileAPI().then((value) {
      profileModel = ProfileModel.fromJson(value.data);
      fullNameController.text = ProfileObj!.data!.userName ?? "User";
      emailController.text = ProfileObj!.data!.emailAddress ?? "Email";
      phoneNoController.text = ProfileObj!.data!.phoneNumber ?? "phone number";
      dobController.text = ProfileObj!.data!.dateOfBirth ?? "date of birth";

      cityController.text = ProfileObj!.data!.city ?? "date of birth";
      isLoading.value = false;
    });

    super.initState();
  }

  DateTime timebackPressed = DateTime.now();

  Future<void> _selectDate(BuildContext context) async {
    final DateTime? picked = await showDatePicker(
        context: context,
        initialDate: DateTime.now(),
        firstDate: DateTime(1900),
        lastDate: DateTime.now(),
        builder: (context, child) {
          return Theme(
              data: Theme.of(context).copyWith(
                colorScheme: const ColorScheme.light(
                  surface: Colors.black,
                  onSurface: Colors.white,
                  primary: Color(0xff9A0000),
                  onPrimary: Colors.white,
                ),
                textButtonTheme: TextButtonThemeData(
                  style: TextButton.styleFrom(
                    foregroundColor: Colors.white,
                  ),
                ),
              ),
              child: child!);
        });

    if (picked != null && picked != DateTime.now()) {
      setState(() {
        dobController.text = "${picked.toLocal()}".split(' ')[0];
        final birthDate = DateTime(
          picked.year,
          picked.month,
          picked.day,
        );
      });
    }
  }

  void UploadData() async {
    Utils.loader();
    var imageFile;

    if (editProfileImage.profilePicPath.value.isNotEmpty) {
      imageFile = await MultipartFile.fromFile(
        editProfileImage.profilePicPath.value,
        filename: path.basename(editProfileImage.profilePicPath.value),
      );
    } else {
      if (ProfileObj!.data!.profilePhoto == null) {
        imageFile = await Helper.assetImageToMultipartFile(
            "assets/images/profileBig.png", "profile");
      } else {
        if (editProfileImage.profilePicPath.value.isEmpty) {
          imageFile = await Helper.networkImageToMultipartFile(
            "${ProfileObj!.data!.profilePhoto ?? ""}",
          );
        } else {
          imageFile = await MultipartFile.fromFile(
            editProfileImage.profilePicPath.value,
            filename: path.basename(editProfileImage.profilePicPath.value),
          );
        }
      }
    }
    FormData formData;

    if (editProfileImage.profilePicPath.value.isEmpty ||
        editProfileImage.profilePicPath.value == "") {
      formData = FormData.fromMap({
        "user_name": fullNameController.text,
        "email_address": emailController.text,
        "phone_number": phoneNoController.text,
        "date_of_birth": dobController.text,
        "city": cityController.text,
      });
    } else {
      formData = FormData.fromMap({
        "user_name": fullNameController.text,
        "email_address": emailController.text,
        "phone_number": phoneNoController.text,
        "date_of_birth": dobController.text,
        "city": cityController.text,
        'profile_photo': imageFile,
      });
    }

    print("formData is ${formData.fields}");
    final data = await PostProfileAPI(formData).ProfileApi();
    // Profiledetails().postProfiledetails(formData);
    if (data.status == ResponseStatus.SUCCESS) {
      Get.back();
      Utils.showToast("Profile updated Successfully!");
      // Get.to(() => CustomBottomBar(pageIndex: 0));
      Get.back(result: true);
      GetProfile().GetProfileAPI();

      // await prefs.setString('name', nameController.text);
      // myusername = nameController.text;
      // Get.back();
      // Get.back(result: true);
    } else {
      Get.back();
      return Utils.showToast(data.message);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Obx(
      () => Form(
        key: formK,
        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: [
                        Padding(
                          padding: const EdgeInsets.symmetric(
                              horizontal: 16, vertical: 16),
                          child: ListView(
                            physics: const BouncingScrollPhysics(),
                            children: [
                              Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  text25W600("My Profile"),
                                  isEdit.value
                                      ? const SizedBox()
                                      : InkWell(
                                          onTap: () {
                                            isEdit.value = true;
                                          },
                                          child: CircleAvatar(
                                            radius: 20.r,
                                            backgroundColor:
                                                const Color(0xFF5A5A5A),
                                            child: Icon(
                                              Icons.edit,
                                              size: 20.sp,
                                              color: Colors.white,
                                            ),
                                          ),
                                        ),
                                ],
                              ),
                              const Gap(20),
                              Center(
                                child: Stack(
                                  children: [
                                    Obx(
                                      () => editProfileImage
                                                  .profilePicPath.value !=
                                              ''
                                          ? ClipOval(
                                              child: SizedBox.fromSize(
                                                size: Size.fromRadius(60.r),
                                                child: editProfileImage
                                                            .profilePicPath
                                                            .value !=
                                                        ''
                                                    ? Image(
                                                        image: FileImage(
                                                          File(
                                                            editProfileImage
                                                                .profilePicPath
                                                                .value,
                                                          ),
                                                        ),
                                                        fit: BoxFit.cover,
                                                        width: 200.w,
                                                        height: 200.h,
                                                      )
                                                    : Image.asset(
                                                        "assets/images/blank-profile-picture-973460_1280.png"),
                                              ),
                                            )
                                          : ClipOval(
                                              child: SizedBox.fromSize(
                                                  size: Size.fromRadius(60.r),
                                                  child: ProfileObj?.data!
                                                              .profilePhoto !=
                                                          null
                                                      ? ClipOval(
                                                          child:
                                                              SizedBox.fromSize(
                                                            size:
                                                                Size.fromRadius(
                                                                    25.r),
                                                            child: CircleAvatar(
                                                              backgroundImage:
                                                                  NetworkImage(
                                                                      ProfileObj!
                                                                          .data!
                                                                          .profilePhoto!),
                                                              radius: 25.r,
                                                            ),
                                                          ),
                                                        )
                                                      : Image.asset(
                                                          "assets/images/png/Ellipse 560 (1).png",
                                                          width: 130,
                                                          height: 130,
                                                        )),
                                            ),
                                    ),
                                    Positioned(
                                      right: 0,
                                      bottom: 0,
                                      child: GestureDetector(
                                        onTap: () {
                                          ImageUploadBottomSheet().showModal(
                                            context,
                                            false,
                                            (result) {
                                              print("File path is $result");
                                              editProfileImage.profilePicPath
                                                  .value = result;
                                            },
                                          );
                                        },
                                        child: CircleAvatar(
                                          radius: 20.r,
                                          backgroundColor:
                                              const Color(0xFF5A5A5A),
                                          child: Icon(
                                            Icons.camera_alt_outlined,
                                            size: 20.sp,
                                            color: Colors.white,
                                          ),
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                              Row(
                                children: [
                                  text18W400("Full Name"),
                                ],
                              ),
                              SizedBox(
                                height: 15.h,
                              ),
                              CustomTextFormField(
                                textEditingController: fullNameController,
                                enabled: isEdit.value,
                                validator: (value) {
                                  if (value == "") {
                                    return "Name is Required";
                                  }
                                },
                              ),
                              SizedBox(
                                height: 30.h,
                              ),
                              Row(
                                children: [
                                  text18W400("Email Address"),
                                ],
                              ),
                              SizedBox(
                                height: 15.h,
                              ),
                              CustomTextFormField(
                                textEditingController: emailController,
                                enabled: isEdit.value,
                                texttype: TextInputType.emailAddress,
                              ),
                              SizedBox(
                                height: 30.h,
                              ),
                              Row(
                                children: [
                                  text18W400("Phone Number"),
                                ],
                              ),
                              SizedBox(
                                height: 15.h,
                              ),
                              CustomTextFormField(
                                textEditingController: phoneNoController,
                                enabled: isEdit.value,
                                texttype: TextInputType.phone,
                              ),
                              SizedBox(
                                height: 30.h,
                              ),
                              Row(
                                children: [
                                  text18W400("Date Of Birth"),
                                ],
                              ),
                              SizedBox(
                                height: 15.h,
                              ),
                              CustomTextFormField(
                                textEditingController: dobController,
                                enabled: isEdit.value,
                                suffixIcon: const Icon(
                                  Icons.calendar_month_outlined,
                                  color: Colors.white,
                                ),
                                readonly: true,
                                onTap: () {
                                  _selectDate(context);
                                },
                              ),
                              SizedBox(
                                height: 30.h,
                              ),
                              Row(
                                children: [
                                  text18W400("City"),
                                ],
                              ),
                              SizedBox(
                                height: 15.h,
                              ),
                              CustomTextFormField(
                                textEditingController: cityController,
                                enabled: isEdit.value,
                              ),
                              SizedBox(
                                height: 40.h,
                              ),
                              !isEdit.value
                                  ? const SizedBox()
                                  : SizedBox(
                                      width: Get.width,
                                      child: kycBtn(
                                        text: "Save",
                                        onTap: () {
                                          final isValid =
                                              formK.currentState?.validate();

                                          if (isValid!) {
                                            UploadData();
                                          }
                                        },
                                        bgClr: const Color(0xFF6C0000),
                                        borderClr: const Color(0xFF990000),
                                      ),
                                    ),
                            ],
                          ),
                        )
                      ],
                    )
            ],
          ),
        ),
      ),
    );
  }
}
