package co.pixelbeard.theanfieldwrap.profile;


import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.app.NotificationManagerCompat;

import butterknife.BindView;
import butterknife.ButterKnife;
import co.pixelbeard.theanfieldwrap.R;
import co.pixelbeard.theanfieldwrap.data.source.DataRepository;
import co.pixelbeard.theanfieldwrap.data.source.local.LocalRepository;
import co.pixelbeard.theanfieldwrap.data.source.remote.RemoteRepository;
import co.pixelbeard.theanfieldwrap.home.HomeFragmentListener;
import co.pixelbeard.theanfieldwrap.playerService.MediaPlayerInterface;
import co.pixelbeard.theanfieldwrap.playerService.PodcastStorageUtil;
import co.pixelbeard.theanfieldwrap.utils.AnimUtils;
import co.pixelbeard.theanfieldwrap.utils.BaseFragment;
import co.pixelbeard.theanfieldwrap.utils.ConnectionUtils;
import co.pixelbeard.theanfieldwrap.utils.FontUtils;
import co.pixelbeard.theanfieldwrap.utils.PrefKey;
import co.pixelbeard.theanfieldwrap.utils.PrefUtils;
import co.pixelbeard.theanfieldwrap.utils.ScreenUtils;
import co.pixelbeard.theanfieldwrap.utils.SubscriptionUtils;
import co.pixelbeard.theanfieldwrap.utils.TawController;
import io.realm.Realm;

public class ProfileFragment extends BaseFragment implements ProfileContract.View {

    private static final String TAG = ProfileFragment.class.getSimpleName();

    @BindView(R.id.ll_need_help)
    LinearLayout llNeedHelp;
    @BindView(R.id.ll_device_management)
    LinearLayout llManageDevices;
    @BindView(R.id.ll_account_details)
    LinearLayout llAccountDetails;
    @BindView(R.id.ll_downloads)
    LinearLayout llDownloads;
    @BindView(R.id.ll_settings)
    LinearLayout llSettings;
    @BindView(R.id.ll_purchases)
    LinearLayout llPurchases;
    @BindView(R.id.ll_subscription_level_container)
    LinearLayout llSubscriptionLevelContainer;

    @BindView(R.id.rl_profile_header)
    RelativeLayout rlProfileHeader;

    @BindView(R.id.txt_need_help)
    TextView txtNeedHelp;
    @BindView(R.id.txt_device_management)
    TextView txtManageDevices;
    @BindView(R.id.txt_account_details)
    TextView txtAccountDetails;
    @BindView(R.id.txt_downloads)
    TextView txtDownloads;
    @BindView(R.id.txt_settings)
    TextView txtSettings;
    @BindView(R.id.txt_purchases)
    TextView txtPurchases;
    @BindView(R.id.txt_subscription_level)
    TextView txtSubscriptionLevel;

    @BindView(R.id.txt_user_full_name)
    TextView txtFullName;
    @BindView(R.id.txt_profile_body)
    TextView txtProfileBody;

    @BindView(R.id.btn_create_account)
    Button btnCreateAccount;
    @BindView(R.id.btn_how_to_subscribe)
    Button btnHowToSubscribe;

    @BindView(R.id.spacer_view)
    View spacerView;

    @BindView(R.id.cl_notifications_disabled)
    ConstraintLayout clNotifDisabled;
    @BindView(R.id.txt_notif_disabled_title)
    TextView txtNotifDisabledTitle;
    @BindView(R.id.txt_notif_disabled_body)
    TextView txtNotifDisabledBody;

    private Context mContext;
    private HomeFragmentListener mListener;
    private MediaPlayerInterface mediaPlayerInterface;

    private ProfileContract.Presenter mPresenter;

    public ProfileFragment() {
        // Required empty public constructor
    }

    public static ProfileFragment newInstance() {
        ProfileFragment fragment = new ProfileFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

        mContext = context;
        mListener = (HomeFragmentListener) context;
        mediaPlayerInterface = (MediaPlayerInterface) context;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {

        }

        new ProfilePresenter(this, new DataRepository(new LocalRepository(Realm.getDefaultInstance()), new RemoteRepository()));
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_profile, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        setTextViewFonts();
        setButtonFonts();

        setOnClickListeners();
        setButtonClickListeners();
    }

