import { ActionIcon, Badge, Flex, Tabs, Typography } from '@tidbcloud/uikit'
import { ExpandNavbarButtonPlaceholder } from '@tidbcloud/uikit/biz'
import { IconChevronRight } from '@tidbcloud/uikit/icons'
import { ResizeCallback } from 're-resizable'
import { useEffect, useState } from 'react'

import ResizableContainer from 'dbaas/components/ResizableContainer'
import useStores from 'dbaas/stores/useStores'
import { eventTracking } from 'dbaas/utils/tracking'

import { useSQLEditorContext, LEFT_PANEL_DEFAULT_WIDTH, LEFT_PANEL_MIN_WIDTH } from '../context/editor-context'
import DatabaseList from '../DatabaseList'
import { useCommonStyles } from '../index.styles'
import SqlFiles from '../SqlFiles'

const SideMenu = () => {
  const {
    store: { preloadedSQLEditor }
  } = useStores()
  const { classes } = useCommonStyles()
  const [resizing, setResizing] = useState(false)

  const {
    sideMenuActiveIndex,
    setSideMenuActiveIndex,
    layout: { leftPanel },
    setLeftPanelLayout,
    resetLeftPanelLayout
  } = useSQLEditorContext()

  useEffect(() => {
    if (preloadedSQLEditor && preloadedSQLEditor.db && preloadedSQLEditor.table) {
      setSideMenuActiveIndex(0)
      localStorage.setItem('Chat2querySideMenuActive', '0')
    } else {
      const lastIndex = parseInt(localStorage.getItem('Chat2querySideMenuActive') || '0')
      setSideMenuActiveIndex(lastIndex)
    }
  }, [])

  const menuChange = (index: number, menuName: string) => {
    setSideMenuActiveIndex(index)
    localStorage.setItem('Chat2querySideMenuActive', `${index}`)
    eventTracking(`${menuName} Tab Clicked`)
  }

  const onResize: ResizeCallback = (_event, _direction, _elementRef, delta) => {
    if ((leftPanel.width || 0) + delta.width <= LEFT_PANEL_MIN_WIDTH + 10) {
      setLeftPanelLayout({
        hidden: true
      })
    }
    setResizing(true)
  }

  const onResizeStop: ResizeCallback = (_event, _direction, _elementRef, delta) => {
    setResizing(false)
    if ((leftPanel.width || 0) + delta.width <= LEFT_PANEL_MIN_WIDTH - 50) {
      setLeftPanelLayout({
        hidden: true,
        width: 1
      })
      return
    }
    setLeftPanelLayout({
      hidden: false,
      width: Math.max(LEFT_PANEL_MIN_WIDTH, (leftPanel.width || 0) + delta.width)
    })
  }

  return (
    <ResizableContainer
      className={resizing ? '' : classes.resizerContainer}
      enable={{
        top: false,
        right: true,
        bottom: false,
        left: false,
        topRight: false,
        bottomRight: false,
        bottomLeft: false,
        topLeft: false
      }}
      size={{ width: leftPanel.hidden ? 0 : (leftPanel.width ?? LEFT_PANEL_DEFAULT_WIDTH), height: '100%' }}
      handleClasses={{ right: classes.resizer }}
      onResize={onResize}
      onResizeStop={onResizeStop}
      minWidth={leftPanel.hidden ? 1 : LEFT_PANEL_MIN_WIDTH}
      maxWidth="50%"
    >
      <Flex
        direction="column"
        sx={(theme) => ({
          borderRight: `1px solid ${theme.colors.carbon[3]}`,
          height: '100%',
          position: 'relative',
          background: theme.white
        })}
      >
        <Flex direction="column" sx={{ overflow: 'hidden', height: '100%' }}>
          <Flex pl={16} pt={16} pb={16} align="center" gap={8}>
            <ExpandNavbarButtonPlaceholder />
            <Typography variant="title-lg" fw={500} ml={-8}>
              SQL Editor
            </Typography>
            <Badge variant="outline" size="sm" color="carbon" c="carbon.7" fw={500}>
              Preview
            </Badge>
          </Flex>
          <Tabs
            value={`${sideMenuActiveIndex}`}
            ml={8}
            styles={(_theme) => ({
              tab: {
                marginRight: 16
              },
              root: {
                display: 'flex',
                flexDirection: 'column',
                height: 'calc(100% - 56px)'
              },
              list: {
                border: 'none',
                flexWrap: 'nowrap',
                gap: '0 !important',
                paddingLeft: 8,
                '&::before': {
                  borderStyle: 'none'
                }
              },
              tabLabel: {
                fontSize: 14
              },
              panel: {
                flex: 1,
                overflow: 'auto'
              }
            })}
            onChange={(value) => menuChange(parseInt(value || ''), value === '0' ? 'schemas' : 'sql files')}
          >
            <Tabs.List>
              <Tabs.Tab value="0">Schemas</Tabs.Tab>
              <Tabs.Tab value="1">SQL Files</Tabs.Tab>
            </Tabs.List>
            <Tabs.Panel value="0">
              <DatabaseList />
            </Tabs.Panel>
            <Tabs.Panel value="1">
              <SqlFiles />
            </Tabs.Panel>
          </Tabs>
        </Flex>
        {leftPanel.hidden && !resizing && (
          <Flex
            align="center"
            sx={(theme) => ({
              position: 'absolute',
              top: 'calc(50% - 15px)',
              right: -18,
              width: 18,
              height: 30,
              backgroundColor: theme.colors.carbon[3],
              borderRadius: '0 18px 18px 0',
              zIndex: 1
            })}
            onClick={() => {
              resetLeftPanelLayout()
            }}
          >
            <ActionIcon
              variant="transparent"
              sx={{
                width: 18,
                minWidth: 18,
                padding: 0
              }}
              color="carbon.6"
            >
              <IconChevronRight size={16} />
            </ActionIcon>
          </Flex>
        )}
      </Flex>
    </ResizableContainer>
  )
}

export default SideMenu
