// ignore_for_file: use_build_context_synchronously

import 'dart:async';
import 'dart:convert';
import 'dart:js_interop';
import 'dart:js_util';

// import 'package:file_picker/file_picker.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:image_picker/image_picker.dart';
import 'package:tour_travel_agr/api/all_api.dart';
import 'package:tour_travel_agr/helper/components_widget/custom_appbar.dart';
import 'package:tour_travel_agr/helper/components_widget/widget_button.dart';
import 'package:tour_travel_agr/helper/components_widget/widget_text_field.dart';
import 'package:tour_travel_agr/helper/modal_dialog.dart';
import 'package:tour_travel_agr/helper/prefs.dart';
import 'package:tour_travel_agr/helper/widget_responsive.dart';
import 'package:tour_travel_agr/models/profile_model.dart';
import 'package:tour_travel_agr/resource/assets.dart';
import 'package:tour_travel_agr/resource/colors.dart';
import 'package:tour_travel_agr/resource/routes.dart';
import 'package:tour_travel_agr/resource/size.dart';
import 'package:tour_travel_agr/resource/strings.dart';

@JS('compressImage')
external dynamic compressImage(byte, quality);

class EditProfileView extends StatefulWidget {
  const EditProfileView({
    super.key,
    required this.profile,
    this.onSuccessUpdate,
  });

  final ProfileModel profile;
  final void Function(bool)? onSuccessUpdate;

  @override
  State<EditProfileView> createState() => _EditProfileViewState();
}

class _EditProfileViewState extends State<EditProfileView> {
  TextEditingController nameController = TextEditingController();
  TextEditingController nikController = TextEditingController();
  TextEditingController hpController = TextEditingController();
  List<String> allowedExt = ['jpg', 'png', 'jpeg'];
  Uint8List? byteImage;
  String? base64Image;

  @override
  void initState() {
    setState(() {
      nameController.text = widget.profile.fullName;
      nikController.text = widget.profile.nik;
      hpController.text = widget.profile.mobilePhone;
    });

    super.initState();
  }

  // Uint8List compressImage(Uint8List imageBytes, int quality) {
  //   final image = img.decodeImage(imageBytes);

  //   // Mengompres gambar dengan kualitas yang ditentukan
  //   final compressedImage = img.encodeJpg(image!, quality: quality);

  //   return compressedImage;
  // }
  // Future<Uint8List> compressImage(Uint8List imageBytes, int quality) async {
  //   final jsObject =
  //       js.JsObject(js.context['compressImage'], [imageBytes, quality]);
  //   final compressedBytes = await jsObject.callMethod('compressImage');

  //   return Uint8List.fromList(compressedBytes);
  // }
  int maxSizeToCompare = 5242880;
  int qualityCompare = 80;

