package com.proyek.akhir.kodel.ui.user.dashboard

import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.proyek.akhir.kodel.R
import com.proyek.akhir.kodel.data.response.AnggotaItem
import com.proyek.akhir.kodel.data.response.BeritaItem
import com.proyek.akhir.kodel.data.response.UtangItem
import com.proyek.akhir.kodel.ui.user.dashboard.ajuanPinjaman.AjuanPinjamanActivity
import com.proyek.akhir.kodel.ui.user.dashboard.detailPenunggak.DetailPenunggakActivity
import com.proyek.akhir.kodel.ui.user.dashboard.history.HistoryActivity
import com.proyek.akhir.kodel.ui.user.dashboard.isiSaldo.IsiSaldoActivity
import com.proyek.akhir.kodel.ui.user.dashboard.tarikSaldo.TarikSaldoActivity
import kotlinx.android.synthetic.main.fragment_dashboard.*
import kotlinx.android.synthetic.main.fragment_dashboard.view.*
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.TimeUnit


class DashboardFragment : Fragment() {
    private val listPenunggak: MutableList<UtangItem> = mutableListOf()
    private val listBerita: MutableList<BeritaItem> = mutableListOf()

    private lateinit var dashboardViewModel: DashboardViewModel

    private lateinit var saldoUserTotal: String

    lateinit var nameUser: String
    lateinit var idAnggota: String
    lateinit var imgUser: String

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        dashboardViewModel =
            ViewModelProvider(this).get(DashboardViewModel::class.java)
        val root = inflater.inflate(R.layout.fragment_dashboard, container, false)

        root.viewDashboard.visibility = View.GONE

        root.dashboardLoading.visibility = View.VISIBLE

        root.lnrUtang.visibility = View.GONE
        root.txtNameHallo.visibility = View.GONE
        root.pengingatPenunggak.visibility = View.GONE

        root.isiSaldoDashboard.setOnClickListener {
            val intent = Intent(activity, IsiSaldoActivity::class.java)
            intent.putExtra("idAnggota", idAnggota)
            intent.putExtra("nameAnggota", nameUser)
            intent.putExtra("imgUser", imgUser)
            startActivity(intent)
        }

        root.tarikSaldoDashboard.setOnClickListener {
            var intent = Intent(activity, TarikSaldoActivity::class.java)
            intent.putExtra("saldoUser", saldoUserTotal)
            intent.putExtra("nameUser", nameUser)
            intent.putExtra("idAnggota", idAnggota)
            startActivity(intent)
        }

        root.historyBellButton.setOnClickListener {
            startActivity(Intent(activity, HistoryActivity::class.java))
        }

        root.detailPenunggak.setOnClickListener {
            startActivity(Intent(activity, DetailPenunggakActivity::class.java))
        }

        root.ajuanPinjamDashboard.setOnClickListener {
            val intent = Intent(activity, AjuanPinjamanActivity::class.java)
            intent.putExtra("nameUser", nameUser)
            startActivity(intent)
        }

        callAnggota()

        callUtang()

        callBerita()

        callPenunggak()

        return root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {

        view.rvBeritaKabarDashboard.setHasFixedSize(true)
        view.rvPenunggakBeranda.setHasFixedSize(true)

        view.rvBeritaKabarDashboard.layoutManager =
            LinearLayoutManager(activity, LinearLayoutManager.HORIZONTAL, false)

        view.rvPenunggakBeranda.layoutManager =
            LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false)

        view.rvBeritaKabarDashboard.adapter = BeritaDashboardAdapter(listBerita)

        view.rvPenunggakBeranda.adapter = PenunggakDashboardAdapter(listPenunggak)

