import 'package:connectycube_sdk/connectycube_sdk.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:image_picker/image_picker.dart';
import 'package:universal_io/io.dart';
import 'package:vmeeting/blocs/edit_profile_bloc/edit_profile_bloc.dart';
import 'package:vmeeting/service/user_repositores/user_repo.dart';
import 'package:vmeeting/src/controllers/enter_number_cont.dart';
import 'package:vmeeting/src/extension/context_extensions.dart';
import 'package:vmeeting/src/widgets/big_text_widget.dart';
import 'package:vmeeting/src/widgets/small_text.dart';
import '../../service/routes/routes_name.dart';
import '../../src/constants/colors_const.dart';
import '../../src/utils/app_utils.dart';
import '../../src/widgets/custom_loading/customloading.dart';
import '../../src/widgets/exceptions/app_exeptions.dart';
import '../../src/widgets/image_avatar.dart';
import '../../src/widgets/textfiled_widgets/auth_text_fild.dart';

class EditProfilePage extends StatefulWidget {
  final NumberController controller;
  const EditProfilePage({super.key, required this.controller});

  @override
  State<EditProfilePage> createState() => _EditProfilePageState();
}

class _EditProfilePageState extends State<EditProfilePage> {
  late EditProfileBloc editProfileBloc;


  final _loginControlle = TextEditingController(text: AppUtils.userModel.login);
  final _loginFocusNode = FocusNode();
  final _phoneControlle = TextEditingController(text: AppUtils.userModel.phone);
  final _phoneFocusNode = FocusNode();
  final _emailControlle = TextEditingController(text: AppUtils.userModel.email);
  final _emailFocusNode = FocusNode();
  final _fullNameControlle = TextEditingController(text: AppUtils.userModel.fullName);
  final _fullNameFocusNode = FocusNode();