  Future<dynamic> compressImageJs(Uint8List imageBytes, int quality) async {
    dynamic result = await promiseToFuture(compressImage(imageBytes, quality));
    return result;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ColorManager.backgroundColor,
      body: ScreenResponsive(
        widget: bodyWidget(context),
        widthScreen: MediaQuery.of(context).size.width,
      ),
    );
  }

  Container bodyWidget(BuildContext context) {
    return Container(
      padding: EdgeInsets.only(
        top: AppPadding.safeAreaTop(context),
        left: AppPadding.p20,
        right: AppPadding.p20,
        bottom: AppPadding.safeAreaBot(context),
      ),
      child: Column(
        children: [
          const CustomAppBar(text: "Edit Profil"),
          Expanded(
            child: SingleChildScrollView(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  GestureDetector(
                    onTap: () async {
                      final imagePicker = ImagePicker();
                      XFile? pickedImage = await imagePicker.pickImage(
                          source: ImageSource.gallery);
                      if (pickedImage != null) {
                        Uint8List uint8 = await pickedImage.readAsBytes();
                        String ext =
                            pickedImage.name.split('.').last.toLowerCase();
                        // print(compressImage(uint8, 50));
                        if (!allowedExt.contains(ext)) {
                          modalDialogGlobal(
                            context: context,
                            title: "Informasi",
                            contentBody:
                                "Hanya mendukung gambar dengan format ${allowedExt.join(', ')}, silakan pilih file lainnya",
                            buttonText: "OK",
                            tapButton: () {
                              Navigator.pop(context);
                            },
                          );
                          return;
                        }
                        if (uint8.length > maxSizeToCompare) {
                          await EasyLoading.show(
                            status: Strings.pleaseWait,
                            maskType: EasyLoadingMaskType.none,
                          );
                          dynamic resultCompress =
                              await compressImageJs(uint8, qualityCompare);
                          EasyLoading.dismiss();
                          if (resultCompress.runtimeType != Uint8List) {
                            modalDialogGlobal(
                              context: context,
                              title: "Informasi",
                              contentBody:
                                  "Kesalahan saat melakukan deteksi gambar",
                              buttonText: "OK",
                              tapButton: () {
                                Navigator.pop(context);
                              },
                            );
                          }
                          setState(() {
                            byteImage = resultCompress;
                            base64Image = base64Encode(byteImage!);
                          });
                        } else {
                          setState(() {
                            byteImage = uint8;
                            base64Image = base64Encode(byteImage!);
                          });
                        }
                      }
                      // FilePickerResult? result =
                      //     await FilePicker.platform.pickFiles();
                      // if (result != null) {
                      //   PlatformFile file = result.files.first;

                      //   String ext = file.name.split('.').last.toLowerCase();
                      //   if (!allowedExt.contains(ext)) {
                      //     modalDialogGlobal(
                      //       context: context,
                      //       title: "Informasi",
                      //       contentBody:
                      //           "Hanya mendukung gambar dengan format ${allowedExt.join(', ')}, silakan pilih file lainnya",
                      //       buttonText: "OK",
                      //       tapButton: () {
                      //         Navigator.pop(context);
                      //       },
                      //     );
                      //     return;
                      //   }
                      //   // print(file.name);
                      //   // print(file.bytes);
                      //   // print(file.size);
                      //   // print(file.extension);
                      //   // print(file.path);
                      //   if (file.size > 2097152) {
                      //     await testComporessList(file.bytes!);
                      //   } else {}
                      //   setState(() {
                      //     byteImage = file.bytes;
                      //     base64Image = base64Encode(byteImage!);
                      //   });
                      //   // print(file.path);
                      // } else {
                      //   // User canceled the picker
                      // }
                    },
                    child: Container(
                      margin: EdgeInsets.only(
                        top: AppMargin.m12,
                      ),
                      width: 112,
                      height: 112,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(100),
                        color: const Color.fromARGB(255, 235, 232, 232),
                      ),
                      child: (byteImage == null)
                          ? (widget.profile.avatarUrl == "")
                              ? Image(
                                  width: 52,
                                  height: 52,
                                  image: AssetImage(
                                    Assets.editProfileSample,
                                  ),
                                )
                              : ClipRRect(
                                  borderRadius: BorderRadius.circular(100),
                                  child: Image.network(
                                    widget.profile.avatarUrl,
                                    fit: BoxFit.fill,
                                  ),
                                )
                          : ClipRRect(
                              borderRadius: BorderRadius.circular(100),
                              child: Image.memory(
                                byteImage!,
                                fit: BoxFit.fill,
                              ),
                            ),
                    ),
                  ),
                  InputTextField(
                    controller: nameController,
                    labelText: "Nama Lengkap",
                    labelColor: ColorManager.primary,
                    borderSideActive: true,
                    hintText: "Nama Lengkap",
                    marginTop: 18,
                  ),
                  InputTextField(
                    controller: nikController,
                    labelText: "NIK",
                    labelColor: ColorManager.primary,
                    borderSideActive: true,
                    enabled: false,
                    hintText: "Nomor Induk Kependudukan",
                    marginTop: 12,
                  ),
                  InputTextField(
                    controller: hpController,
                    labelText: "Nomor Handphone",
                    labelColor: ColorManager.primary,
                    borderSideActive: true,
                    enabled: false,
                    hintText: "628....",
                    marginTop: 12,
                    inputType: TextInputType.number,
                  ),
                  Container(
                    margin: const EdgeInsets.only(top: 30),
                    child: CustomButton(
                      text: "Ubah",
                      onTap: () async {
                        await EasyLoading.show(
                          status: Strings.pleaseWait,
                          maskType: EasyLoadingMaskType.none,
                        );
                        Api.changeProfile(
                          nameController.text,
                          base64Image,
                        ).then((apiResponse) {
                          EasyLoading.dismiss();
                          if (apiResponse.error) {
                            if (apiResponse.data["code"] ==
                                "WRONG_SESSION_ID") {
                              modalDialogGlobal(
                                context: context,
                                title: "Session Expired",
                                contentBody: Strings.sessionExpired,
                                buttonText: "OK",
                                tapButton: () {
                                  removeSessionId();
                                  Navigator.pushNamedAndRemoveUntil(
                                    context,
                                    Routes.loginRoute,
                                    (route) => false,
                                  );
                                },
                              );
                            } else {
                              modalDialogGlobal(
                                context: context,
                                title: "Error",
                                contentBody: apiResponse.msg,
                                buttonText: "OK",
                                tapButton: () {
                                  Navigator.pop(context);
                                },
                              );
                            }
                          } else {
                            modalDialogGlobal(
                                context: context,
                                title: "Success",
                                contentBody: apiResponse.msg,
                                buttonText: "Ok",
                                tapButton: () {
                                  widget.onSuccessUpdate!(true);
                                  Navigator.pop(context);
                                  Navigator.pop(context);
                                });
                          }
                        });
                      },
                    ),
                  )
                ],
              ),
            ),
          )
        ],
      ),
    );
  }
}