        view.refreshDashboardUser.setOnRefreshListener {
            viewDashboard.visibility = View.GONE
            refreshDashboardUser.isRefreshing = true
            callAnggota()
            callUtang()
            callBerita()
            callPenunggak()
        }
    }

    private fun callAnggota() {
        dashboardViewModel = ViewModelProvider(this).get(DashboardViewModel::class.java)
        dashboardViewModel.setDataAnggota().observe(viewLifecycleOwner, Observer { item ->
            showData(item)
        })
    }

    private fun callUtang() {
        dashboardViewModel = ViewModelProvider(this).get(DashboardViewModel::class.java)
        dashboardViewModel.setDataUtang().observe(viewLifecycleOwner, Observer { utang ->
            if (utang[0].tglPinjam != null) {
                lnrUtang.visibility = View.VISIBLE
                showUtang(utang)
            } else {
                lnrUtang.visibility = View.GONE
            }
        })
    }

    private fun callBerita() {
        dashboardViewModel = ViewModelProvider(this).get(DashboardViewModel::class.java)
        dashboardViewModel.setDataBerita().observe(viewLifecycleOwner, Observer { berita ->
            if (berita != null) {
                listBerita.clear()
                for (i in 0 until berita.size) {
                    listBerita.add(berita[i])
                }
                viewDashboard.visibility = View.VISIBLE
                dashboardLoading.visibility = View.GONE
                refreshDashboardUser.isRefreshing = false
            } else {
                dashboardLoading.visibility = View.GONE
                lnrBeritaKabar.visibility = View.GONE
                rvBeritaKabarDashboard.visibility = View.GONE
                refreshDashboardUser.isRefreshing = false
                Toast.makeText(context, "Harap Refresh!", Toast.LENGTH_SHORT).show()
            }
        })
    }

    private fun callPenunggak() {
        dashboardViewModel = ViewModelProvider(this).get(DashboardViewModel::class.java)
        dashboardViewModel.setDataPenunggak().observe(viewLifecycleOwner, Observer { penunggak ->
            if (penunggak != null) {
                listPenunggak.clear()
                if (penunggak.size < 2) {
                    detailPenunggak.visibility = View.GONE
                } else {
                    detailPenunggak.visibility = View.VISIBLE
                }
                for (i in 0 until penunggak.size) {
                    listPenunggak.add(penunggak[i])
                }
            } else {
                lnrPenunggak.visibility = View.INVISIBLE
                rvPenunggakBeranda.visibility = View.INVISIBLE
            }
        })
    }

    private fun showUtang(utang: List<UtangItem>) {

        sisaUtang.text = getString(R.string.sisa_utang_value, utang[0].jlhUtang)

        if (utang[0].isMenunggak) {
            pengingatPenunggak.visibility = View.VISIBLE
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//                val current = LocalDateTime.now()
//                val formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy. HH:mm:ss")
//                var answer: String = current.format(formatter)

        } else {
            val inputFormatter = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.US)
            val datePinjamApi = inputFormatter.parse(utang[0].tglPinjam)
            val millionSeconds = datePinjamApi?.time?.minus(Calendar.getInstance().timeInMillis)

            if (millionSeconds!! <= 0) {
                keteranganUtang.text = "Menunggak"
                jatuhtempUtang.text = getString(
                    R.string.hari_lagi,
                    millionSeconds.let { TimeUnit.MILLISECONDS.toDays(it).toString() })
            } else {
                keteranganUtang.text = "Jatuh Tempo"
                jatuhtempUtang.text = getString(
                    R.string.hari_lagi,
                    millionSeconds.let { TimeUnit.MILLISECONDS.toDays(it).toString() })
            }
        }
    }

    private fun showData(anggota: List<AnggotaItem>) {
        saldoUser.text = getString(R.string.saldo_user_value, anggota[0].saldoAnggota)
        saldoUserTotal = anggota[0].saldoAnggota.toString()
        //Nama Anggota
        var name = anggota[0].namaAnggota
        nameUser = anggota[0].namaAnggota
        idAnggota = anggota[0].idAnggota.toString()
        imgUser = anggota[0].fotoDiriAnggota

        val arr: Array<String> = name.split(" ").toTypedArray()
        val firstWord = arr[0]
        txtNameHallo.visibility = View.VISIBLE
        txtNameHallo.text = getString(R.string.halo_name, firstWord)
    }
}
