'use client'

import type { SortFilterItem as SortFilterItemType } from '@/lib/constants'

import { createUrl } from '@/utilities/createUrl'
import { updateShopSearchParams } from '@/utilities/shopParams'
import clsx from 'clsx'
import Link from 'next/link'
import { usePathname, useSearchParams } from 'next/navigation'

import type { ListItem } from '.'
import type { PathFilterItem as PathFilterItemType } from '.'

function PathFilterItem({ item }: { item: PathFilterItemType }) {
  const pathname = usePathname()
  const searchParams = useSearchParams()
  const active = pathname === item.path
  const newParams = new URLSearchParams(searchParams.toString())
  const className = clsx(
    'flex min-h-9 w-full items-center justify-center rounded-lg border px-3 py-2 text-center text-xs font-semibold transition duration-200',
    {
      'border-[#dbe8d7] bg-white text-[#607668] hover:border-[#8aac95] hover:bg-[#f2f7ee] hover:text-[#063f2b] hover:shadow-sm':
        !active,
      'border-[#003b29] bg-[#003b29] text-white shadow-sm': active,
    },
  )

  newParams.delete('q')

  return (
    <li className="flex" key={item.title}>
      {active ? (
        <p className={className}>{item.title}</p>
      ) : (
        <Link className={className} href={createUrl(item.path, newParams)}>
          {item.title}
        </Link>
      )}
    </li>
  )
}

function SortFilterItem({ item }: { item: SortFilterItemType }) {
  const pathname = usePathname()
  const searchParams = useSearchParams()
  const currentSort = searchParams.get('sort') || 'title'
  const active = currentSort === item.slug
  const href = createUrl(
    pathname,
    updateShopSearchParams(searchParams, {
      type: 'sort',
      value: item.slug,
    }),
  )
  const className = clsx(
    'flex min-h-9 w-full items-center justify-center rounded-lg border px-3 py-2 text-center text-xs font-semibold transition duration-200',
    {
      'border-[#dbe8d7] bg-white text-[#607668] hover:border-[#8aac95] hover:bg-[#f2f7ee] hover:text-[#063f2b] hover:shadow-sm':
        !active,
      'border-[#003b29] bg-[#003b29] text-white shadow-sm': active,
    },
  )

  return (
    <li className="flex" key={item.title}>
      {active ? (
        <p className={className}>{item.title}</p>
      ) : (
        <Link className={className} href={href} prefetch={false}>
          {item.title}
        </Link>
      )}
    </li>
  )
}

export function FilterItem({ item }: { item: ListItem }) {
  return 'path' in item ? <PathFilterItem item={item} /> : <SortFilterItem item={item} />
}
