
import 'dart:convert';

import 'package:doctor/common/zoom_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:doctor/common/dashboard.dart';
import 'package:doctor/common/settings.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';


class UpdateProfile extends StatefulWidget {
  const UpdateProfile({Key? key}) : super(key: key);
  @override
  State<UpdateProfile> createState() => _UpdateprofileState();
}

class _UpdateprofileState extends State<UpdateProfile> {

  bool isPwdObscureText=true;
  bool isFirstAddButtonShow=false;
  bool isSecondAddButtonShow=false;
  bool is2ndPlaceOfPracticeControllerVisible=false;
  bool is3rdPlaceOfPracticeControllerVisible=false;
  bool isConfirmPwdObscureText=true;
  TextEditingController nameController = TextEditingController();
  TextEditingController mobileNumberController = TextEditingController();
  TextEditingController emailController = TextEditingController();
  TextEditingController ageController = TextEditingController();
  TextEditingController specializationController = TextEditingController();
  TextEditingController qualificationController = TextEditingController();
  TextEditingController hospitalNameController1 = TextEditingController();
  TextEditingController hospitalNameController2 = TextEditingController();
  TextEditingController hospitalNameController3 = TextEditingController();
  TextEditingController practiceAddressController1 = TextEditingController();
  TextEditingController practiceAddressController2 = TextEditingController();
  TextEditingController practiceAddressController3 = TextEditingController();
  String? gender;
  List placeOfPractices=[];




  @override
  void initState() {
    isPwdObscureText=true;
    isConfirmPwdObscureText=true;
    nameController.text=AppSettings.doctorName;
    mobileNumberController.text=AppSettings.phoneNumber;
    emailController.text=AppSettings.email;
    specializationController.text=AppSettings.specialization;
    qualificationController.text=AppSettings.qualification;
    ageController.text=AppSettings.age;
    gender=AppSettings.gender;
    hospitalNameController1.text=AppSettings.placeOfPractice1;
    hospitalNameController2.text=AppSettings.placeOfPractice2;
    hospitalNameController3.text=AppSettings.placeOfPractice3;
    practiceAddressController1.text=AppSettings.placeOfPracticeAddress1;
    practiceAddressController2.text=AppSettings.placeOfPracticeAddress2;
    practiceAddressController3.text=AppSettings.placeOfPracticeAddress3;

    super.initState();


  }

  final ImagePicker _picker = ImagePicker();

  Future pickImageFromGallery() async {
    try {
      final image = await _picker.pickImage(source: ImageSource.gallery);
      if (image == null) return;
      final imageTemp = File(image.path);
      AppSettings.preLoaderDialog(context);
      var res = await AppSettings.uploadImageHTTPNew(image);
      print(jsonDecode(res));
      Navigator.of(context, rootNavigator: true).pop();
      setState(() {
        AppSettings.profilePictureUrl = jsonDecode(res)['picture'];
      });
      AppSettings.saveData('profile', jsonDecode(res)['picture'], 'STRING');
    } on PlatformException catch (e) {
      print('Failed to pick image: $e');
    }
  }

  Future takeImageFromCamera() async {
    try {
      final image = await _picker.pickImage(source: ImageSource.camera);
      if (image == null) return;
      final imageTemp = File(image.path);
      AppSettings.preLoaderDialog(context);
      var res = await AppSettings.uploadImageHTTPNew(image);
      print(jsonDecode(res));
      Navigator.of(context, rootNavigator: true).pop();
      setState(() {
        AppSettings.profilePictureUrl = jsonDecode(res)['picture'];
      });
      AppSettings.saveData('profile', jsonDecode(res)['picture'], 'STRING');
    } on PlatformException catch (e) {
      print('Failed to pick image: $e');
    }
  }


