import styled from "@emotion/styled"
import { useTranslation } from "react-i18next"
import Icon from "@aet/icons/macro"
import { memo, useMemo } from "react"
import { sortBy } from "lodash"
import { Pill } from "~/shared/styled"
import { useDomainSuggestions } from "~/options/hooks/useDomainSuggestions"
import type { Rule } from "~/shared/models"
import { RuleType } from "~/shared/models/enums.generated"
import { useActiveFileName } from "~/options/hooks/useFileName"
import { jaroDistance } from "~/options/tabs/FileTree/stringSimilarity"

export const AddRule = memo<{
  rules?: Rule[]
  onAddDomain(domain: string, exclude?: boolean): void
}>(({ rules, onAddDomain }) => {
  const { t } = useTranslation()
  const existingDomains = useMemo(
    () => rules?.filter(r => r.type === RuleType.Domain).map(r => r.value) ?? [],
    [rules],
  )
  const fileName = useActiveFileName()
  const suggestions = useDomainSuggestions({ skip: false })

  const list = useMemo(() => {
    let res = suggestions.map(s => s.hostname).filter(d => !existingDomains.includes(d))
    if (fileName) {
      res = sortBy(res, domain => jaroDistance(domain, fileName))
    }
    return res
  }, [suggestions, existingDomains, fileName])

  const onAddEmpty = (e: React.MouseEvent) => {
    e.stopPropagation()
    onAddDomain("")
  }

  return (
    <AddRuleContainer>
      <StyledButton onClick={onAddEmpty}>
        <Icon icon="RiAddFill" />
        {t("rule.addRule")}
      </StyledButton>

      <SuggestionContainer>
        {list.map(domain => (
          <SuggestionButton key={domain} onClick={() => onAddDomain(domain)}>
            <Icon icon="RiAddFill" />
            {domain}
          </SuggestionButton>
        ))}
      </SuggestionContainer>
    </AddRuleContainer>
  )
})

const AddRuleContainer = styled.div`
  display: flex;
  align-items: center;
`

const StyledButton = styled(Pill)`
  display: flex;
  align-items: center;
  margin-top: 12px;
  padding: 7px 12px 7px 10px;
  > svg {
    margin-right: 4px;
  }
`

const SuggestionContainer = styled.div`
  display: flex;
  flex: 1;
  overflow: scroll;
  -webkit-mask-image: linear-gradient(90deg, #000 85%, transparent);
`
const SuggestionButton = styled(StyledButton)`
  font-style: italic;
  margin-left: 5px;
  padding: 5px 7px 5px 5px;
  white-space: nowrap;
`
