import 'dart:io';
import 'package:flutter/material.dart';
import 'package:top_news_app/helper/custom_appbar.dart';
import 'package:top_news_app/helper/helper.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:image_picker/image_picker.dart';
import 'package:top_news_app/localization/localization.dart';
import '../model/user.dart';
import '../repos/exception_handlers.dart';
import '../repos/repository.dart';
import '../services/auth_service.dart';
import '../services/storage_service.dart';

class UpdateProfile extends StatefulWidget {
  final User user;
  const UpdateProfile({Key? key, required this.user}) : super(key: key);

  @override
  State<UpdateProfile> createState() => _UpdateProfileState();
}

class _UpdateProfileState extends State<UpdateProfile> {
  bool showPassword = false;
  var name = TextEditingController();
  var bio = TextEditingController();
  bool isLoading = false;

  var authService = AuthService();
  XFile? _image ;
  final imagePicker = ImagePicker();

  Widget showImage = Container();


  _showPicker() {
    showModalBottomSheet(
        context: context,
        builder: (BuildContext bc) {
          return SafeArea(
            child: Wrap(
              children: <Widget>[
                ListTile(
                    leading: const Icon(Icons.photo_library),
                    title:  Text(getTranslated(context, 'Photo Gallery') ?? 'Photo Gallery'),
                    onTap: () {
                      _pickImageFromGallery();
                      Navigator.pop(context);
                    }),
                ListTile(
                  leading: const Icon(Icons.photo_camera),
                  title:  Text(getTranslated(context, 'Camera')??'Camera'),
                  onTap: () {
                    _pickImageFromCamera();
                    Navigator.pop(context);
                  },
                ),
              ],
            ),
          );
        });
  }

  _pickImageFromCamera() async {
    final pickedFile = await imagePicker.pickImage(source: ImageSource.camera);

    setState(() {
      if (pickedFile != null) {
        setState(() {
          _image = XFile(pickedFile.path);
        });
      } else {

      }
    });
    _saveValue();
  }

  _pickImageFromGallery() async {
    final pickedFile = await imagePicker.pickImage(source: ImageSource.gallery);

    setState(() {
      if (pickedFile != null) {
        setState(() {
          _image = XFile(pickedFile.path);
        });
      } else {

      }
    });
    _saveValue();
  }


  Widget _showImage() {
    if (_image != null) {
      return GestureDetector(
        onTap: (){
          _showPicker();
        },
        child: Align(
          alignment: Alignment.center,
          child: Center(
            child: Stack(
              children: [
                Container(
                  width: 130,
                  height: 130,
                  decoration: BoxDecoration(
                    border: Border.all(
                        width: 4,
                        color: Theme.of(context).scaffoldBackgroundColor),
                    boxShadow: const [
                      BoxShadow(
                          spreadRadius: 2,
                          blurRadius: 10,
                          offset: Offset(0, 10))
                    ],
                    shape: BoxShape.rectangle,),
                  child: Image(
                    image: FileImage(File(_image!.path)),
                    fit: BoxFit.cover,
                  ),
                ),
                Positioned(
                    bottom: 0,
                    right: 0,
                    child: Container(
                      height: 40,
                      width: 40,
                      decoration: BoxDecoration(
                        shape: BoxShape.circle,
                        border: Border.all(
                          width: 4,
                          color: Theme.of(context).primaryColor,
                        ),
                      ),
                      child: const Icon(
                        Icons.edit,
                      ),
                    )),
              ],
            ),
          ),
        ),
      );
    } else {
      return GestureDetector(
        onTap: (){
          _showPicker();
        },
        child: Align(
          alignment: Alignment.center,
          child: Center(
            child: Stack(
              children: [
                Container(
                  width: 130,
                  height: 130,
                  decoration: BoxDecoration(
                    border: Border.all(
                        width: 4,
                        color: Theme.of(context).scaffoldBackgroundColor),
                    boxShadow: [
                      BoxShadow(
                          spreadRadius: 2,
                          blurRadius: 10,
                          color: Colors.black.withOpacity(0.1),
                          offset: const Offset(0, 10))
                    ],
                    shape: BoxShape.rectangle,),
                  child: Image(
                    image: NetworkImage('${widget.user.data?.avatar}'),
                    fit: BoxFit.cover,
                  ),
                ),
                Positioned(
                    bottom: 0,
                    right: 0,
                    child: Container(
                      height: 40,
                      width: 40,
                      decoration: const BoxDecoration(
                        shape: BoxShape.circle,
                        color: primaryColors,
                      ),
                      child: const Icon(
                        Icons.edit,
                      ),
                    )),
              ],
            ),
          ),
        ),
      );
    }
  }


