package com.kbs.kbsintranett;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;

import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.tasks.Task;

public class LoginFragment extends Fragment {

    private static final String TAG = "LoginFragment";
    private GoogleSignInClient mGoogleSignInClient;
    private TextView statusText;
    private SignInButton signInButton;
    private View reviewerLoginArea; // Nytt

    private final ActivityResultLauncher<Intent> signInLauncher = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            result -> {
                Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(result.getData());
                handleGoogleResult(task);
            }
    );

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_login, container, false);
        statusText = view.findViewById(R.id.status_text);
        signInButton = view.findViewById(R.id.sign_in_button);
        signInButton.setSize(SignInButton.SIZE_WIDE);

        // Finn reviewer-knappen (vi legger den til i XML-en under)
        reviewerLoginArea = view.findViewById(R.id.reviewer_login_text);

        String clientId = MainActivity.GOOGLE_WEB_CLIENT_ID;
        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken(clientId)
                .requestEmail()
                .build();
        mGoogleSignInClient = GoogleSignIn.getClient(requireActivity(), gso);

        signInButton.setOnClickListener(v -> {
            statusText.setText("Starter Google innlogging...");
            Intent signInIntent = mGoogleSignInClient.getSignInIntent();
            signInLauncher.launch(signInIntent);
        });

        // Reviewer Bypass-logikk
        if (reviewerLoginArea != null) {
            reviewerLoginArea.setOnClickListener(v -> {
                performReviewerLogin();
            });
        }

        return view;
    }

    private void performReviewerLogin() {
        statusText.setText("Kobler til som gjest...");
        signInButton.setEnabled(false);

        // Vi sender den hemmelige nøkkelen i stedet for et ekte Google-token
        AuthRepository.loginToWordPress(
                "KBS_REVIEW_BYPASS_2026_SECRET",
                "Google Reviewer",
                "google-test@kbs.no",
                null,
                new AuthRepository.AuthCallback() {
                    @Override
                    public void onSuccess(String role) {
                        if (isAdded()) {
                            NavController navController = Navigation.findNavController(requireActivity(), R.id.nav_host_fragment);
                            navController.navigate(R.id.action_login_to_home);
                        }
                    }

                    @Override
                    public void onError(String message) {
                        if (isAdded()) {
                            statusText.setText("Feil ved tilkobling: " + message);
                            signInButton.setEnabled(true);
                        }
                    }
                }
        );
    }

    private void handleGoogleResult(Task<GoogleSignInAccount> completedTask) {
        try {
            GoogleSignInAccount account = completedTask.getResult(ApiException.class);
            statusText.setText("Google OK. Kobler til KBS Intranett...");
            signInButton.setEnabled(false);

            String photoUrl = (account.getPhotoUrl() != null) ? account.getPhotoUrl().toString() : null;

            AuthRepository.loginToWordPress(
                    account.getIdToken(),
                    account.getDisplayName(),
                    account.getEmail(),
                    photoUrl,
                    new AuthRepository.AuthCallback() {
                        @Override
                        public void onSuccess(String role) {
                            if (isAdded()) {
                                NavController navController = Navigation.findNavController(requireActivity(), R.id.nav_host_fragment);
                                navController.navigate(R.id.action_login_to_home);
                            }
                        }

                        @Override
                        public void onError(String message) {
                            if (isAdded()) {
                                statusText.setText(message);
                                signInButton.setEnabled(true);
                            }
                        }
                    }
            );
        } catch (ApiException e) {
            Log.w(TAG, "signInResult:failed code=" + e.getStatusCode());
            String message = (e.getStatusCode() == 12500) ? "Konto ikke funnet." : "Google-feil: " + e.getStatusCode();
            statusText.setText(message);
        }
    }
}