import {
  NDKFilter,
  NDKKind,
  NDKSubscriptionCacheUsage
} from '@nostr-dev-kit/ndk'
import { ModCard } from 'components/ModCard'
import { ModFilter } from 'components/Filters/ModsFilter'
import { PaginationWithPageNumbers } from 'components/Pagination'
import { SearchInput } from 'components/SearchInput'
import { MAX_MODS_PER_PAGE, T_TAG_VALUE } from 'constants.ts'
import {
  useAppSelector,
  useFilteredMods,
  useLocalStorage,
  useMuteLists,
  useNDKContext,
  useNSFWList
} from 'hooks'
import { useEffect, useMemo, useRef, useState } from 'react'
import { useParams, useSearchParams } from 'react-router-dom'
import { FilterOptions, ModDetails } from 'types'
import {
  CurationSetIdentifiers,
  DEFAULT_FILTER_OPTIONS,
  extractModData,
  isModDataComplete,
  scrollIntoView
} from 'utils'
import { useCuratedSet } from 'hooks/useCuratedSet'
import { CategoryFilterPopup } from 'components/Filters/CategoryFilterPopup'

export const GamePage = () => {
  const scrollTargetRef = useRef<HTMLDivElement>(null)
  const params = useParams()
  const { name: gameName } = params
  const { ndk } = useNDKContext()
  const muteLists = useMuteLists()
  const nsfwList = useNSFWList()
  const repostList = useCuratedSet(CurationSetIdentifiers.Repost)

  const [filterOptions] = useLocalStorage<FilterOptions>(
    'filter',
    DEFAULT_FILTER_OPTIONS
  )
  const [mods, setMods] = useState<ModDetails[]>([])

  const [currentPage, setCurrentPage] = useState(1)

  const userState = useAppSelector((state) => state.user)

  // Search
  const searchTermRef = useRef<HTMLInputElement>(null)
  const [searchParams, setSearchParams] = useSearchParams()
  const [searchTerm, setSearchTerm] = useState(searchParams.get('q') || '')

  // Categories filter
  const [categories, setCategories] = useState(searchParams.getAll('l') || [])
  const [heirarchies, setFullHeirarchies] = useState(
    searchParams.getAll('h') || []
  )
  const [showCategoryPopup, setShowCategoryPopup] = useState(false)

  const handleSearch = () => {
    const value = searchTermRef.current?.value || '' // Access the input value from the ref
    setSearchTerm(value)

    if (value) {
      searchParams.set('q', value)
    } else {
      searchParams.delete('q')
    }

    setSearchParams(searchParams, {
      replace: true
    })
  }

  // Handle "Enter" key press inside the input
  const handleKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
    if (event.key === 'Enter') {
      handleSearch()
    }
  }

  const filteredMods = useMemo(() => {
    const filterSourceFn = (mod: ModDetails) => {
      if (filterOptions.source === window.location.host) {
        return mod.rTag === filterOptions.source
      }
      return true
    }

    // If search term is missing, only filter by sources
    if (searchTerm === '') return mods.filter(filterSourceFn)

    const lowerCaseSearchTerm = searchTerm.toLowerCase()

    const filterFn = (mod: ModDetails) =>
      mod.title.toLowerCase().includes(lowerCaseSearchTerm) ||
      mod.game.toLowerCase().includes(lowerCaseSearchTerm) ||
      mod.summary.toLowerCase().includes(lowerCaseSearchTerm) ||
      mod.body.toLowerCase().includes(lowerCaseSearchTerm) ||
      mod.tags.findIndex((tag) =>
        tag.toLowerCase().includes(lowerCaseSearchTerm)
      ) > -1

    return mods.filter(filterFn).filter(filterSourceFn)
  }, [filterOptions.source, mods, searchTerm])

  const filteredModList = useFilteredMods(
    filteredMods,
    userState,
    filterOptions,
    nsfwList,
    muteLists,
    repostList
  )

  // Pagination logic
  const totalGames = filteredModList.length
  const totalPages = Math.ceil(totalGames / MAX_MODS_PER_PAGE)
  const startIndex = (currentPage - 1) * MAX_MODS_PER_PAGE
  const endIndex = startIndex + MAX_MODS_PER_PAGE
  const currentMods = filteredModList.slice(startIndex, endIndex)

  const handlePageChange = (page: number) => {
    if (page >= 1 && page <= totalPages) {
      scrollIntoView(scrollTargetRef.current)
      setCurrentPage(page)
    }
  }

  useEffect(() => {
    const filter: NDKFilter = {
      kinds: [NDKKind.Classified],
      '#t': [T_TAG_VALUE]
    }

    if (categories.length) {
      filter['#l'] = categories.map((l) => `com.degmods:${l}`)
    }

    if (heirarchies.length) {
      filter['#L'] = heirarchies.map((L) => `com.degmods:${L}`)
    }

    const subscription = ndk.subscribe(filter, {
      cacheUsage: NDKSubscriptionCacheUsage.PARALLEL,
      closeOnEose: true
    })

    subscription.on('event', (ndkEvent) => {
      if (isModDataComplete(ndkEvent)) {
        const mod = extractModData(ndkEvent)
        if (mod.game === gameName)
          setMods((prev) => {
            if (prev.find((e) => e.aTag === mod.aTag)) return [...prev]

            return [...prev, mod]
          })
      }
    })

    subscription.start()

    // Cleanup function to stop subscription
    return () => {
      subscription.stop()
    }
  }, [gameName, ndk, categories, heirarchies])

  if (!gameName) return null

  return (
    <>
      <div className='InnerBodyMain'>
        <div className='ContainerMain'>
          <div
            className='IBMSecMainGroup IBMSecMainGroupAlt'
            ref={scrollTargetRef}
          >
            <div className='IBMSecMain'>
              <div className='SearchMainWrapper'>
                <div className='IBMSMTitleMain'>
                  <h2 className='IBMSMTitleMainHeading'>
                    Game:&nbsp;
                    <span className='IBMSMTitleMainHeadingSpan'>
                      {gameName}
                    </span>
                    {searchTerm !== '' && (
                      <>
                        &nbsp;&mdash;&nbsp;
                        <span className='IBMSMTitleMainHeadingSpan'>
                          {searchTerm}
                        </span>
                      </>
                    )}
                  </h2>
                </div>
                <SearchInput
                  handleKeyDown={handleKeyDown}
                  handleSearch={handleSearch}
                  ref={searchTermRef}
                />
              </div>
            </div>
            <ModFilter>
              <div className='FiltersMainElement'>
                <button
                  className='btn btnMain btnMainDropdown'
                  type='button'
                  onClick={() => {
                    setShowCategoryPopup(true)
                  }}
                >
                  Categories
                  <svg
                    xmlns='http://www.w3.org/2000/svg'
                    viewBox='0 0 512 512'
                    width='1em'
                    height='1em'
                    fill='currentColor'
                  >
                    <path d='M3.9 54.9C10.5 40.9 24.5 32 40 32l432 0c15.5 0 29.5 8.9 36.1 22.9s4.6 30.5-5.2 42.5L320 320.9 320 448c0 12.1-6.8 23.2-17.7 28.6s-23.8 4.3-33.5-3l-64-48c-8.1-6-12.8-15.5-12.8-25.6l0-79.1L9 97.3C-.7 85.4-2.8 68.8 3.9 54.9z' />
                  </svg>
                </button>
              </div>
            </ModFilter>

            <div className='IBMSecMain IBMSMListWrapper'>
              <div className='IBMSMList'>
                {currentMods.map((mod) => (
                  <ModCard key={mod.id} {...mod} />
                ))}
              </div>
            </div>
            <PaginationWithPageNumbers
              currentPage={currentPage}
              totalPages={totalPages}
              handlePageChange={handlePageChange}
            />
          </div>
        </div>
      </div>
      {showCategoryPopup && <CategoryFilterPopup />}
    </>
  )
}
