package com.example.tampopo_client.views;


import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;

import androidx.activity.EdgeToEdge;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.bumptech.glide.Glide;
import com.example.tampopo_client.R;
import com.example.tampopo_client.Tampopo;
import com.example.tampopo_client.viewmodels.UserViewModel;
import com.google.android.material.imageview.ShapeableImageView;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.security.AccessController;
import java.util.Base64;

public class ProfileActivity extends AppCompatActivity {

    private UserViewModel userViewModel;
    Tampopo app;
    private String changeIconUrl;
    private boolean iconFlag;
    ShapeableImageView iconView;

    private ActivityResultLauncher<String[]> launcher = registerForActivityResult(new ActivityResultContracts.OpenDocument(), new ActivityResultCallback<Uri>() {
        @Override
        public void onActivityResult(Uri uri) {
            if(uri == null){
                iconFlag = false;
                return;
            }
            ShapeableImageView changeIconButton = findViewById(R.id.changeIcon);
            changeIconButton.setImageURI(uri);
            try {
                InputStream inputStream = getApplicationContext().getContentResolver().openInputStream(uri);
                Bitmap bitmap = BitmapFactory.decodeStream(new BufferedInputStream(inputStream));
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
                byte[] byteArray = stream.toByteArray();
                changeIconUrl = Base64.getEncoder().encodeToString(byteArray);
                iconFlag = true;
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
    });
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_profile);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        // ViewModel初期化
        userViewModel = new ViewModelProvider(this).get(UserViewModel.class);

        app = (Tampopo) getApplication();
        String uid = app.getUserId();

        ShapeableImageView iconView = findViewById(R.id.myicon);
        ShapeableImageView changeIconView = findViewById(R.id.changeIcon);



        //プロフィール編集画面から設定画面への遷移
        ImageButton buttonReturn = (ImageButton) findViewById(R.id.buttonReturn);
        buttonReturn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Intent intent = new Intent(ProfileActivity.this, SettingActivity.class);
                startActivity(intent);
            }
        });


        //もともとのidとニックネームとアイコンを表示
        userViewModel.getIconAsync(uid);
        userViewModel.getIcon().observe(this, new Observer<String>() {
            @Override
            public void onChanged(String iconUrl) {
                Glide.with(ProfileActivity.this).load(iconUrl).into(iconView);
            }
        });

        EditText nicknameInput = findViewById(R.id.nicknamebutton);
        nicknameInput.setText(((Tampopo) ProfileActivity.this.getApplication()).getNickname());

        EditText useridInput = findViewById(R.id.idbutton);
        useridInput.setText(((Tampopo) ProfileActivity.this.getApplication()).getUserId());


        //IDを変更できないようにする
        useridInput.setEnabled(false);

        //アイコンを押したときの変更
        iconView.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v) {
                launcher.launch(new String[] {"image/*"});
            }

        });

        //決定ボタン
        Button dicisionbutton = findViewById(R.id.dicisionbutton);

        //決定ボタンを押したときにidとニックネームとアイコンを保存
        dicisionbutton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {


                EditText usernicknameInput = findViewById(R.id.nicknamebutton);
                String usernickname = usernicknameInput.getText().toString();

                EditText useridInput = findViewById(R.id.idbutton);
                String userid = useridInput.getText().toString();

                // Application（Tampopo）に保存

                app.setNickname(usernickname);
                app.setUserId(userid);

                userViewModel.updateName(app.getUserId(), usernickname, app.getToken());
                if(iconFlag){
                    Bitmap iconBitmap = ((BitmapDrawable) changeIconView.getDrawable()).getBitmap();
                    userViewModel.updateIcon(app.getUserId(),changeIconUrl,app.getToken());
                    app.setIcon(changeIconUrl);
                }

                // 設定画面に戻る
                Intent intent = new Intent(ProfileActivity.this, SettingActivity.class);
                startActivity(intent);
            }
        });


    }

    @Override
    protected void onStart() {
        super.onStart();

        //もともとのidとニックネームを表示
        EditText nicknameInput = findViewById(R.id.nicknamebutton);
        nicknameInput.setText(((Tampopo) ProfileActivity.this.getApplication()).getNickname());

        EditText useridInput = findViewById(R.id.idbutton);
        useridInput.setText(((Tampopo) ProfileActivity.this.getApplication()).getUserId());

    }


}
