import { filterAtom } from "@/atoms"
import { Link, router, usePage } from "@inertiajs/react"
import { useAtomValue } from "jotai"
import { useState } from "react"
import { useSearchParams } from "@/utils/format"
import { cn } from "@/lib/utils"

function Pagination({ links, meta }) {
  const { props } = usePage();
  const location = new URL(props.location);
  const params = new URLSearchParams(location.search);
  const filters = Object.keys(useAtomValue(filterAtom) ?? [])

  const [pageInput, setPageInput] = useState(meta?.current_page || 1)

  const handlePerPageChange = (e) => {
    const value = e.target.value
    params.set("per_page", value)
    params.delete("page") // Reset to page 1 when changing per_page
    router.visit(`${location.pathname}?${params.toString()}`)
  }

  const handlePageSubmit = (e) => {
    e.preventDefault()
    let page = parseInt(pageInput)
    if (page < 1) page = 1
    if (page > (meta?.last_page || 1)) page = meta?.last_page || 1

    params.set("page", page)
    router.visit(`${location.pathname}?${params.toString()}`)
  }

  const getLinkClasses = (active) => {
    return cn(
      "relative block rounded border px-3 py-1.5 text-xs font-medium transition-all duration-300",
      active
        ? "bg-blue-600 text-white border-blue-600"
        : "bg-white text-gray-500 border-gray-300 hover:bg-gray-100 dark:bg-gray-800 dark:text-gray-400 dark:border-gray-700 dark:hover:bg-gray-700 dark:hover:text-white"
    )
  }

  return (
    <nav aria-label="Pagination" className="grid grid-cols-2 sm:flex sm:flex-row items-center justify-between gap-4 w-full py-2">
      {/* Per Page Selector */}
      <div className="flex items-center gap-2 order-2 sm:order-1 justify-self-start">
        <select
          value={params.get("per_page") || 20}
          onChange={handlePerPageChange}
          className="bg-white border border-gray-300 text-gray-700 text-xs rounded focus:ring-blue-500 focus:border-blue-500 block pl-2 pr-8 py-1.5 dark:bg-gray-800 dark:border-gray-600 dark:placeholder-gray-400 dark:text-gray-300 hover:border-gray-400 transition-colors cursor-pointer"
        >
          {[10, 20, 50, 100, 250, 500].map((val) => (
            <option key={val} value={val}>{val}</option>
          ))}
        </select>
        <span className="text-xs text-gray-500 dark:text-gray-400">items</span>
      </div>

      {/* Pagination Links */}
      <ul className="flex items-center gap-1 order-1 sm:order-2 col-span-2 w-full justify-center sm:w-auto flex-wrap sm:flex-nowrap pb-2 sm:pb-0 px-1">
        {links.map((link, i) => {
          let pageParams
          if (link.url) {
            const pageUrl = new URL(link.url)
            pageParams = new URLSearchParams(pageUrl.search)
          }

          if (pageParams && params.get('searchBy')) {
            pageParams?.set("searchBy", params?.get('searchBy'));
          }
          if (pageParams && params.get('q')) {
            pageParams?.set("q", params?.get('q'));
          }
          if (pageParams && params.get('filter')) {
            pageParams?.set("filter", params?.get('filter'));
          }
          if (pageParams && params.get('status')) {
            pageParams?.set("status", params?.get('status'));
          }

          if (pageParams && params.get('sort')) {
            pageParams.set('sort', params.get('sort'))
          }
          if (pageParams && params.get('sortDirection')) {
            pageParams.set('sortDirection', params.get('sortDirection'))
          }

          if (pageParams && params.get('category_id')) {
            pageParams.set('category_id', params.get('category_id'))
          }

          // Preserve per_page
          if (pageParams && params.get('per_page')) {
            pageParams.set('per_page', params.get('per_page'))
          }

          if (filters?.length > 0) {
            for (const filter of filters) {
              if (pageParams && params.get(filter)) {
                pageParams.set(filter, params.get(filter))
              }
            }
          }

          // Handle deleted_at specific case if needed or general dynamic filters
          if (pageParams) {
            params.forEach((value, key) => {
              if (!pageParams.has(key) && key !== 'page') {
                pageParams.set(key, value)
              }
            })
          }


          return (
            <li key={i} aria-current="page">
              <Link
                className={getLinkClasses(link.active)}
                href={!link.url
                  ? "#"
                  : `${location.pathname}?${pageParams?.toString()}`}
                dangerouslySetInnerHTML={{ __html: link.label }}
              />
            </li>
          );
        })}
      </ul>

      {meta && (
        <form onSubmit={handlePageSubmit} className="flex items-center gap-1 order-3 justify-self-end ml-auto sm:ml-0">
          <span className="text-xs text-gray-500 dark:text-gray-400">Page</span>
          <input
            type="number"
            min="1"
            max={meta.last_page}
            value={pageInput}
            onChange={(e) => setPageInput(e.target.value)}
            className="bg-gray-50 border border-gray-300 text-gray-900 text-xs rounded focus:ring-blue-500 focus:border-blue-500 block w-12 p-1 text-center dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500"
          />
          <span className="text-xs text-gray-500 dark:text-gray-400">/ {meta.last_page}</span>
        </form>
      )}
    </nav>
  )
}

export default Pagination