import { useRef, useState, useEffect, useCallback } from 'react'
import { Box, IconButton, Tooltip } from '@mui/material'
import type { ChatToolCodeAreaProps } from '../types'
import { CHAT_TOOL_CODE_AREA_MAX_HEIGHT } from '../const'
import { ChatToolFullViewDialog } from './chat-tool-full-view-dialog'
import { styles } from './styles'
import { OpenDiagonallyRight } from '@carto/meridian-ds/custom-icons'

export function ChatToolCodeArea({
  content,
  title = '',
  isError = false,
  labels = {},
  sx,
}: ChatToolCodeAreaProps) {
  const preRef = useRef<HTMLPreElement>(null)
  const [isOverflowing, setIsOverflowing] = useState(false)
  const [dialogOpen, setDialogOpen] = useState(false)

  const checkOverflow = useCallback(() => {
    const el = preRef.current
    if (el) {
      setIsOverflowing(el.scrollHeight > el.clientHeight)
    }
  }, [])

  useEffect(() => {
    checkOverflow()
    const el = preRef.current
    if (!el) return

    const observer = new ResizeObserver(checkOverflow)
    observer.observe(el)
    return () => observer.disconnect()
  }, [checkOverflow, content])

  const fullViewLabel = labels.fullView ?? 'Full view'

  return (
    <Box sx={{ ...styles.codeArea, ...sx }}>
      <Box
        component='pre'
        ref={preRef}
        sx={{
          ...styles.codeAreaPre,
          maxHeight: CHAT_TOOL_CODE_AREA_MAX_HEIGHT,
          ...(isError ? styles.codeAreaPreError : {}),
        }}
      >
        {content}
      </Box>
      {isOverflowing && (
        <Tooltip title={fullViewLabel}>
          <IconButton
            size='small'
            onClick={() => setDialogOpen(true)}
            sx={styles.codeAreaFullViewButton}
          >
            <OpenDiagonallyRight />
          </IconButton>
        </Tooltip>
      )}
      <ChatToolFullViewDialog
        open={dialogOpen}
        onClose={() => setDialogOpen(false)}
        title={title}
        content={content}
      />
    </Box>
  )
}
