import browser from "webextension-polyfill"
import { useCallback, useEffect, useState } from "react"
import { sortBy, uniqBy } from "lodash"
import { useChromeEvent } from "~/shared/hooks/useChromeEvent"

const INVALID_PROTOCOLS = new Set(["chrome:", "chrome-extension:", "about:"])

interface DomainSuggestion {
  hostname: string
  title?: string
}

/**
 * Returns a list of currently opened hostnames.
 */
export function useDomainSuggestions({
  skip,
}: {
  /** Skip fetching suggestions */
  skip: boolean
}) {
  const [suggestions, setSuggestions] = useState<DomainSuggestion[]>([])

  const fetch = useCallback(async () => {
    const windows = await browser.windows.getAll({ populate: true })

    const tabs = windows
      .filter(tab => !tab.incognito)
      .flatMap(tab => tab.tabs || [])
      .filter(tab => tab.url)
      .map(tab => {
        const url = new URL(tab.url!)
        if (INVALID_PROTOCOLS.has(url.protocol)) {
          return null
        }

        return {
          hostname: url.hostname,
          title: tab.title,
        }
      })
      .filter(Boolean)
      .filter(x => x.hostname)

    setSuggestions(sortedUnique(tabs, tab => tab.hostname))
  }, [])

  useChromeEvent(browser.tabs.onUpdated, fetch)

  useEffect(() => {
    if (skip) {
      return
    }

    void fetch()
  }, [fetch, skip])

  return suggestions
}

function sortedUnique<T>(list: T[], by: (value: T) => any) {
  return sortBy(uniqBy(list, by), by)
}