    @Override
    public void onResume() {
        super.onResume();
        TawController.setCurrentPage(TAG);

        if (!PrefUtils.getInstance().getBooleanPref(PrefKey.IS_GUEST_ACCOUNT)) {
            new Handler().postDelayed(() -> mPresenter.subscribe(), 600);
        }

        if (isAdded() && !isDetached()) {
            setData();
            checkNotifDisabled();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    private void setTextViewFonts() {
        txtManageDevices.setTypeface(FontUtils.getInstance().getDinAlternateBold());
        txtNeedHelp.setTypeface(FontUtils.getInstance().getDinAlternateBold());
        txtAccountDetails.setTypeface(FontUtils.getInstance().getDinAlternateBold());
        txtDownloads.setTypeface(FontUtils.getInstance().getDinAlternateBold());
        txtSettings.setTypeface(FontUtils.getInstance().getDinAlternateBold());
        txtPurchases.setTypeface(FontUtils.getInstance().getDinAlternateBold());

        txtFullName.setTypeface(FontUtils.getInstance().getDinAlternateBold());

        txtProfileBody.setTypeface(FontUtils.getInstance().getDinAlternateBold());
        txtSubscriptionLevel.setTypeface(FontUtils.getInstance().getDinAlternateBold());

        txtNotifDisabledTitle.setTypeface(FontUtils.getInstance().getDinAlternateBold());
        txtNotifDisabledBody.setTypeface(FontUtils.getInstance().getDinAlternateBold());
    }

    private void setButtonFonts() {
        btnCreateAccount.setTypeface(FontUtils.getInstance().getDinAlternateBold());
        btnHowToSubscribe.setTypeface(FontUtils.getInstance().getDinAlternateBold());
    }

    private void setOnClickListeners() {

        llManageDevices.setOnClickListener(v -> {
            mListener.startDevicesActivity();
        });

        llNeedHelp.setOnClickListener(v -> {
            String url = "https://taw.helpscoutdocs.com/";
            Intent i = new Intent(Intent.ACTION_VIEW);
            i.setData(Uri.parse(url));
            startActivity(i);
        });

        llAccountDetails.setOnClickListener(v -> {
            mListener.setAccountDetailsFrag();
        });

        llDownloads.setOnClickListener(v -> {
            mListener.setDownloadsFrag();
        });

        llSettings.setOnClickListener(v -> {
            mListener.setSettingsFrag();
        });

        llPurchases.setOnClickListener(v -> {
            mListener.setWalletFrag();
        });

        clNotifDisabled.setOnClickListener(v -> {
            Intent intent = new Intent();
            intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");

            //for Android 5-7
            intent.putExtra("app_package", mContext.getPackageName());
            intent.putExtra("app_uid", mContext.getApplicationInfo().uid);

            // for Android 8 and above
            intent.putExtra("android.provider.extra.APP_PACKAGE", mContext.getPackageName());

            startActivity(intent);
        });
    }

    private void setButtonClickListeners() {
        btnCreateAccount.setOnClickListener(v -> {
            mListener.startSignUpActivityAsGuest();
        });

        btnHowToSubscribe.setOnClickListener(v -> {
            mListener.setHowToSubscribeFrag(true);
        });
    }

    private void setData() {
        if (PrefUtils.getInstance().getBooleanPref(PrefKey.IS_GUEST_ACCOUNT)) {
            setGuestAccountUI();
        } else if (!SubscriptionUtils.getSubscriptionLevelAsString(PrefUtils.getInstance().getSubs(), mContext).equals("")) {
            setHasSubsUI();

        } else {
            setNoSubsUI();
        }
    }

    private void checkNotifDisabled() {

        if (isAdded()) {
            if (NotificationManagerCompat.from(mContext).areNotificationsEnabled()) {
                spacerView.setVisibility(View.VISIBLE);
                clNotifDisabled.setVisibility(View.GONE);
            } else {
                spacerView.setVisibility(View.GONE);
                clNotifDisabled.setVisibility(View.VISIBLE);
            }
        }
    }

    private void setGuestAccountUI() {
        btnCreateAccount.setVisibility(View.VISIBLE);
        btnHowToSubscribe.setVisibility(View.GONE);
        txtProfileBody.setText(getString(R.string.profile_guest_user_body));
        txtFullName.setText(getString(R.string.guest_account));

        llAccountDetails.setVisibility(View.GONE);
        llDownloads.setVisibility(View.GONE);
        llPurchases.setVisibility(View.GONE);
        llManageDevices.setVisibility(View.GONE);
    }

    private void setNoSubsUI() {
        btnCreateAccount.setVisibility(View.GONE);
        btnHowToSubscribe.setVisibility(View.VISIBLE);
        txtProfileBody.setText(getString(R.string.profile_full_user_not_subscribed_body));
        txtFullName.setText(String.format("%s %s", PrefUtils.getInstance().getStringPref(PrefKey.FIRSTNAME), PrefUtils.getInstance().getStringPref(PrefKey.LASTNAME)));
        llSubscriptionLevelContainer.setVisibility(View.GONE);

        txtProfileBody.setVisibility(View.VISIBLE);


        llAccountDetails.setVisibility(View.VISIBLE);
        llDownloads.setVisibility(View.VISIBLE);
        llSettings.setVisibility(View.VISIBLE);
        llPurchases.setVisibility(View.VISIBLE);

        rlProfileHeader.getLayoutParams().height = (int) ScreenUtils.dpToPx(330, mContext);


        llManageDevices.setVisibility(View.VISIBLE);

    }

    private void setHasSubsUI() {
        btnCreateAccount.setVisibility(View.GONE);
        btnHowToSubscribe.setVisibility(View.GONE);
        txtProfileBody.setVisibility(View.GONE);
        txtFullName.setText(String.format("%s %s", PrefUtils.getInstance().getStringPref(PrefKey.FIRSTNAME), PrefUtils.getInstance().getStringPref(PrefKey.LASTNAME)));

        llSubscriptionLevelContainer.setVisibility(View.VISIBLE);
        txtSubscriptionLevel.setText(SubscriptionUtils.getSubscriptionLevelAsString(PrefUtils.getInstance().getSubs(), mContext));

        rlProfileHeader.getLayoutParams().height = (int) ScreenUtils.dpToPx(205, mContext);

        llAccountDetails.setVisibility(View.VISIBLE);
        llDownloads.setVisibility(View.VISIBLE);
        llSettings.setVisibility(View.VISIBLE);
        llPurchases.setVisibility(View.VISIBLE);
        llManageDevices.setVisibility(View.VISIBLE);
    }

    @Override
    public void setPresenter(ProfileContract.Presenter presenter) {
        if (presenter != null) {
            mPresenter = presenter;
        } else {
            throw new RuntimeException("Presenter is null");
        }
    }

    @Override
    public void goBack() {
        mListener.goBack();
    }

    @Override
    public void showLoader(String text) {
        if (isAdded()) {
            llSubscriptionLevelContainer.setVisibility(View.VISIBLE);
            txtSubscriptionLevel.setVisibility(View.VISIBLE);
            txtSubscriptionLevel.setText(getString(R.string.checking_subs));

            llSubscriptionLevelContainer.startAnimation(AnimUtils.getPulsateFade(mContext));
        }
    }

    @Override
    public void hideLoader() {
        if (isAdded())
            llSubscriptionLevelContainer.clearAnimation();
    }

    @Override
    public void onUnknownError(String error) {
        if (mListener != null && isAdded()) {
            mListener.showSingleButtonDialog(getString(R.string.error), error, null);
        }
    }

    @Override
    public void onTimeout() {
        if (mListener != null && isAdded()) {
            mListener.showSingleButtonDialog(getString(R.string.timeout_title), getString(R.string.timeout_body), null);
        }
    }

    @Override
    public void onNetworkError() {
        if (mListener != null && isAdded()) {
            mListener.showSingleButtonDialog(getString(R.string.network_error_title), getString(R.string.network_error_body), null);
        }
    }

    @Override
    public void onConnectionError() {
        if (mListener != null && isAdded()) {
            mListener.showNoInternetHeader();
        }
    }

    @Override
    public void logoutUser() {
        mPresenter.clearUserData(mContext);
        if (mediaPlayerInterface != null && mediaPlayerInterface.isPlaying()) {
            mediaPlayerInterface.stop();
        }
        PodcastStorageUtil.getInstance().clearStoredPodcast();
        mListener.startWalkThroughActivity();
    }

    @Override
    public boolean checkConnection() {
        return ConnectionUtils.userHasConnection(mContext);
    }

    @Override
    public void updateSubsState() {
        if (isAdded()) {
            setData();
        }
    }
}
