package com.example.shorti;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.Body;
import retrofit2.http.POST;

public class RegAndAuth extends AppCompatActivity {

    Button authBtn;
    Button regBtn;
    EditText login;
    EditText password;
    SharedPreferences settings;

    interface RequestAuth {
        @POST("/api/Identity/signup")
        Call<ResponseSignUp> signUp(@Body RequestSignUp requestSignUp);

        @POST("/api/Identity/signin")
        Call<ResponseSignUp> signIn(@Body RequestSignIn requestSignIn);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_reg_and_auth);
        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;
        });

        authBtn = findViewById(R.id.authBtn);
        regBtn = findViewById(R.id.regBtn);
        login = findViewById(R.id.login);
        password = findViewById(R.id.password);

        Context context = (Context) this;

        settings = getSharedPreferences("user_data", MODE_PRIVATE);

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://212.109.198.242:5064")
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        RequestAuth requestAuth = retrofit.create(RequestAuth.class);

        authBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Toast.makeText(context, "Auth", Toast.LENGTH_SHORT).show();
                requestAuth.signIn(
                        new RequestSignIn(
                                login.getText().toString(),
                                password.getText().toString()
                        )
                ).enqueue(new Callback<ResponseSignUp>() {
                    @Override
                    public void onResponse(Call<ResponseSignUp> call, Response<ResponseSignUp> response) {
                        //Toast.makeText(context, "token: " + response.body().accessToken, Toast.LENGTH_SHORT).show();
                        setPrefs(
                                response.body().id,
                                response.body().userName,
                                response.body().accessToken,
                                response.body().refreshToken
                        );
                        goToMainFeed();
                    }

                    @Override
                    public void onFailure(Call<ResponseSignUp> call, Throwable t) {
                        Toast.makeText(context, "Ошибка авторизации", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });

        regBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Toast.makeText(context, "Reg", Toast.LENGTH_SHORT).show();
                requestAuth.signUp(
                        new RequestSignUp(
                                login.getText().toString(),
                                password.getText().toString(),
                                password.getText().toString()
                        )
                ).enqueue(new Callback<ResponseSignUp>() {
                    @Override
                    public void onResponse(Call<ResponseSignUp> call, Response<ResponseSignUp> response) {
                        //Toast.makeText(context, "token: " + response.body().accessToken, Toast.LENGTH_SHORT).show();
                        setPrefs(
                                response.body().id,
                                response.body().userName,
                                response.body().accessToken,
                                response.body().refreshToken
                        );
                        goToMainFeed();
                    }

                    @Override
                    public void onFailure(Call<ResponseSignUp> call, Throwable t) {
                        Toast.makeText(context, "Ошибка регистрации", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }

    private void setPrefs(String id, String userName, String accessToken, String refreshToken) {
        SharedPreferences.Editor editor = settings.edit();
        editor.putString("access_token", accessToken);
        editor.putString("refresh_token", refreshToken);
        editor.putString("user_name", userName);
        editor.putString("id", id);
        editor.apply();
    }

    private void goToMainFeed() {
        Intent intent = new Intent(this, MainFeed.class);
        startActivity(intent);
    }
}