package com.pan_american.android.ui.group_management.group_info

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import com.pan_american.android.OASystem
import com.pan_american.android.R
import com.pan_american.android.base.BaseFragment
import com.pan_american.android.base.CardAdapter
import com.pan_american.android.base.CustomAlertDialog
import com.pan_american.android.data.model.common.entity.RequestCodeBean
import com.pan_american.android.data.model.group_management.group_info.entity.GroupCustomerInfo
import com.pan_american.android.databinding.FragmentGroupCustomerListBinding
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class GroupCustomerListFragment : BaseFragment<FragmentGroupCustomerListBinding>() {

    private lateinit var adapter: CardAdapter<GroupCustomerInfo>

    override fun getViewBinding(
        inflater: LayoutInflater, container: ViewGroup?, bundle: Bundle?
    ) = FragmentGroupCustomerListBinding.inflate(layoutInflater, container, false)

    override fun onStart() {
        super.onStart()

        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }

        initViews()
        initEvents()
    }

    override fun onStop() {
        super.onStop()

        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
    }

    override fun initViews() {

        initList(OASystem.groupCustomerList)

        if (!OASystem.authorization(OASystem.GROUP_CLIENT_LIST, OASystem.EDIT)) {
            binding.apply {
                reset.visibility = View.GONE
            }
        }

        if (!OASystem.authorization(OASystem.GROUP_CLIENT_LIST, OASystem.ADD)) {
            binding.apply {
                add.visibility = View.GONE
                scan.visibility = View.GONE
            }
        }
    }

    override fun initEvents() {

        binding.add.setOnClickListener {
            val groupCustomerDetailFragment = GroupCustomerDetailFragment()
            val bundle = Bundle()

            bundle.putInt("position", -1)
            bundle.putBoolean("from_list", false)

            groupCustomerDetailFragment.arguments = bundle

            parentFragmentManager.beginTransaction().setCustomAnimations(
                R.anim.slide_right_in,
                R.anim.slide_left_out,
                R.anim.slide_left_in,
                R.anim.slide_right_out
            ).addToBackStack(null)
                .replace(R.id.add_group_info_container, groupCustomerDetailFragment).commit()
        }

        binding.scan.setOnClickListener {
            EventBus.getDefault().post(RequestCodeBean(OASystem.CAMERA_REQUEST_CODE))
        }

        binding.reset.setOnClickListener {

            if (OASystem.groupCustomerList.size == 0) {
                return@setOnClickListener
            }

            CustomAlertDialog.Builder(OASystem.context).apply {
                setTitle(resources.getString(R.string.alert))
                setMessage(resources.getString(R.string.client_list_reset_alert))
                setNegativeButtonAndListener(resources.getString(R.string.cancel)) { dialog, _ ->
                    dialog.dismiss()
                }
                setPositiveButtonAndListener(resources.getString(R.string.confirm)) { _, _ ->
                    OASystem.groupCustomerList.clear()
                    initList(OASystem.groupCustomerList)
                }
            }.show()
        }

        binding.nextPage.setOnClickListener {

            for ((i, item) in OASystem.groupCustomerList.withIndex()) {
                if (item.companyFullName == resources.getString(R.string.no_info) || item.companyFullName.isBlank()) {
                    showMessage(String.format(resources.getString(R.string.client_company_hint), i + 1))
                    return@setOnClickListener
                }

                if (item.job.isBlank()) {
                    showMessage(String.format(resources.getString(R.string.client_job_hint), i + 1))
                    return@setOnClickListener
                }
            }

            parentFragmentManager.beginTransaction().setCustomAnimations(
                R.anim.slide_right_in,
                R.anim.slide_left_out,
                R.anim.slide_left_in,
                R.anim.slide_right_out
            ).addToBackStack(null)
                .replace(R.id.add_group_info_container, GroupInfoRequireFragment()).commit()
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun initGroupCustomerList(list: ArrayList<GroupCustomerInfo>) {

        initList(list)
    }

    private fun initList(list: ArrayList<GroupCustomerInfo>) {
        adapter = CardAdapter.Builder<GroupCustomerInfo>().apply {
            setData(list)
            setLayoutId(R.layout.item_group_customer_list)
            setCanDelete(OASystem.authorization(OASystem.GROUP_CLIENT_LIST, OASystem.DELETE))
            addBindView { itemView, data ->
                itemView.findViewById<TextView>(R.id.customer_name).text = String.format(
                    resources.getString(R.string.with_space_format), data.lastName, data.firstName
                )

                when (data.sex) {
                    0 -> {
                        itemView.findViewById<TextView>(R.id.customer_gender).text =
                            resources.getString(R.string.male)
                    }

                    1 -> {
                        itemView.findViewById<TextView>(R.id.customer_gender).text =
                            resources.getString(R.string.female)
                    }

                    else -> {
                        itemView.findViewById<TextView>(R.id.customer_gender).text =
                            resources.getString(R.string.no_info)
                    }
                }


                itemView.findViewById<TextView>(R.id.customer_unit).apply {
                    text = data.companyFullName.ifBlank {
                        resources.getString(R.string.no_info)
                    }
                }

                itemView.findViewById<TextView>(R.id.customer_job).apply {
                    text = data.job.ifBlank {
                        resources.getString(R.string.no_info)
                    }
                }

                for (item in OASystem.berthType) {
                    if (item.id == data.shippingSpaceTypeId) {
                        itemView.findViewById<TextView>(R.id.berth_name).text = item.name
                    }
                }
            }
        }.create()

        val layoutManager = LinearLayoutManager(OASystem.context)

        binding.customerList.layoutManager = layoutManager

        binding.customerList.adapter = adapter

        adapter.onRecyclerViewItemClick =
            object : CardAdapter.OnRecyclerViewItemClick<GroupCustomerInfo> {
                override fun onItemClick(position: Int) {

                    val groupCustomerDetailFragment = GroupCustomerDetailFragment()
                    val bundle = Bundle()

                    bundle.putInt("position", position)
                    bundle.putBoolean("from_list", true)

                    groupCustomerDetailFragment.arguments = bundle

                    parentFragmentManager.beginTransaction().setCustomAnimations(
                        R.anim.slide_right_in,
                        R.anim.slide_left_out,
                        R.anim.slide_left_in,
                        R.anim.slide_right_out
                    ).addToBackStack(null)
                        .replace(R.id.add_group_info_container, groupCustomerDetailFragment)
                        .commit()
                }

                override fun onItemDelete(position: Int) {
                    CustomAlertDialog.Builder(OASystem.context).apply {
                        setTitle(resources.getString(R.string.alert))
                        setMessage(
                            String.format(
                                resources.getString(R.string.delete_alert_text),
                                OASystem.groupCustomerList[position].lastName + OASystem.groupCustomerList[position].firstName
                            )
                        )
                        setNegativeButtonAndListener(resources.getString(R.string.cancel)) { dialog, _ ->
                            dialog.dismiss()
                        }
                        setPositiveButtonAndListener(resources.getString(R.string.confirm)) { _, _ ->
                            OASystem.groupCustomerList.removeAt(position)

                            adapter.notifyItemRemoved(position)
                            adapter.notifyItemRangeChanged(
                                position, OASystem.groupCustomerList.size
                            )
                        }
                        setCancelable(false)
                    }.show()
                }
            }
    }
}