package com.example.smart119.views

import android.content.res.Resources
import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.LinearLayout
import androidx.core.view.setPadding
import com.example.smart119.R

object PaginationHelper {
    var totalPages: Int = 1      // 전체 페이지 수
    var totalRows: Int = 1      // 전체 행 개수
    var currentPage: Int = 1     // 현재 페이지 번호
    var minPage: Int = 1         // 현재 표시되는 최소 페이지 번호
    var maxPage: Int = 5         // 현재 표시되는 최대 페이지 번호
    var buttonMap = mutableMapOf<Int, Button>()
    var pageRequest = false;

    fun setupPaginationLayout(view: View, totalPage: Int, totalRow: Int, update_page:(Int)-> Unit) {
        totalPages = totalPage
        totalRows = totalRow
        currentPage = 1

        // 최소 & 최대 페이지 계산
//        minPage = ((currentPage - 1) / 5) * 5 + 1
        minPage = currentPage
        maxPage = minPage + 4
        if (maxPage > totalPages) maxPage = totalPages

        val pageButtonsContainer = view.findViewById<LinearLayout>(R.id.pageButtonsContainer)

        // dp 값을 px로 변환
        val buttonWidthPx = (60 * Resources.getSystem().displayMetrics.density).toInt()
        val marginPx = (4 * Resources.getSystem().displayMetrics.density).toInt()

        val buttonCount = maxPage - minPage + 1
        // 페이지 버튼 컨테이너 너비 설정 (340dp → px 변환)
        var totalWidthPx = (340 * Resources.getSystem().displayMetrics.density).toInt()
        totalWidthPx = (buttonCount * buttonWidthPx) + ((buttonCount - 1) * (marginPx * 2))
        pageButtonsContainer.layoutParams = LinearLayout.LayoutParams(totalWidthPx, ViewGroup.LayoutParams.MATCH_PARENT)

        val cornerRadiusPx = (10 * Resources.getSystem().displayMetrics.density).toFloat()

        // 기존 버튼 초기화
        pageButtonsContainer.removeAllViews()
        _clear_button()
        if (totalPage == 0) {
            pageButtonsContainer.setPadding(10)
            return
        };
        else {
            pageButtonsContainer.setPadding(0)
        }

        // 페이지 개수만큼 버튼 추가
        var pageCount = 0;
        for (page in minPage..maxPage) {
            val button = Button(pageButtonsContainer.context).apply {
                id = View.generateViewId()
                text = page.toString()
                textSize = 14f
                setPadding(6, 6, 6, 6)
                layoutParams = LinearLayout.LayoutParams(buttonWidthPx, ViewGroup.LayoutParams.MATCH_PARENT).apply {
                    if (pageCount == 0) {
                        marginStart = (marginPx)
                    }
                    marginEnd = marginPx
                }
                setOnClickListener {
                    updatePage(view, page) // 페이지 변경
                    update_page(page)
                }
                background = GradientDrawable().apply {
                    shape = GradientDrawable.RECTANGLE
                    cornerRadius = cornerRadiusPx
                    setColor(Color.parseColor("#0971B8"))
                }
                setTextColor(Color.WHITE)
            }

            // 현재 페이지 버튼 색상 강조
            if (page == currentPage) {
                button.background = GradientDrawable().apply {
                    shape = GradientDrawable.RECTANGLE
                    cornerRadius = cornerRadiusPx
                    setColor(Color.BLUE)
                }
                button.setTextColor(Color.WHITE)
            }

            pageButtonsContainer.addView(button)
            _add_button(page, button)

            pageCount++;
        }

        pageRequest = true;

        println(buttonWidthPx)
    }

    fun _add_button(pageNum:Int, btn:Button) {
        buttonMap[pageNum] = btn
    }
    fun _clear_button() {
        buttonMap.clear();
    }

