import Tabs from "@mui/material/Tabs"
import Tab from "@mui/material/Tab"
import Box from "@mui/material/Box"
import {useTheme} from "@mui/material/styles"
import {apply_flex} from "./utils"

export function render({model, view}) {
  const [active, setActive] = model.useState("active")
  const [centered] = model.useState("centered")
  const [closable] = model.useState("closable")
  const [color] = model.useState("color")
  const [disabled] = model.useState("disabled")
  const [location] = model.useState("tabs_location")
  const [names] = model.useState("_names")
  const [sx] = model.useState("sx")
  const [wrapped] = model.useState("wrapped")
  const headers = model.get_child("_headers")
  const objects = model.get_child("objects")

  const theme = useTheme()
  const contentRef = React.useRef(null)
  const [minHeight, setMinHeight] = React.useState(null)

  const handleChange = (event, newValue) => {
    // Capture current height before changing tabs
    if (contentRef.current) {
      const height = contentRef.current.scrollHeight
      setMinHeight(height > 0 ? height : 0)
    }
    setActive(newValue)
  }

  React.useLayoutEffect(() => {
    // Update min-height after new content is rendered
    if (contentRef.current) {
      // Use a small delay to allow content to fully render
      const timeoutId = setTimeout(() => {
        setMinHeight(0)
      }, 50)
      return () => clearTimeout(timeoutId)
    }
  }, [active])

  const orientation = (location === "above" || location === "below") ? "horizontal" : "vertical"

  const handleClose = (event, index) => {
    event.stopPropagation()
    if (index === active && index > objects.length - 2) {
      setActive(Math.max(0, objects.length - 2))
    }
    const newObjects = [...view.model.data.objects]
    newObjects.splice(index, 1)
    view.model.data.setv({objects: newObjects})
  }

  const tabs = (
    <Tabs
      centered={centered}
      indicatorColor={color}
      textColor={color}
      value={active}
      onChange={handleChange}
      orientation={orientation}
      scrollButtons="auto"
      TabIndicatorProps={{
        sx: {
          backgroundColor: theme.palette[color].main,
          ...(location === "right" && {left: 0, right: "auto", width: 3}),
          ...(location === "bottom" && {top: 0, bottom: "auto", height: 3}),
        },
      }}
      sx={{transition: "height 0.3s", ...sx}}
      variant="scrollable"
    >
      {names.map((label, index) => (
        <Tab
          key={index}
          disabled={disabled.includes(index)}
          label={
            closable ? (
              <Box sx={{display: "flex", alignItems: "center"}}>
                {label ? <span dangerouslySetInnerHTML={{__html: label}} />: headers[index]}
                <Box
                  component="span"
                  sx={{
                    ml: 1,
                    cursor: "pointer",
                    "&:hover": {opacity: 0.7}
                  }}
                  onClick={(e) => handleClose(e, index)}
                >
                  ✕
                </Box>
              </Box>
            ) : (label ? <span dangerouslySetInnerHTML={{__html: label}} /> : headers[index])
          }
          wrapped={wrapped}
        />
      ))}
    </Tabs>
  )
  const content = apply_flex(view.get_child_view(model.objects[active]), "column") || objects[active]

  return (
    <Box
      className="MuiTabsPanel"
      sx={{
        display: objects.length === 0 ? "none" : "flex",
        flexDirection: (location === "left" || location === "right") ? "row" : "column",
        height: "100%",
        maxWidth: "100%",
        position: "relative"
      }}
    >
      { (location === "left" || location === "above") && tabs }
      <Box
        key={`tab-content-${active}`}
        ref={contentRef}
        sx={{
          flex: 1,
          minHeight: minHeight ? `${minHeight}px` : 0,
          minWidth: 0,
          display: "flex",
          flexDirection: "column",
          overflow: "auto",
          position: "relative",
          width: "100%",
          opacity: 1,
          transition: theme.transitions.create(["opacity", "min-height"], {
            duration: theme.transitions.duration.short,
            easing: theme.transitions.easing.easeInOut
          })
        }}
      >
        {content}
      </Box>
      { (location === "right" || location === "below") && tabs }
    </Box>
  );
}
