import { Tabs, Box, Alert, Typography } from '@tidbcloud/uikit'
import { ResizeCallback } from 're-resizable'
import { useMemo, useState } from 'react'

import ResizableContainer from 'dbaas/components/ResizableContainer'
import { useHelpCenterContext } from 'dbaas/screens/HelpCenter/context'
import { eventTracking } from 'dbaas/utils/tracking'

import { useDataApiContext, RIGHT_PANEL_DEFAULT_WIDTH, RIGHT_PANEL_MIN_WIDTH } from '../context'
import DatabaseList from '../DatabaseList'
import { useCommonStyles } from '../index.styles'

import Params from './Params'
import Properties from './Properties'
import SystemDataParams from './SystemDataParams'

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

  const {
    layout: { rightPanel },
    setRightPanelLayout,
    editEndpoint,
    panelOpenedKey,
    setPanelOpenedKey
  } = useDataApiContext()

  const { dataServiceGuideStep } = useHelpCenterContext()

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

  const onResizeStop: ResizeCallback = (_event, _direction, _elementRef, delta) => {
    setResizing(false)
    if ((rightPanel.width || 0) + delta.width <= RIGHT_PANEL_MIN_WIDTH) {
      setRightPanelLayout({
        hidden: true
      })
      return
    }
    setRightPanelLayout({
      width: (rightPanel.width || 0) + delta.width
    })
  }

  const panelKey = useMemo(() => {
    if (dataServiceGuideStep === 4) {
      return 'Properties'
    } else if (dataServiceGuideStep === 5) {
      return 'Params'
    } else {
      return panelOpenedKey
    }
  }, [dataServiceGuideStep, panelOpenedKey])

  return (
    <ResizableContainer
      className={resizing ? '' : commonClasses.resizerContainer}
      enable={{
        top: false,
        left: rightPanel.hidden ? false : true,
        bottom: false,
        right: false,
        topRight: false,
        bottomRight: false,
        bottomLeft: false,
        topLeft: false
      }}
      size={{ width: rightPanel.hidden ? 0 : (rightPanel.width ?? RIGHT_PANEL_DEFAULT_WIDTH), height: '100%' }}
      handleClasses={{ left: commonClasses.resizer }}
      onResize={onResize}
      onResizeStop={onResizeStop}
      minWidth={rightPanel.hidden ? 0 : RIGHT_PANEL_MIN_WIDTH}
      maxWidth="50%"
    >
      <Box
        sx={(theme) => ({
          height: '100%',
          borderLeft: `1px solid ${theme.colors.carbon[3]}`
        })}
      >
        <Tabs
          value={panelKey}
          styles={(theme) => ({
            root: {
              display: 'flex',
              flexDirection: 'column',
              height: '100%'
            },
            list: {
              border: 'none',
              gap: 16,
              padding: '16px 16px 2px',
              '&::before': {
                'border-style': 'none'
              }
            },
            tab: {
              flex: '0 !important'
            },
            panel: {
              flex: 1,
              overflow: panelOpenedKey === 'Properties' ? 'hidden' : 'auto',
              backgroundColor: theme.white
            }
          })}
          onChange={(val: string) => {
            eventTracking('DataService panel tab clicked', {
              val
            })
            setPanelOpenedKey(val)
          }}
        >
          <Tabs.List grow data-guide="tab">
            <Tabs.Tab value="Properties">Properties</Tabs.Tab>
            <Tabs.Tab value="Params">Params</Tabs.Tab>
            <Tabs.Tab value="Schema">Schema</Tabs.Tab>
          </Tabs.List>

          <Tabs.Panel value="Properties">
            <Properties resizing={resizing} />
          </Tabs.Panel>
          <Tabs.Panel value="Params">
            {editEndpoint?.type === 'system-data' ? <SystemDataParams args={editEndpoint.args} /> : <Params />}
          </Tabs.Panel>
          <Tabs.Panel value="Schema">
            {!editEndpoint?.cluster_id || editEndpoint?.cluster_id === '0' ? (
              <Alert color="yellow" c="yellow">
                <Typography variant="title-md" c="yellow.8">
                  Pick a cluster and database to get started
                </Typography>
                <Typography c="yellow.8" mt={16}>
                  Browse the contents of your databases, tables and columns.
                </Typography>
              </Alert>
            ) : (
              <DatabaseList />
            )}
          </Tabs.Panel>
        </Tabs>
      </Box>
    </ResizableContainer>
  )
}

export default SideMenu