    fun rePaginationLayout(view: View, update_page:(Int)-> Unit) {
        val pageButtonsContainer = view.findViewById<LinearLayout>(R.id.pageButtonsContainer)

        // dp 값을 px로 변환
        val buttonWidthPx = (60 * Resources.getSystem().displayMetrics.density).toInt()
        val marginPx = (4 * Resources.getSystem().displayMetrics.density).toInt()

        val buttonCount = maxPage - minPage + 1
        // 페이지 버튼 컨테이너 너비 설정 (340dp → px 변환)
        var totalWidthPx = (340 * Resources.getSystem().displayMetrics.density).toInt()
        totalWidthPx = (buttonCount * buttonWidthPx) + ((buttonCount - 1) * (marginPx * 2))
        pageButtonsContainer.layoutParams = LinearLayout.LayoutParams(totalWidthPx, ViewGroup.LayoutParams.MATCH_PARENT)

        println("totalWidthPx ${totalWidthPx}")

        val cornerRadiusPx = (10 * Resources.getSystem().displayMetrics.density).toFloat()

        // 기존 버튼 초기화
        pageButtonsContainer.removeAllViews()
        _clear_button()

        // 페이지 개수만큼 버튼 추가
        var pageCount = 0;
        for (page in minPage..maxPage) {
            val button = Button(pageButtonsContainer.context).apply {
                id = View.generateViewId()
                text = page.toString()
                textSize = 14f
                setPadding(6, 6, 6, 6)
                layoutParams = LinearLayout.LayoutParams(buttonWidthPx, ViewGroup.LayoutParams.MATCH_PARENT).apply {
                    if (pageCount == 0) {
                        marginStart = (marginPx)
                    }
                    marginEnd = marginPx
                }
                setOnClickListener {
                    updatePage(view, page) // 페이지 변경
                    update_page(page)
                }
                background = GradientDrawable().apply {
                    shape = GradientDrawable.RECTANGLE
                    cornerRadius = cornerRadiusPx
                    setColor(Color.parseColor("#0971B8"))
                }
                setTextColor(Color.WHITE)
            }

            // 현재 페이지 버튼 색상 강조
            if (page == currentPage) {
                button.background = GradientDrawable().apply {
                    shape = GradientDrawable.RECTANGLE
                    cornerRadius = cornerRadiusPx
                    setColor(Color.BLUE)
                }
                button.setTextColor(Color.WHITE)
            }

            pageButtonsContainer.addView(button)
            _add_button(page, button)

            pageCount++;
        }
    }

    fun nextPage(view: View, update_page: (Int) -> Unit):Boolean {
        if (currentPage == maxPage) {
            // 5==5 이고,
            if (maxPage < totalPages) {
                minPage = maxPage + 1
                if ((maxPage + 5) <= totalPages) {
                    maxPage = maxPage + 5
                }
                else {
                    maxPage = totalPages
                }

                currentPage++;
                rePaginationLayout(view, { page ->
                    update_page(page)
                })
                return true;
            }
            else return false
        }
        else {
            var bef_Page = buttonMap.get(currentPage);
            var nxt_Page = buttonMap.get(currentPage + 1);
            activePageButton(bef_Page, false)
            activePageButton(nxt_Page, true)
            currentPage++
            return true;
        }
    }

    //1,2,3,4,5,6,7,8,9,10
    //12345
    //678910
    //6에서 prev 누른 경우,(min=6, max=10)
    fun prevPage(view: View, update_page: (Int) -> Unit):Boolean {
        if (currentPage == minPage) {
            if (minPage > 1) {
                var checkMax = maxPage - 5;
                if (checkMax < 5) checkMax = 5;
                maxPage = checkMax;
                minPage = minPage - 5;
                currentPage--;
                rePaginationLayout(view, { page ->
                    update_page(page)
                })
                return true
            }
            else
                return false
        }
        else {
            if (currentPage > 1) {
                var bef_Page = buttonMap.get(currentPage);
                var prv_Page = buttonMap.get(currentPage - 1);
                activePageButton(bef_Page, false)
                activePageButton(prv_Page, true)
                currentPage--
                return true;
            }
            else
                return false
        }
    }

    fun activePageButton(pageBtn: Button?, isActive: Boolean) {
        if (isActive) {
            pageBtn?.background = GradientDrawable().apply {
                shape = GradientDrawable.RECTANGLE
                cornerRadius = (10 * Resources.getSystem().displayMetrics.density).toFloat()
                setColor(Color.BLUE)
            }
            pageBtn?.setTextColor(Color.WHITE)
        } else {
            pageBtn?.background = GradientDrawable().apply {
                shape = GradientDrawable.RECTANGLE
                cornerRadius = (10 * Resources.getSystem().displayMetrics.density).toFloat()
                setColor(Color.parseColor("#0971B8"))
            }
            pageBtn?.setTextColor(Color.WHITE)
        }

    }

    fun updatePage(view: View, newPage: Int) {
        if (newPage in 1..totalPages) {
            var bef_Page = buttonMap.get(currentPage);
            var nxt_Page = buttonMap.get(newPage);
            activePageButton(bef_Page, false)
            activePageButton(nxt_Page, true)

            currentPage = newPage
        }
    }

    fun getPageInfo(): String {
        return "총 페이지: $totalPages, 현재 페이지: $currentPage, 표시 범위: $minPage ~ $maxPage"
    }
}