import { Box, Flex } from '@tidbcloud/uikit'
import { useMediaQuery } from '@tidbcloud/uikit/hooks'
import { useMemo } from 'react'

const RIGHT_PANEL_WIDTHS = {
  sm: 360, // [960, 1440)
  md: 400, // [1440, 1920)
  lg: 560 // >= 1920
}

const LEFT_FORM_MAX_WIDTH = 1072

interface TwoPaneLayoutProps {
  visible: boolean
  header: React.ReactNode
  rightSection: React.ReactNode
  contentBottomPadding?: number
}

export const TwoPaneLayout = ({
  children,
  contentBottomPadding = 96,
  header,
  rightSection,
  visible
}: React.PropsWithChildren<TwoPaneLayoutProps>) => {
  const mdMatched = useMediaQuery('(min-width: 1440px) and (max-width: 1919px)')
  const lgMatched = useMediaQuery('(min-width: 1920px)')
  const over1920Matched = useMediaQuery('(min-width: 1921px)')

  const rightWidth = useMemo(() => {
    if (lgMatched) {
      return RIGHT_PANEL_WIDTHS.lg
    }
    if (mdMatched) {
      return RIGHT_PANEL_WIDTHS.md
    }
    return RIGHT_PANEL_WIDTHS.sm
  }, [lgMatched, mdMatched])

  return (
    <Flex
      align="stretch"
      gap={0}
      mod={{ hidden: !visible }}
      sx={{
        height: '100%',
        minHeight: 0,
        overflowY: 'auto',
        overflowX: 'hidden',
        '&[data-hidden]': {
          display: 'none'
        }
      }}
    >
      <Box sx={{ flex: 1 }}>
        {header}
        <Box
          px="xl"
          pb={contentBottomPadding}
          sx={
            over1920Matched
              ? {
                  maxWidth: LEFT_FORM_MAX_WIDTH,
                  marginLeft: 'auto',
                  marginRight: 'auto'
                }
              : undefined
          }
        >
          {children}
        </Box>
      </Box>

      <Box
        sx={{
          flexShrink: 0,
          width: rightWidth,
          position: 'sticky',
          top: 0,
          height: '100%',
          backgroundColor: 'var(--mantine-color-carbon-2)',
          borderLeft: `1px solid var(--mantine-color-carbon-3)`
        }}
      >
        <Box
          sx={(t) => ({
            height: '100%',
            display: 'flex',
            flexDirection: 'column',
            padding: t.spacing.xl
          })}
        >
          {rightSection}
        </Box>
      </Box>
    </Flex>
  )
}
