package com.rdiot.yx485.fragment;

import static android.view.View.GONE;
import static android.view.View.VISIBLE;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import com.google.android.material.tabs.TabLayout;
import com.rdiot.yx485.adapter.ExampleListAdapter;
import com.rdiot.yx485.base.BaseFragment;
import com.rdiot.yx485.bean.HomeBase;
import com.rdiot.yx485.bean.ModelRepleBean;
import com.rdiot.yx485.databinding.FragmentExampleBinding;
import com.rdiot.yx485.http.Url;
import com.rdiot.yx485.main.MainActivityTab;
import com.rdiot.yx485.main.MainViewModel;
import com.rdiot.yx485.util.LocalCache;
import com.rdiot.yx485.webview.WebViewActivity;
import com.zcolin.gui.zrecyclerview.BaseRecyclerAdapter;
import com.zcolin.gui.zrecyclerview.ZRecyclerView;

import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link SceneFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class SceneFragment extends BaseFragment implements ZRecyclerView.PullLoadMoreListener {
    private FragmentExampleBinding mBinding;
    private MainViewModel mViewModel;
    private int position = 0, mPage = 1;
    private HomeBase mHomeBase;
    private boolean isFragmentAlive = false;
    private String mTypeList = "";

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

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment ExampleFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static SceneFragment newInstance(String param1, String param2) {
        SceneFragment fragment = new SceneFragment();
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        isFragmentAlive = true;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mBinding = FragmentExampleBinding.inflate(inflater, container, false);
        View view = mBinding.getRoot();

        initRecyclerView();
        initViews();
        initData();
        return view;
    }

    private void initData() {
        mViewModel = new ViewModelProvider(requireActivity()).get(MainViewModel.class);
        mViewModel.getSelectedHome().observe(getViewLifecycleOwner(), home -> {
            mHomeBase = home;
            onRefresh();
        });
        // 观察场景列表数据
        mViewModel.getSceneList().observe(getViewLifecycleOwner(), sceneList -> {
            if (!isFragmentAlive || mBinding == null) return;

            if (sceneList != null) {
                notifyData(sceneList, mPage == 1);
                mBinding.recyclerExample.setPullLoadMoreCompleted();
                mBinding.recyclerExample.setNoMore(true);
            }
        });
    }

    private void initRecyclerView() {
        mBinding.recyclerExample.setOnPullLoadMoreListener(this);
        mBinding.recyclerExample.setIsShowNoMore(false);
        mBinding.recyclerExample.setIsLoadMoreEnabled(false);

        // 延迟执行刷新，确保Fragment完全初始化
        mBinding.recyclerExample.post(() -> {
            if (isFragmentAlive && mBinding != null) {
                mBinding.recyclerExample.refreshWithPull();
            }
        });
    }

    private void initViews() {
        // 初始化空状态视图
        mBinding.emptyStateLayout.tvTitle.setText("添加场景");
        mBinding.emptyStateLayout.tvSubtitle.setText("还没有场景，快去添加吧");
        mBinding.emptyStateLayout.btnAddDevice.setOnClickListener(v ->
                WebViewActivity.newIntent(requireContext(), Url.BASE_URL2 + "/#/scene/:" + mHomeBase.getId(), null)
        );

        mBinding.recyclerExample.setOnItemClickListener((BaseRecyclerAdapter.OnItemClickListener<ModelRepleBean.DataBean>) (covertView, position, data) -> {
            // Handle item click
        });

        mBinding.jiating.setOnClickListener(view1 -> {
            if (getActivity() instanceof MainActivityTab) {
                ((MainActivityTab) getActivity()).showHomeListWindow(mBinding.jiating);
            }
        });

        mBinding.tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                position = tab.getPosition();
                loadData();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        isFragmentAlive = false;
    }

    /**
     * 获取场景
     */
    private void getchangjing(String typeList) {
        mTypeList = typeList;
        if (!isFragmentAlive || mBinding == null) return;
        mViewModel.loadSceneList(mHomeBase.getId(), typeList);
    }

    /**
     * 设置数据Adapter
     */
    @SuppressLint("NotifyDataSetChanged")
    public void notifyData(List<ModelRepleBean.DataBean> list, boolean isClear) {
        if (list == null || list.isEmpty()) {
            mBinding.recyclerExample.setVisibility(GONE);
            mBinding.emptyStateLayout.getRoot().setVisibility(VISIBLE);
            return;
        }

        mBinding.recyclerExample.setVisibility(VISIBLE);
        mBinding.emptyStateLayout.getRoot().setVisibility(GONE);

        ExampleListAdapter recyclerAdapter = new ExampleListAdapter(getContext(), id -> mViewModel.doScene(id), "oneKey".equals(mTypeList));
        recyclerAdapter.addDatas(list);
        mBinding.recyclerExample.setAdapter(recyclerAdapter);
        recyclerAdapter.notifyDataSetChanged();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (isResumed() && isFragmentAlive && mBinding != null) {
            onRefresh();
        }
    }

    @Override
    public void onRefresh() {
        if (!isFragmentAlive || mBinding == null) {
            return;
        }

        if (mHomeBase == null) {
            mHomeBase = LocalCache.getDefaultHome();
            if (mHomeBase == null) {
                return;
            }
        }

        mBinding.jiating.setText(mHomeBase.getName());
        mPage = 1;
        loadData();
        mBinding.recyclerExample.setNoMore(false);
    }

    private void loadData() {
        if (position == 0) {
            getchangjing("automation");
        } else if (position == 1) {
            getchangjing("oneKey");
        }
    }

    @Override
    public void onLoadMore() {
        if (!isFragmentAlive || mBinding == null) return;

        mPage = mPage + 1;
        loadData();
    }

    @Override
    public void onDestroyView() {
        if (mBinding != null) {
            mBinding.recyclerExample.setOnPullLoadMoreListener(null);
            mBinding.tabLayout.clearOnTabSelectedListeners();
        }
        super.onDestroyView();
        mBinding = null;
    }
}