import styled from "@emotion/styled"
import { memo, useCallback } from "react"
import { useEvent } from "@aet/hooks"
import { FixedSizeList } from "react-window"
import { useSelector } from "~/options/store"
import { FileItem } from "../FileItem"
import { ContainerDimensions } from "~/vendor/react-container-dimensions"
import { useOpenFile } from "~/options/hooks/useOpenFile"
import { type Tree, type TreeItem, useTreeContext } from "../index"

export const SimpleList = memo<{
  list: Tree
  listRef?: React.Ref<FixedSizeList>
  multiSelect: boolean
}>(({ list, listRef, multiSelect }) => {
  const render = useFileListRenderer()

  return (
    <SimpleListContainer>
      {list.length > 0 && (
        <ContainerDimensions>
          {({ height, width, ref }) => (
            <FixedSizeList<unknown>
              outerRef={ref}
              height={height}
              itemCount={list.length}
              itemSize={30}
              width={width}
              ref={listRef}
            >
              {({ index, style }) => render({ item: list[index], style, multiSelect })}
            </FixedSizeList>
          )}
        </ContainerDimensions>
      )}
    </SimpleListContainer>
  )
})

interface ListRendererProps {
  children?: React.ReactNode
  className?: string
  item: TreeItem
  multiSelect: boolean
  readOnly?: boolean
  style?: React.CSSProperties
}

export function useFileListRenderer() {
  const activeId = useSelector(state => state.activeFileId)
  const open = useOpenFile()
  const { selectedFiles, setSelectedFiles } = useTreeContext()

  const onToggle = useEvent((checked: boolean, itemId: string) => {
    if (checked) {
      setSelectedFiles([...selectedFiles, itemId])
    } else {
      setSelectedFiles(selectedFiles.filter(id => id !== itemId))
    }
  })

  return useCallback(
    ({
      item,
      style,
      readOnly,
      className,
      children,
      multiSelect: multi,
    }: ListRendererProps) => (
      <FileItem
        active={multi ? selectedFiles.includes(item.id) : item.id === activeId}
        className={className}
        item={item}
        key={item.id}
        onOpen={open}
        onToggle={checked => onToggle(checked, item.id)}
        readOnly={readOnly}
        selectedFileIds={selectedFiles}
        style={style}
        multi={multi}
      >
        {children}
      </FileItem>
    ),
    [selectedFiles, onToggle, open, activeId],
  )
}

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