import 'dart:convert';

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: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';

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();
  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();
  }

  @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 Profile"),
          Expanded(
            child: SingleChildScrollView(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  GestureDetector(
                    onTap: () async {
                      FilePickerResult? result =
                          await FilePicker.platform.pickFiles();
                      if (result != null) {
                        PlatformFile file = result.files.first;

                        // print(file.name);
                        // print(file.bytes);
                        // print(file.size);
                        // print(file.extension);
                        // print(file);
                        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: "Update",
                      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);
                                });
                          }
                        });
                      },
                    ),
                  )
                ],
              ),
            ),
          )
        ],
      ),
    );
  }
}