  @override
  void initState() {
    super.initState();
    editProfileBloc = BlocProvider.of<EditProfileBloc>(context);
    editProfileBloc.add(EditProfileFetchEvent());
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        elevation: 0,
        title: const BigText(text: "Edit profile"),
      ),
      body: BlocConsumer<EditProfileBloc, EditProfileState>(
        listener: (context, state) {},
        builder: (context, state) {
          if (state is EditProfileInitialState) {
            return buildLoading();
          } else if (state is EditProfileLoadedState) {
            return buildUI(state.user);
          }
          if (state is EditProfileExceptionState) {
            return  const Center(
                child: AppExceptionsWidget(
                    message: "Exception", authName: MainRoutes.edit_profile_page));
          }
          return const Center(child: Text("AloVoice"));
        },
      ),
    );
  }

  Widget buildUI(CubeUser cubeUser){
    return Container(
      margin: EdgeInsets.symmetric(horizontal: context.w * 0.06),
      child: SingleChildScrollView(
        child: Column(children: [
          SizedBox(height: context.h * 0.05),
          buildImage(context,cubeUser),
          buildTextFiled(cubeUser),
          SizedBox(height: context.h * 0.03),
          buildButtons(context,cubeUser),

        ],),
      )
    );
  }

  Widget buildTextFiled(CubeUser cubeUser){
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
      SizedBox(height: context.h * 0.06),
      const SmallText(text: "Full Name"),
        SizedBox(height: context.h * 0.01),
      AuthTextFild(
        lableName: "FullName",
        borderRadius: 10,
        elevation: 1,
        color: Colors.grey.withOpacity(0.2),
        focusNode: _fullNameFocusNode,
        textEditingController: _fullNameControlle,
      ),
      SizedBox(height: context.h * 0.02),
        const SmallText(text: "Email"),
        SizedBox(height: context.h * 0.01),
      AuthTextFild(
        lableName: "Email",
        borderRadius: 10,
        elevation: 1,
        color: Colors.grey.withOpacity(0.2),
        type: TextInputType.emailAddress,
        focusNode: _emailFocusNode,
        textEditingController: _emailControlle,
      ),
      SizedBox(height: context.h * 0.02),
        const SmallText(text: "Login"),
        SizedBox(height: context.h * 0.01),
      AuthTextFild(
        lableName: "Login",
        borderRadius: 10,
        elevation: 1,
        color: Colors.grey.withOpacity(0.2),
        focusNode: _loginFocusNode,
        textEditingController: _loginControlle,
      ),
      SizedBox(height: context.h * 0.02),
        const SmallText(text: "Phone Number"),
        SizedBox(height: context.h * 0.01),
      AuthTextFild(
        lableName: "Phone Number",
        borderRadius: 10,
        elevation: 1,
        color: Colors.grey.withOpacity(0.2),
        focusNode: _phoneFocusNode,
        textEditingController: _phoneControlle,
        type: TextInputType.phone,
      ),
      SizedBox(height: context.h * 0.01),
    ],);
  }


  Widget buildButtons(BuildContext context, CubeUser cubeUser) {
    return StreamBuilder(stream: widget.controller.outputElevatedButton,
        builder: (BuildContext context, snapshot){
          return Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              ElevatedButton(
                style: ElevatedButton.styleFrom(
                  foregroundColor: Colors.white,
                  backgroundColor: ColorConst.appGreenColor,
                  disabledForegroundColor: Colors.grey.withOpacity(0.38),
                  disabledBackgroundColor: Colors.grey.withOpacity(0.12),
                ),
                onPressed: () async {
                  if(_loginControlle.text.isNotEmpty && _emailControlle.text.isNotEmpty && _fullNameControlle.text.isNotEmpty){
                    widget.controller.inputElevatedButton.add(true);
                    editProfileBloc.add(EditProfileUpdateEvent(
                      controller: widget.controller,
                        user: CubeUser(
                          fullName: _fullNameControlle.text,
                          email: _emailControlle.text,
                          login: _loginControlle.text,
                          phone: _phoneControlle.text,
                          id: cubeUser.id,
                        ), context: context
                    ));
                  }else{
                    AppUtils.showSnackBar(context, "PLEASE ENTER THE SAME VALUE AGAIN");
                  }

                },
                child: SizedBox(
                  height: context.h * 0.06,
                  child:  Center(
                    child: snapshot.data ?? false
                        ? AppUtils.buttonLoader
                        :  BigText(
                      text: "Update".toUpperCase(),
                      fontWidget: FontWeight.bold,
                      size: 16,
                    ),
                  ),
                ),
              ),
            ],
          );
        });
  }


  Widget buildImage(BuildContext context, CubeUser cubeUser) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.end,
      children: [
    imageCameraForView == null
        ? AvatarImage(
          radius: context.h * 0.09,
          imagePath: getPrivateUrlForUid(cubeUser.avatar),
        )
        : CircleAvatar(
    radius: 70,
    backgroundColor: ColorConst.appGreenColor,
    backgroundImage: FileImage(imageCameraForView!)),
          InkWell(
          child: Icon(Icons.edit,size: 30,color: ColorConst.appGreenColor,),
          onTap: (){
            _onImageButtonPressed(ImageSource.gallery,
                context: context);
          },
        )

      ],
    );
  }

  File? imageCameraForView;
  final ImagePicker _picker = ImagePicker();
  Future<void> _onImageButtonPressed(ImageSource source,
      {required BuildContext context}) async {
    if (mounted) {
      {
        try {
          final XFile? pickedFile = await _picker.pickImage(
            source: source,
            maxWidth: 480,
            maxHeight: 640,
            imageQuality: 100,
          );
          pickImageCameraAndUpload(context, pickedFile);
        } on PlatformException catch (e) {
          print('Failed to pick image: $e');
        }
      }
    }
  }

  File? documentFile;
  Future<void> pickImageCameraAndUpload(
      BuildContext context, XFile? imageCamera) async {
    if (imageCamera != null) {
      documentFile = File(imageCamera.path);
      setState(() {});
      Future.delayed(Duration(seconds: 1));
      try {
        final imageTempCamera = File(imageCamera.path);
        setState(() => imageCameraForView = imageTempCamera);
        await UserRepository.getInstance().uploadAvatar(file: imageTempCamera, context: context);
      } on PlatformException catch (e) {
        print('Failed to pick image: $e');
      }
    }
  }

  Widget buildLoading() {
    return Center(child: CustomLoading());
  }
}
