import { ActionIcon, Box, Flex, Typography } from '@tidbcloud/uikit'
import { IconXClose } from '@tidbcloud/uikit/icons'
import { rgba } from '@tidbcloud/uikit/utils'
import { clsx } from 'clsx'
import { useEffect } from 'react'

import { useTabsStyles } from 'dbaas/screens/DataService/layout.styles'

import { useSQLEditorContext } from '../context/editor-context'
import { deleteEditor } from '../sql-code-editor/editor-cache'

const Tabs = () => {
  const {
    openedFiles,
    setOpenedFiles,
    editedSqlFile,
    editedSqlFileRef,
    setEditedSqlFile,
    scrollEle,
    setScrollEle,
    sqlFiles
  } = useSQLEditorContext()

  const data = openedFiles
  const activeId = editedSqlFile?.id
  const { classes } = useTabsStyles()

  useEffect(() => {
    const index = openedFiles.findIndex((ele) => ele?.id === scrollEle?.id)
    if (index !== -1) {
      const eles = document.getElementsByClassName('endpointItem')
      eles[index].scrollIntoView()
    }
  }, [scrollEle?.id])

  useEffect(() => {
    if (editedSqlFile?.id !== -1) {
      setScrollEle(editedSqlFile)
    }
  }, [editedSqlFile?.id])

  return (
    <Flex
      sx={{
        overflow: 'hidden'
      }}
    >
      <Box
        sx={() => ({
          flex: 1,
          overflow: 'hidden',
          paddingRight: 16
        })}
      >
        <Box
          sx={(t) => ({
            height: 48,
            overflowX: 'auto',
            overflowY: 'hidden',
            whiteSpace: 'nowrap',
            '::-webkit-scrollbar': {
              height: '0px !important'
            },
            '&:hover::-webkit-scrollbar': {
              height: '4px !important'
            },
            '&:hover::-webkit-scrollbar-thumb': {
              backgroundColor: rgba(t.colors.carbon[5], 0.4),
              borderRadius: 2
            },
            '&:hover::-webkit-scrollbar-thumb:hover': {
              backgroundColor: rgba(t.colors.carbon[5], 0.8)
            }
          })}
        >
          {data.map((ele: any, index: number) => {
            const isActive = `${ele?.id}` === `${activeId}`
            return (
              <Box
                key={index}
                sx={(theme) => ({
                  color: isActive ? theme.colors.carbon[9] : theme.colors.carbon[7],
                  position: 'relative',
                  display: 'inline-block',
                  minWidth: 120,
                  maxWidth: 200,
                  padding: '0 18px 0 12px',
                  overflow: 'hidden',
                  textOverflow: 'ellipsis',
                  borderRight: `1px solid ${theme.colors.carbon[4]}`,
                  backgroundColor: isActive ? theme.colors.carbon[0] : '',
                  cursor: 'pointer'
                })}
                className={clsx(classes.openedEndpoint, isActive && 'active', 'endpointItem')}
                onClick={() => {
                  const file = sqlFiles.find((item: any) => item?.id === ele?.id)
                  if (!file) {
                    return
                  }
                  setEditedSqlFile(file)
                  editedSqlFileRef.current = file
                }}
              >
                <Box
                  sx={(theme) => ({
                    position: 'absolute',
                    height: isActive ? 2 : 1,
                    left: 0,
                    right: 0,
                    top: 0,
                    background: isActive ? theme.black : theme.colors.carbon[4]
                  })}
                ></Box>
                <Typography variant="title-sm" lh="48px">
                  {ele?.name}
                </Typography>
                {data.length > 1 && (
                  <ActionIcon
                    variant="subtle"
                    component="span"
                    className="delete-btn"
                    sx={{
                      position: 'absolute',
                      right: 2,
                      top: 14,
                      minWidth: 20,
                      minHeight: 20,
                      width: 20,
                      height: 20
                    }}
                    onClick={(e: any) => {
                      e.preventDefault()
                      e.stopPropagation()
                      const files = openedFiles.filter((item: any) => item?.id !== ele?.id)
                      setOpenedFiles(files)

                      localStorage.setItem('SqlEditorOpenedFiles', JSON.stringify(files.map((file) => file.id)))

                      deleteEditor(ele?.id + '')

                      if (ele.id !== editedSqlFileRef.current.id) {
                        return
                      }

                      const file = sqlFiles.find((file) => file.id === files[0].id)
                      const cur = file || sqlFiles[0]
                      setEditedSqlFile(cur)
                      editedSqlFileRef.current = cur
                    }}
                  >
                    <IconXClose size={14} />
                  </ActionIcon>
                )}
              </Box>
            )
          })}
        </Box>
      </Box>
    </Flex>
  )
}

export default Tabs
