import { css } from "@emotion/css"
import styled from "@emotion/styled"
import { useFirstMountState } from "@react-hookz/web"
import { useTranslation } from "react-i18next"
import { memo } from "react"
import { useEvent } from "@aet/hooks"
import { gql, useLazyQuery } from "~/generated/graphql"
import { token } from "../../theme"
import { useInputOnChange } from "~/shared/hooks/useInput"
import { SearchResults } from "./SearchResults"
import { S, useLocalStorageState } from "~/shared/hooks/useLocalStorage"

const SEARCH_TAB = gql<"SearchTab">`
  query SearchTab($query: String!, $caseSensitive: Boolean!) {
    search(query: $query, caseSensitive: $caseSensitive, regExp: false) {
      file {
        id
        name
      }
      line
      index
      submatch {
        match
        start
        end
      }
    }
  }
`

export const SearchTab = memo<ClassNameProp>(({ className }) => {
  const { t } = useTranslation()
  const [search, setSearch] = useLocalStorageState(S.SearchTabSearch, "")
  const [replace, setReplace] = useLocalStorageState(S.SearchTabReplace, "")

  const onSearchChange = useInputOnChange(setSearch)
  const onReplaceChange = useInputOnChange(setReplace)

  const isFirstMount = useFirstMountState()

  const [runSearchTabQuery, { data }] = useLazyQuery(SEARCH_TAB, {
    variables: {
      query: search,
      caseSensitive: false,
    },
  })

  const executeSearch = useEvent(() => {
    runSearchTabQuery({
      variables: {
        query: search,
        caseSensitive: false,
      },
    })
  })

  if (isFirstMount && search) {
    setTimeout(() => executeSearch(), 0)
  }

  const onKeydown = useEvent((e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === "Enter") {
      e.stopPropagation()
      executeSearch()
    }
  })

  return (
    <SearchTabContainer className={className}>
      <div
        className={css`
          margin: 0 10px;
          margin-bottom: 5px;
        `}
      >
        <Input
          type="search"
          placeholder={t("search.find")}
          value={search}
          onKeyDown={onKeydown}
          onChange={onSearchChange}
        />
      </div>
      {false && (
        <div
          className={css`
            margin: 0 10px;
          `}
        >
          <Input
            disabled
            type="search"
            placeholder={t("search.replaceAll")}
            value={replace}
            onKeyDown={onKeydown}
            onChange={onReplaceChange}
          />
        </div>
      )}
      {data != null && <SearchResults data={data} />}
    </SearchTabContainer>
  )
})

const SearchTabContainer = styled.div`
  display: flex;
  flex-direction: column;
  border-radius: 5px;
  padding: 7px 0;
  height: 100%;

  body.light & {
    background-color: rgb(247 248 250);
  }
`

const Input = styled.input`
  background-color: ${token.canvas.overlay};
  border-radius: 75px;
  border: 1px solid ${token.border.default};
  padding: 5px 10px;
  width: 100%;
  &:disabled {
    cursor: not-allowed;
    opacity: 0.7;
  }
  &:focus {
    border-color: #5f677a;
  }
`
