import styled from "@emotion/styled"
import { memo, useMemo } from "react"
import { css } from "@emotion/css"
import Icon from "@aet/icons/macro"
import { useFileListRenderer } from "./SimpleList"
import type { GetFileListQuery } from "~/generated/graphql"
import { getTabs, useSelector } from "~/options/store"
import { ButtonWrapper } from "~/shared/styled"
import { TabCloseButton } from "~/options/editor/Tabs/CloseDot"
import type { TreeItem } from "../index"
import { token } from "~/options/theme"
import { useFileSaver } from "~/options/hooks/useSaveFile"

export const OpenedList = memo<{
  data?: GetFileListQuery
}>(({ data }) => {
  const tabs = useSelector(getTabs)

  const list = useMemo(() => {
    const ids = new Set(tabs.map(t => t.id))
    return data?.files.filter(s => ids.has(s.id)) ?? []
  }, [tabs, data?.files])

  const render = useFileListRenderer()

  if (list.length < 2) {
    return null
  }

  return (
    <div>
      <List>
        {list.map(item =>
          render({
            item,
            className: listItem,
            readOnly: true,
            children: <OpenedTabToolbar item={item} key={item.id} />,
            multiSelect: false,
          }),
        )}
      </List>
      <hr />
    </div>
  )
})

const OpenedTabToolbar = memo(({ item }: { item: TreeItem }) => {
  const isStyleDirty = useSelector(s => s.dirtyFileIds.has(item.id))
  const save = useFileSaver()

  return (
    <ButtonContainer>
      <ButtonWrapper disabled={!isStyleDirty} onClick={() => save(item.id)}>
        <Icon icon="VscSave" />
      </ButtonWrapper>
      <TabCloseButton fileId={item.id} fileName={item.name} />
    </ButtonContainer>
  )
})

const List = styled.div`
  border-radius: 5px;
  margin-top: 7px;
  flex-grow: 1;
`

const ButtonContainer = styled.div`
  display: flex;
  align-items: center;
  > button {
    font-size: 1.143em;
    margin-left: 3px;
    cursor: pointer;
    &:hover {
      color: ${token.accent.fg};
    }
  }
`

const listItem = css`
  height: 30px;
  &:not(:hover) ${ButtonContainer} {
    display: none;
  }
`