  _saveValue() async{
    try{
      var repo = Repository();
      var response = await repo.httpFileUpload('avatar/update', _image!,'');
      var result = processResponse(response);
      StorageService().setSingleValue('avatar', result['link'].toString());
    }catch ($e){
      var message = ExceptionHandlers().getExceptionString($e);
      showMessage(message);
    }

  }

  @override
  void initState() {
    super.initState();
    name.text = widget.user.data!.name!;
    bio.text = widget.user.data?.bio ?? '';
  }

  updateProfile() async{
    setState(() {
      isLoading = true;
    });

    try {
      if (name.text != '' && bio.text != '') {
        StorageService().setSingleValue('name', name.text);
        var result = await authService.updateProfile(
            name.text.toString(), bio.text.toString());

        if (result.containsKey('message')) {
          showMessage(result['message']);
        }
        if (result.containsKey('result')) {
          StorageService().setSingleValue('name', name.text);
        }
      } else {
        showMessage(getTranslated(context, 'Enter the right data') ??
            'Enter the right data');
      }
    }catch ($e){
      var message = ExceptionHandlers().getExceptionString($e);
      showMessage(message);
    }
    setState(() {
      isLoading = false;
    });
  }

  @override
  Widget build(BuildContext context) {

    Size size = MediaQuery.of(context).size;
    return SafeArea(
      child: Scaffold(
        appBar: customAppBar(getTranslated(context, 'Profile update') ?? 'Profile update', '',context),
        body:  Container(
          padding: const EdgeInsets.all(12),
          child: GestureDetector(
            onTap: () {
              FocusScope.of(context).unfocus();
            },
            child: ListView(
              children: [
                const SizedBox(
                  height: 25,
                ),
                Center(
                  child: _showImage(),
                ),
                const SizedBox(
                  height: 35,
                ),
                buildTextField(getTranslated(context, 'Full Name') ?? 'Full Name', "${widget.user.data?.name}", false,name),
                buildTextField(getTranslated(context, 'About') ?? 'About', "${widget.user.data?.bio ?? ''}", false,bio),
                const SizedBox(
                  height: 15,
                ),
                GestureDetector(
                  onTap: (){

                    updateProfile();

                  },
                  child:  Container(
                    height: 50,
                    width: size.width,
                    margin: const EdgeInsets.symmetric(horizontal: 40),
                    decoration: const BoxDecoration(
                        borderRadius: BorderRadius.all(Radius.circular(15)),
                      color: primaryColors
                    ),
                    child: Center(child:
                    isLoading ? const CircularProgressIndicator() :  Text(getTranslated(context, 'Update Information') ?? 'Update Information',style: GoogleFonts.robotoMono(fontWeight: FontWeight.bold),)),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget buildTextField(
      String labelText, String placeholder, bool isPasswordTextField, TextEditingController controller) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 35.0),
      child: TextField(
        controller: controller,
        obscureText: isPasswordTextField ? showPassword : false,
        decoration: InputDecoration(
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(15.0),
            ),

            suffixIcon: isPasswordTextField
                ? IconButton(
              onPressed: () {
                showPassword = !showPassword;
              },
              icon: const Icon(
                Icons.remove_red_eye,
                color: Colors.grey,
              ),
            )
                : null,
            contentPadding: const EdgeInsets.all(12),
            labelText: labelText,
            labelStyle: GoogleFonts.robotoSerif(fontWeight: FontWeight.w500),
            floatingLabelBehavior: FloatingLabelBehavior.always,
            hintText: placeholder,
            hintMaxLines: 8,
            hintStyle:  GoogleFonts.roboto(
              fontSize: 16,
              fontWeight: FontWeight.bold,
            )),
      ),
    );
  }
}