import { Listbox } from "@headlessui/react"
import styled from "@emotion/styled"
import { useTranslation } from "react-i18next"
import { css, cx } from "@emotion/css"
import Icon from "@aet/icons/macro"
import { memo } from "react"
import { useEvent } from "@aet/hooks"
import { FileState } from "~/shared/models/enums.generated"
import type { TreeItem } from "./index"
import type { TranslationKey } from "~/shared/i18n/data.generated"
import { S, useLocalStorageState } from "~/shared/hooks/useLocalStorage"
import { isGlobalStyle } from "~/shared"
import { color, token } from "~/options/theme"

const enum Filter {
  Null,
  Hidden,
  Archived,
  Deleted,
  NoIcon,
}

export interface FilterState {
  key: Filter
  icon: React.ReactElement
  value: (file: TreeItem) => boolean
  label: TranslationKey
}

const filterStates: FilterState[] = [
  {
    key: Filter.Null,
    icon: <Icon icon="VscFiles" />,
    value: file => file.state === FileState.None,
    label: "tab.file",
  },
  {
    key: Filter.Hidden,
    icon: <Icon icon="BiHide" />,
    value: file => file.state === FileState.Hidden,
    label: "editor.hidden",
  },
  {
    key: Filter.Archived,
    icon: <Icon icon="VscArchive" />,
    value: file => file.state === FileState.Archived,
    label: "editor.archived",
  },
  {
    key: Filter.Deleted,
    icon: <Icon icon="VscTrash" />,
    value: file => file.state === FileState.Deleted,
    label: "editor.deleted",
  },
  {
    key: Filter.NoIcon,
    icon: <Icon icon="SlQuestion" />,
    value: file => !file.icon || (file.icon === ddgEmpty && !isGlobalStyle(file)),
    label: "editor.noIcon",
  },
]

export function useFilterState() {
  return useLocalStorageState(
    S.FileTreeFilter,
    filterStates[0],
    filter => filter.key,
    key => filterStates.find(({ key: k }) => k === key)!,
  )
}

export const FilterStateSelect = memo<{
  filterState: FilterState
  setFilterState: (state: FilterState) => void
}>(({ filterState, setFilterState }) => {
  const { t } = useTranslation()
  const onChange = useEvent((value: Filter) => {
    setFilterState(filterStates.find(({ key }) => key === value)!)
  })

  const currentKey = filterState.key

  return (
    <Listbox name="filterState" value={currentKey} onChange={onChange}>
      {({ open }) => (
        <>
          <SubheadingSelect>
            {t(filterStates.find(({ key }) => key === currentKey)!.label)}
            {open ? <Icon icon="VscChevronUp" /> : <Icon icon="VscChevronDown" />}
          </SubheadingSelect>
          <SubheadingOptions className={subheadingOptions}>
            {filterStates.map(({ key, label, icon }) => {
              const active = key === currentKey
              return (
                <Listbox.Option key={key} value={key} className={cx({ active })}>
                  {active ? (
                    <Icon icon="BsCheckLg" />
                  ) : (
                    icon ?? <svg style={{ width: "1em", height: "1em" }} />
                  )}
                  {t(label)}
                </Listbox.Option>
              )
            })}
          </SubheadingOptions>
        </>
      )}
    </Listbox>
  )
})

const SubheadingSelect = styled(Listbox.Button)`
  align-items: center;
  border: none;
  cursor: pointer;
  display: flex;
  flex-grow: 1;
  font-size: 0.88em;
  letter-spacing: 0.7px;
  margin: -2px -5px;
  margin-top: -6px;
  opacity: 0.7;
  text-align: left;
  text-transform: uppercase;
  > svg {
    margin-left: 5px;
  }
  > option {
    text-transform: none;
  }
  &:hover {
    text-decoration: underline;
  }
`

const SubheadingOptions = styled(Listbox.Options)`
  list-style: none;
  margin-left: -10px;
  margin-top: 20px;
  min-width: 240px;
  padding-inline-start: 0;
  z-index: 5;
  padding: 5px;
`

export const subheadingOptions = css`
  background-color: ${token.canvas.overlay};
  border-radius: 5px;
  border: 1px solid ${token.border.default};
  box-shadow: ${token.shadow.extraLarge};
  position: absolute;
  padding: 5px;

  > li {
    display: flex;
    align-items: center;
    padding: 6px 10px;
    border-radius: 5px;
    cursor: pointer;
    &.active {
      background-color: ${color("#e9e9e9", "#20324e")};
    }
    &:hover {
      background-color: ${color("#ddd", "#20324e")};
    }
    &:not(:last-child) {
      margin-bottom: 2px;
    }
    > svg {
      margin-right: 7px;
    }
  }
`

const ddgEmpty =
  "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyhpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/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