<script setup lang="ts">
import { breakpointsTailwind } from '@vueuse/core'

const props = withDefaults(
  defineProps<{
    modelValue?: boolean
    collapsible?: boolean
    side?: 'left' | 'right'
    grow?: boolean
    width?: number
    resizable?: boolean | object
  }>(),
  {
    side: 'left',
  },
)
const emit = defineEmits(['update:modelValue'])
const { isDashboardSidebarSliderOpen } = useProState()
const breakpoints = useBreakpoints(breakpointsTailwind)
const smallerThanLg = breakpoints.smaller('lg')
const id = useId()
const { el, width, onDrag } = props.resizable
  ? useResizable(id, {
    ...(typeof props.resizable === 'object' ? props.resizable : {}),
    value: props.width,
  })
  : {
      el: undefined,
      width: toRef(props.width),
      onDrag: undefined,
      isDragging: undefined,
    }

const isOpen = computed({
  get() {
    return props.modelValue !== undefined
      ? props.modelValue
      : isDashboardSidebarSliderOpen.value
  },
  set(value) {
    props.modelValue !== undefined
      ? emit('update:modelValue', value)
      : (isDashboardSidebarSliderOpen.value = value)
  },
})

provide('isOpen', isOpen)
</script>

<template>
  <div
    ref="el"
    :class="
      cn(
        'flex-col items-stretch relative w-full',
        [
          grow
            ? 'flex-1'
            : 'border-b lg:border-b-0 lg:border-r border-border lg:w-[--width] flex-shrink-0',
          collapsible ? 'hidden lg:flex' : 'flex',
        ],
        $attrs.class ?? '',
      )
    "
    :style="{ '--width': width && !grow ? `${width}px` : undefined }"
  >
    <slot />
    <slot name="handle">
      <UiDashboardPanelHandle v-if="resizable && !grow" @mousedown="onDrag" />
    </slot>

    <Sheet v-if="collapsible && smallerThanLg" v-model:open="isOpen">
      <SheetContent
        :side="side"
        class="lg:hidden p-0 [&>button]:hidden w-full flex flex-col"
      >
        <slot />
      </SheetContent>
    </Sheet>
  </div>
</template>
