package com.rdiot.yx485.home;

import static android.app.Activity.RESULT_OK;
import static android.view.View.GONE;
import static android.view.View.VISIBLE;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.rdiot.yx485.InviteActivity;
import com.rdiot.yx485.adapter.HomePersonAdapter;
import com.rdiot.yx485.base.BaseFragment;
import com.rdiot.yx485.bean.HomeResultBean;
import com.rdiot.yx485.databinding.FragmentHomeBinding;
import com.rdiot.yx485.room.RoomManageActivity;
import com.rdiot.yx485.util.DialogUtils;


public class HomeFragment extends BaseFragment {
    HomeResultBean.HomeInfo mHomeInfo;
    private HomeViewModel mViewModel;
    private FragmentHomeBinding mBinding;
    private boolean mChanged = false;

    private ActivityResultLauncher<Intent> mResultLauncher;
    private ActivityResultLauncher<Intent> mResultLauncher2;

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

    public static HomeFragment newInstance(HomeResultBean.HomeInfo listBean) {
        HomeFragment fragment = new HomeFragment();
        Bundle args = new Bundle();
        args.putParcelable("listBean", listBean);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        mBinding = FragmentHomeBinding.inflate(inflater, container, false);

        // Get the passed argument
        if (getArguments() != null) {
            mHomeInfo = getArguments().getParcelable("listBean");
        }

        initView();
        initData();
        refreshView();
        return mBinding.getRoot();
    }

    private void initView() {
        mBinding.cyrecyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
        mBinding.fankui.setOnClickListener(v -> {
            Intent intent = RoomManageActivity.newIntent(requireContext(), mHomeInfo.record_id);
            intent.putExtra("source", "roomManage");
            mResultLauncher2.launch(intent);
        });
        mBinding.homename.setOnClickListener(v -> {
            DialogUtils.showInputDialog(requireActivity(), "修改家庭名称", mHomeInfo.name, "请输入家庭名称", name -> {
                mChanged = true;
                mHomeInfo.name = name;
                refreshView();
            });
        });
        mBinding.btnSave.setOnClickListener(v -> mViewModel.updateHomeInfo(mHomeInfo));
        mBinding.btnDelete.setOnClickListener(v -> {
            DialogUtils.showAlertDialog(requireContext(), "删除家庭", "确定要删除改家庭吗？", (dialog, which) -> {
                if (mHomeInfo != null && !TextUtils.isEmpty(mHomeInfo.record_id)) {
                    mViewModel.deleteHome(mHomeInfo.record_id);
                }
            }, (dialog, which) -> {
            });
        });
        mResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            if (result.getResultCode() == RESULT_OK && result.getData() != null) {
                Bundle bundle = result.getData().getBundleExtra("bundle");
                if (bundle == null) {
                    return;
                }

                String[] arr = bundle.getStringArray("address");
                if (arr == null || arr.length != 4) {
                    return;
                }

                mHomeInfo.province = arr[0];
                mHomeInfo.city = arr[1];
                mHomeInfo.district = arr[2];
                mHomeInfo.address = arr[3];
                mChanged = true;
                refreshView();
            }
        });
        mBinding.homeadress.setOnClickListener(v -> mResultLauncher.launch(HomeCreateActivity.updateAddress(requireContext(), mHomeInfo)));
        mResultLauncher2 = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            if (result.getResultCode() == RESULT_OK && result.getData() != null) {
                boolean changed = result.getData().getBooleanExtra("changed", false);
                if (changed) {
                    mViewModel.loadHomeList(false);
                }
            }
        });
    }

    private void refreshView() {
        mBinding.btnSave.setVisibility(mChanged ? VISIBLE : GONE);
        mBinding.btnDelete.setVisibility(mChanged ? GONE : VISIBLE);

        if (mHomeInfo == null) {
            return;
        }

        mBinding.homename.setText(mHomeInfo.name == null ? "" : mHomeInfo.name);
        mBinding.homeadress.setText(String.format("%s%s%s%s", mHomeInfo.province, mHomeInfo.city, mHomeInfo.district, mHomeInfo.address));
    }

    private void initData() {
        mViewModel = new ViewModelProvider(requireActivity()).get(HomeViewModel.class);
        mViewModel.getUpdateState().observe(getViewLifecycleOwner(), success -> {
            if (success) {
                mChanged = false;
                refreshView();
            }
        });

        if (mHomeInfo == null) {
            return;
        }

        mBinding.fangjiannum.setText(String.format("房间 %s  | ", mHomeInfo.room == null ? 0 : mHomeInfo.room.size()));
        mBinding.shebeinum.setText(String.format("设备 %s  | ", mHomeInfo.devices == null ? 0 : mHomeInfo.devices.size()));
        mBinding.chengyuannum.setText(String.format("成员 %s ", mHomeInfo.member == null ? 0 : mHomeInfo.member.size()));
        mBinding.homeroom.setText(String.format("%s个房间", mHomeInfo.room == null ? 0 : mHomeInfo.room.size()));

        if (mHomeInfo.member != null) {
            HomePersonAdapter homeAdapter = new HomePersonAdapter(mHomeInfo.member, new HomePersonAdapter.OnMemberClickListener() {
                @Override
                public void onMemberClick(HomeResultBean.HomeInfo.MemberBean member) {
                    mResultLauncher2.launch(HomeCreateActivity.showMemberInfo(requireContext(), member, mHomeInfo.admin_id));
                }

                @Override
                public void onAddMemberClick() {
                    mResultLauncher2.launch(InviteActivity.newIntent(requireContext(), mHomeInfo));
                }
            }, mHomeInfo.admin_id);
            mBinding.cyrecyclerView.setAdapter(homeAdapter);
        }
    }
}