  @override
  Widget build(BuildContext context) {

    return Scaffold(
        appBar:AppSettings.appBar('Edit Profile'),
        body: Stack(children: <Widget>[
          Container(
            decoration: const BoxDecoration(
             /* image: DecorationImage(
                image: AssetImage("images/backgroundimage.png"),
                fit: BoxFit.cover,
              ),*/
            ),
          ),
          GestureDetector(
            onTap: () {
              FocusScope.of(context).requestFocus(new FocusNode());
            },
            child: SafeArea(
                child: SingleChildScrollView(
                  child: Padding(
                    padding: EdgeInsets.all(10),
                    child: Column(
                      children: <Widget>[
                        SizedBox(
                          height:MediaQuery.of(context).size.height * .02,
                        ),
                        Container(child:  GestureDetector(
                          child: Container(
                            width: MediaQuery.of(context).size.width * .30,
                            height: MediaQuery.of(context).size.height * .20,
                            decoration: BoxDecoration(
                                shape: BoxShape.circle,
                                image: DecorationImage(
                                    image: (AppSettings.profilePictureUrl != ''&& AppSettings.profilePictureUrl != 'null') ?
                                    NetworkImage(AppSettings.profilePictureUrl) as ImageProvider : AssetImage("images/profile_pic.png"), // picked file
                                    fit: BoxFit.fitWidth)),
                          ),
                          onTap: () {
                            Navigator.push(
                                context,
                                new MaterialPageRoute(
                                    builder: (__) => new ImageZoomPage(imageName:'Profile',imageDetails:AppSettings.profilePictureUrl)));

                          },
                        ),),
                        TextButton(
                          child: const Text(
                            'Change',
                            style: TextStyle(decoration: TextDecoration.underline,color: primaryColor,fontSize: 12),
                          ),
                          onPressed: () {
                            showModalBottomSheet<void>(
                                context: context,
                                builder: (BuildContext context) {
                                  return SizedBox(
                                    height: 200,
                                    child: Center(
                                      child: Row(
                                        mainAxisAlignment: MainAxisAlignment.center,
                                        children: <Widget>[
                                          GestureDetector(
                                            child: Icon(
                                              Icons.camera_alt_outlined,
                                              size: 100,
                                              color: primaryColor,
                                            ),
                                            onTap: () async {
                                              await takeImageFromCamera();
                                              Navigator.pop(context);
                                            },
                                          ),
                                          SizedBox(
                                            width:
                                            MediaQuery.of(context).size.width * .20,
                                          ),
                                          GestureDetector(
                                            child: Icon(
                                              Icons.photo,
                                              size: 100,
                                              color: primaryColor,
                                            ),
                                            onTap: () async {
                                              await pickImageFromGallery();
                                              Navigator.pop(context);
                                            },
                                          ),
                                        ],
                                      ),
                                    ),
                                  );
                                });
                            //signup screen
                          },
                        ),
                        SizedBox(height:MediaQuery.of(context).size.height * .02,),
                        Container(
                          child: TextFormField(
                            cursorColor: greyColor,
                            controller: nameController,
                            decoration: const InputDecoration(
                              prefixIcon: Icon(
                                Icons.person,
                                color: greyColor,
                              ),
                              border: OutlineInputBorder(
                                  borderSide: BorderSide(color: greyColor)),
                              focusedBorder: OutlineInputBorder(
                                borderSide: BorderSide(color: greyColor),
                              ),
                              enabledBorder: OutlineInputBorder(
                                borderSide: BorderSide(color: greyColor),
                              ),
                              labelText: 'DoctorName',
                              labelStyle: TextStyle(
                                color: greyColor, //<-- SEE HERE
                              ),
                            ),
                          ),
                        ),//name
                        SizedBox(height:MediaQuery.of(context).size.height * .02,),
                        Container(
                          child: TextFormField(
                            cursorColor: greyColor,
                            controller: emailController,
                            keyboardType: TextInputType.emailAddress,
                            decoration: const InputDecoration(
                              prefixIcon: Icon(
                                Icons.email,
                                color: greyColor,
                              ),
                              border: OutlineInputBorder(
                                  borderSide: BorderSide(color: greyColor)),
                              focusedBorder: OutlineInputBorder(
                                borderSide: BorderSide(color: greyColor),
                              ),
                              enabledBorder: OutlineInputBorder(
                                borderSide: BorderSide(color: greyColor),
                              ),
                              labelText: 'Enter email ID',
                              labelStyle: TextStyle(
                                color: greyColor, //<-- SEE HERE
                              ),
                            ),
                          ),
                        ), //email
                        SizedBox(height:MediaQuery.of(context).size.height * .02,),
                        Container(
                          child: TextFormField(
                            cursorColor: greyColor,
                            controller: mobileNumberController,
                            keyboardType: TextInputType.number,
                            decoration: const InputDecoration(
                              prefixIcon: Icon(
                                Icons.phone_android,
                                color: greyColor,
                              ),
                              border: OutlineInputBorder(
                                  borderSide: BorderSide(color: greyColor)),
                              focusedBorder: OutlineInputBorder(
                                borderSide: BorderSide(color: greyColor),
                              ),
                              enabledBorder: OutlineInputBorder(
                                borderSide: BorderSide(color: greyColor),
                              ),
                              labelText: 'Enter Mobile Number',
                              labelStyle: TextStyle(
                                color: greyColor, //<-- SEE HERE
                              ),
                            ),
                          ),
                        ), //mobile
                        SizedBox(height:MediaQuery.of(context).size.height * .02,),
                        Container(
                          child: TextFormField(
                            cursorColor: greyColor,
                            controller: ageController,
                            keyboardType: TextInputType.number,
                            decoration: const InputDecoration(
                              prefixIcon: Icon(
                                Icons.person,
                                color: greyColor,
                              ),
                              border: OutlineInputBorder(
                                  borderSide: BorderSide(color: greyColor)),
                              focusedBorder: OutlineInputBorder(
                                borderSide: BorderSide(color: greyColor),
                              ),
                              enabledBorder: OutlineInputBorder(
                                borderSide: BorderSide(color: greyColor),
                              ),
                              labelText: 'Enter age',
                              labelStyle: TextStyle(
                                color: greyColor, //<-- SEE HERE
                              ),
                            ),
                          ),
                        ),
                        SizedBox(height:MediaQuery.of(context).size.height * .02,),
                        Text('Select Gender',style: TextStyle(color: primaryColor,fontSize: 14,fontWeight: FontWeight.bold),),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.start,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [

                            Expanded(child: RadioListTile(
                              title: Text("Male",style: TextStyle(color: primaryColor,fontSize: 11)),
                              value: "male",
                              groupValue: gender,
                              activeColor: primaryColor,
                              onChanged: (value){
                                setState(() {
                                  gender = value.toString();
                                });
                              },
                            ),),
                            Expanded(child: RadioListTile(
                              title: Text("Female",style:TextStyle(color: primaryColor,fontSize: 11)),
                              value: "female",
                              groupValue: gender,
                              activeColor: primaryColor,
                              onChanged: (value){
                                setState(() {
                                  gender = value.toString();
                                });
                              },
                            ),),
                            Expanded(child: RadioListTile(
                              title: Text("Others",style: TextStyle(color: primaryColor,fontSize: 11)),
                              value: "other",
                              groupValue: gender,
                              activeColor: primaryColor,

                              onChanged: (value){
                                setState(() {
                                  gender = value.toString();
                                });
                              },
                            ),),
                          ],
                        ),
                        SizedBox(height:MediaQuery.of(context).size.height * .02,),
                        Container(
                          child: TextFormField(
                            cursorColor: greyColor,
                            controller: qualificationController,
                            decoration: const InputDecoration(
                              prefixIcon: Icon(
                                Icons.quickreply,
                                color: greyColor,
                              ),
                              border: OutlineInputBorder(
                                  borderSide: BorderSide(color: greyColor)),
                              focusedBorder: OutlineInputBorder(
                                borderSide: BorderSide(color: greyColor),
                              ),
                              enabledBorder: OutlineInputBorder(
                                borderSide: BorderSide(color: greyColor),
                              ),
                              labelText: 'Enter qualification',
                              labelStyle: TextStyle(
                                color: greyColor, //<-- SEE HERE
                              ),
                            ),
                          ),
                        ),
                        SizedBox(height:MediaQuery.of(context).size.height * .02,),
                        Container(
                          child: TextFormField(
                            cursorColor: greyColor,
                            controller: specializationController,
                            decoration: const InputDecoration(
                              prefixIcon: Icon(
                                Icons.folder_special,
                                color: greyColor,
                              ),
                              border: OutlineInputBorder(
                                  borderSide: BorderSide(color: greyColor)),
                              focusedBorder: OutlineInputBorder(
                                borderSide: BorderSide(color: greyColor),
                              ),
                              enabledBorder: OutlineInputBorder(
                                borderSide: BorderSide(color: greyColor),
                              ),
                              labelText: 'Enter specialization',
                              labelStyle: TextStyle(
                                color: greyColor, //<-- SEE HERE
                              ),
                            ),
                          ),
                        ),
                        SizedBox(height:MediaQuery.of(context).size.height * .02,),
                        Text('Place of practice',style: TextStyle(color: primaryColor,fontSize: 14,fontWeight: FontWeight.bold),),
                        SizedBox(height:MediaQuery.of(context).size.height * .02,),
                        Container(
                          width: double.infinity,
                          decoration: BoxDecoration(
                              color: secondaryColor,
                              border: Border.all(
                                //width: 10,
                                color: Colors.white,
                              ),
                              borderRadius: BorderRadius.circular(
                                20,
                              )),
                          child: Padding(
                            padding: EdgeInsets.all(10),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.end,
                              children: [
                                TextFormField(
                                  cursorColor: greyColor,
                                  controller: hospitalNameController1,
                                  decoration: const InputDecoration(
                                    prefixIcon: Icon(
                                      Icons.location_city,
                                      color: greyColor,
                                    ),
                                    border: OutlineInputBorder(
                                        borderSide: BorderSide(color: greyColor)),
                                    focusedBorder: OutlineInputBorder(
                                      borderSide: BorderSide(color: greyColor),
                                    ),
                                    enabledBorder: OutlineInputBorder(
                                      borderSide: BorderSide(color: greyColor),
                                    ),
                                    labelText: 'Enter hospital name',
                                    labelStyle: TextStyle(
                                      color: greyColor, //<-- SEE HERE
                                    ),
                                  ),
                                ),
                                SizedBox(height:MediaQuery.of(context).size.height * .02,),
                                TextFormField(
                                  cursorColor: greyColor,
                                  controller: practiceAddressController1,
                                  decoration: const InputDecoration(
                                    prefixIcon: Icon(
                                      Icons.location_on,
                                      color: greyColor,
                                    ),
                                    border: OutlineInputBorder(
                                        borderSide: BorderSide(color: greyColor)),
                                    focusedBorder: OutlineInputBorder(
                                      borderSide: BorderSide(color: greyColor),
                                    ),
                                    enabledBorder: OutlineInputBorder(
                                      borderSide: BorderSide(color: greyColor),
                                    ),
                                    labelText: 'Enter practice address',
                                    labelStyle: TextStyle(
                                      color: greyColor, //<-- SEE HERE
                                    ),
                                  ),
                                ),
                               Visibility(
                                   visible: hospitalNameController1.text!='',
                                   child:  IconButton(
                                   onPressed: (){

                                     setState(() {
                                       is2ndPlaceOfPracticeControllerVisible=true;
                                     });
                                   },
                                   icon: Icon(Icons.add_box, color: primaryColor,)))
                              ],
                            ),
                          ),
                        ),
                        SizedBox(height:MediaQuery.of(context).size.height * .02,),
                        Visibility(
                          visible:hospitalNameController2.text!=''&&hospitalNameController2.text!='null'||is2ndPlaceOfPracticeControllerVisible,
                          child: Container(
                            width: double.infinity,
                            decoration: BoxDecoration(
                                color: secondaryColor,
                                border: Border.all(
                                  //width: 10,
                                  color: Colors.white,
                                ),
                                borderRadius: BorderRadius.circular(
                                  20,
                                )),
                            child: Padding(
                              padding: EdgeInsets.all(10),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.end,
                                children: [
                                  TextFormField(
                                    cursorColor: greyColor,
                                    controller: hospitalNameController2,
                                    decoration: const InputDecoration(
                                      prefixIcon: Icon(
                                        Icons.location_city,
                                        color: greyColor,
                                      ),
                                      border: OutlineInputBorder(
                                          borderSide: BorderSide(color: greyColor)),
                                      focusedBorder: OutlineInputBorder(
                                        borderSide: BorderSide(color: greyColor),
                                      ),
                                      enabledBorder: OutlineInputBorder(
                                        borderSide: BorderSide(color: greyColor),
                                      ),
                                      labelText: 'Enter hospital name',
                                      labelStyle: TextStyle(
                                        color: greyColor, //<-- SEE HERE
                                      ),
                                    ),
                                  ),
                                  SizedBox(height:MediaQuery.of(context).size.height * .02,),
                                  TextFormField(
                                    cursorColor: greyColor,
                                    controller: practiceAddressController2,
                                    decoration: const InputDecoration(
                                      prefixIcon: Icon(
                                        Icons.location_on,
                                        color: greyColor,
                                      ),
                                      border: OutlineInputBorder(
                                          borderSide: BorderSide(color: greyColor)),
                                      focusedBorder: OutlineInputBorder(
                                        borderSide: BorderSide(color: greyColor),
                                      ),
                                      enabledBorder: OutlineInputBorder(
                                        borderSide: BorderSide(color: greyColor),
                                      ),
                                      labelText: 'Enter practice place',
                                      labelStyle: TextStyle(
                                        color: greyColor, //<-- SEE HERE
                                      ),
                                    ),
                                  ),
                                  Visibility(
                                      visible: hospitalNameController2.text!='',
                                      child:  IconButton(
                                          onPressed: (){

                                            setState(() {
                                              is3rdPlaceOfPracticeControllerVisible=true;
                                            });
                                          },
                                          icon: Icon(Icons.add_box, color: primaryColor,)))
                                ],
                              ),
                            ),
                          ),),
                        SizedBox(height:MediaQuery.of(context).size.height * .02,),
                        Visibility(
                          visible: hospitalNameController3.text!=''&&hospitalNameController3.text!='null'||is3rdPlaceOfPracticeControllerVisible,
                          child: Container(
                            width: double.infinity,
                            decoration: BoxDecoration(
                                color: secondaryColor,
                                border: Border.all(
                                  //width: 10,
                                  color: Colors.white,
                                ),
                                borderRadius: BorderRadius.circular(
                                  20,
                                )),
                            child: Padding(
                              padding: EdgeInsets.all(10),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.end,
                                children: [
                                  TextFormField(
                                    cursorColor: greyColor,
                                    controller: hospitalNameController3,
                                    decoration: const InputDecoration(
                                      prefixIcon: Icon(
                                        Icons.location_city,
                                        color: greyColor,
                                      ),
                                      border: OutlineInputBorder(
                                          borderSide: BorderSide(color: greyColor)),
                                      focusedBorder: OutlineInputBorder(
                                        borderSide: BorderSide(color: greyColor),
                                      ),
                                      enabledBorder: OutlineInputBorder(
                                        borderSide: BorderSide(color: greyColor),
                                      ),
                                      labelText: 'Enter hospital name',
                                      labelStyle: TextStyle(
                                        color: greyColor, //<-- SEE HERE
                                      ),
                                    ),
                                  ),
                                  SizedBox(height:MediaQuery.of(context).size.height * .02,),
                                  TextFormField(
                                    cursorColor: greyColor,
                                    controller: practiceAddressController3,
                                    onChanged:(val) {

                                    },
                                    decoration: const InputDecoration(
                                      prefixIcon: Icon(
                                        Icons.location_on,
                                        color: greyColor,
                                      ),
                                      border: OutlineInputBorder(
                                          borderSide: BorderSide(color: greyColor)),
                                      focusedBorder: OutlineInputBorder(
                                        borderSide: BorderSide(color: greyColor),
                                      ),
                                      enabledBorder: OutlineInputBorder(
                                        borderSide: BorderSide(color: greyColor),
                                      ),
                                      labelText: 'Enter practice place',
                                      labelStyle: TextStyle(
                                        color: greyColor, //<-- SEE HERE
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ),),
                        SizedBox(height:MediaQuery.of(context).size.height * .02,),
                        Container(
                            width:double.infinity,
                            height: MediaQuery.of(context).size.height * .06,
                            child: ElevatedButton(
                              style: ElevatedButton.styleFrom(
                                primary: primaryColor, // background
                                onPrimary: Colors.white, // foreground
                              ),
                              onPressed: () async{
                                if(hospitalNameController1!=''){
                                  placeOfPractices.add({
                                    'hospitalName': hospitalNameController1.text,
                                    'address': practiceAddressController1.text
                                  });
                                }
                                if(hospitalNameController2!=''){
                                  placeOfPractices.add({
                                    'hospitalName': hospitalNameController2.text,
                                    'address': practiceAddressController2.text
                                  });
                                }
                                if(hospitalNameController3!=''){
                                  placeOfPractices.add({
                                    'hospitalName': hospitalNameController3.text,
                                    'address': practiceAddressController3.text
                                  });
                                }





                                int age=0;
                              if(ageController.text.toString()!=''||ageController.text.toString()!='null'){
                                age=int.parse(ageController.text.toString());
                              }
                              else{
                                age=0;
                              }
                              var payload = new Map<String, dynamic>();
                              payload["doctorName"] = nameController.text.toString();
                              payload["phone"] = mobileNumberController.text.toString();
                              payload["age"] = age;
                              payload["gender"] = gender;
                              payload["specialization"] = specializationController.text;
                              payload["qualification"] =qualificationController.text ;
                              payload["placeOfPractice"] =placeOfPractices ;
                              payload["emails"] = [{"email":emailController.text.toString()}];
                              bool signUpStatus = await AppSettings.updateProfile(payload);
                              try{
                                if (signUpStatus) {
                                  Navigator.pop(context);
                                  Navigator.push(
                                    context,
                                    MaterialPageRoute(builder: (context) => Dashboard()),
                                  );
                                  AppSettings.longSuccessToast("profile  updated");
                                } else {

                                  AppSettings.longFailedToast("profile not updated");
                                }
                              }
                              catch(exception){
                                print(exception);
                                AppSettings.longFailedToast("Please enter valid details");
                              }

                              },
                              child: Text('Update'),
                            )
                        ),


                      ],
                    ),
                  )
                )),
          ),
        ]));
  }
}
