import styled from "@emotion/styled"
import { useTranslation } from "react-i18next"
import { memo, useRef } from "react"
import { useEvent } from "@aet/hooks"
import { token } from "../../theme"
import { getActiveFile, getActiveFileRules, useDispatch, useSelector } from "../../store"
import { addRule, deleteRule, updateRule } from "~/options/store/actions"
import { RuleView } from "./Rule"
import { RuleType } from "~/shared/models/enums.generated"
import { isGlobalStyle } from "~/shared"
import { AddRule } from "./AddRule"

export const Rules = memo<{ className?: string }>(({ className }) => {
  const { t } = useTranslation()
  const isActiveTabGlobal = useSelector(state => isGlobalStyle(getActiveFile(state)))

  const rules = useSelector(getActiveFileRules)
  const dispatch = useDispatch()
  const tbody = useRef<HTMLTableSectionElement>(null)

  const onAddDomain = useEvent((domain: string, exclude = false) => {
    dispatch(
      addRule({
        type: RuleType.Domain,
        value: domain,
        exclude,
      }),
    )
    setTimeout(() => {
      const last = tbody.current!.lastElementChild!
      last.scrollIntoView()
      last.querySelector<HTMLInputElement>("input[type=text]")!.focus()
    }, 200)
  })

  if (isActiveTabGlobal) {
    return (
      <RulesContainer className={className}>
        {t("file.globalFileCannotHaveRules")}
      </RulesContainer>
    )
  }

  return (
    <RulesContainer className={className}>
      {Boolean(rules?.length) && (
        <RuleContainer>
          <Table>
            <tbody ref={tbody}>
              {rules!.map((rule, index, { length }) => (
                <RuleView
                  rule={rule}
                  key={index}
                  setRule={rule => dispatch(updateRule({ index, rule }))}
                  onDelete={length === 1 ? undefined : () => dispatch(deleteRule(index))}
                />
              ))}
            </tbody>
          </Table>
        </RuleContainer>
      )}

      <AddRule rules={rules} onAddDomain={onAddDomain} />
    </RulesContainer>
  )
})

const RulesContainer = styled.div`
  margin: 12px;
  margin-bottom: 2px;
  flex-grow: 1;
`

const RuleContainer = styled.div`
  max-height: calc(var(--panel-size) - 110px);
  overflow-y: scroll;
`

const Table = styled.table`
  border: 1px solid ${token.border.muted};
  border-radius: 3px;
  border-spacing: 0;
  width: 100%;
  td {
    padding: 6px;
    &:first-of-type {
      padding-left: 12px;
    }
    &:not(:last-child) {
      border-right: 1px solid ${token.border.muted};
    }
  }
`
