<script setup lang="ts">
import type { CSSProperties } from 'vue';

import { computed, shallowRef, useSlots, watchEffect } from 'vue';

import { EasyFlowScrollbar } from '@easyflow-core/shadcn-ui';

import { useScrollLock } from '@vueuse/core';

import { SidebarCollapseButton, SidebarFixedButton } from './widgets';

interface Props {
  /**
   * 折叠区域高度
   * @default 42
   */
  collapseHeight?: number;
  /**
   * 折叠宽度
   * @default 48
   */
  collapseWidth?: number;
  /**
   * 隐藏的dom是否可见
   * @default true
   */
  domVisible?: boolean;
  /**
   * 扩展区域宽度
   */
  extraWidth: number;
  /**
   * 固定扩展区域
   * @default false
   */
  fixedExtra?: boolean;
  /**
   * 头部高度
   */
  headerHeight: number;
  /**
   * 是否侧边混合模式
   * @default false
   */
  isSidebarMixed?: boolean;
  /**
   * 顶部margin
   * @default 60
   */
  marginTop?: number;
  /**
   * 混合菜单宽度
   * @default 80
   */
  mixedWidth?: number;
  /**
   * 顶部padding
   * @default 60
   */
  paddingTop?: number;
  /**
   * 是否显示
   * @default true
   */
  show?: boolean;
  /**
   * 显示折叠按钮
   * @default true
   */
  showCollapseButton?: boolean;
  /**
   * 显示固定按钮
   * @default true
   */
  showFixedButton?: boolean;
  /**
   * 主题
   */
  theme: string;

  /**
   * 宽度
   */
  width: number;
  /**
   * zIndex
   * @default 0
   */
  zIndex?: number;
}

const props = withDefaults(defineProps<Props>(), {
  collapseHeight: 96,
  collapseWidth: 48,
  domVisible: true,
  fixedExtra: false,
  isSidebarMixed: false,
  marginTop: 0,
  mixedWidth: 70,
  paddingTop: 0,
  show: true,
  showCollapseButton: true,
  showFixedButton: true,
  zIndex: 0,
});

const emit = defineEmits<{ leave: [] }>();
const collapse = defineModel<boolean>('collapse');
const extraCollapse = defineModel<boolean>('extraCollapse');
const expandOnHovering = defineModel<boolean>('expandOnHovering');
const expandOnHover = defineModel<boolean>('expandOnHover');
const extraVisible = defineModel<boolean>('extraVisible');

const isLocked = useScrollLock(document.body);
const slots = useSlots();

const asideRef = shallowRef<HTMLDivElement | null>();

const hiddenSideStyle = computed((): CSSProperties => calcMenuWidthStyle(true));

const style = computed((): CSSProperties => {
  const { isSidebarMixed, marginTop, paddingTop, zIndex } = props;

  return {
    '--scroll-shadow': 'var(--surface-elevated)',
    backgroundColor: 'hsl(var(--nav-surface-subtle) / 0.16)',
    backgroundImage:
      'linear-gradient(180deg, hsl(var(--nav-surface) / 0.3) 0%, hsl(var(--nav-surface-subtle) / 0.2) 28%, hsl(var(--glass-tint) / 0.12) 100%)',
    backdropFilter: 'blur(calc(var(--glass-blur) * 1.5)) saturate(188%)',
    boxShadow:
      'inset 0 1px 0 hsl(var(--nav-sheen) / 0.14), inset -1px 0 0 hsl(var(--nav-border) / 0.08)',
    ...calcMenuWidthStyle(false),
    height: `calc(100% - ${marginTop}px)`,
    marginTop: `${marginTop}px`,
    paddingTop: `${paddingTop}px`,
    zIndex,
    ...(isSidebarMixed && extraVisible.value ? { transition: 'none' } : {}),
  };
});

const extraStyle = computed((): CSSProperties => {
  const { extraWidth, show, width, zIndex } = props;

  return {
    backgroundColor: 'hsl(var(--nav-surface-subtle) / 0.12)',
    backgroundImage:
      'linear-gradient(180deg, hsl(var(--nav-surface-subtle) / 0.24) 0%, hsl(var(--glass-tint) / 0.12) 100%)',
    backdropFilter: 'blur(calc(var(--glass-blur) * 1.34)) saturate(182%)',
    boxShadow:
      'inset 0 1px 0 hsl(var(--nav-sheen) / 0.12), inset -1px 0 0 hsl(var(--nav-border) / 0.08)',
    left: `${width}px`,
    width: extraVisible.value && show ? `${extraWidth}px` : 0,
    zIndex,
  };
});
const extraTitleStyle = computed((): CSSProperties => {
  const { headerHeight } = props;

  return {
    height: `${Math.max(headerHeight - 1, 0)}px`,
  };
});

const contentWidthStyle = computed((): CSSProperties => {
  const { collapseWidth, fixedExtra, isSidebarMixed, mixedWidth } = props;
  if (isSidebarMixed && fixedExtra) {
    return { width: `${collapse.value ? collapseWidth : mixedWidth}px` };
  }
  return {};
});

const contentStyle = computed((): CSSProperties => {
  const { collapseHeight, headerHeight } = props;

  return {
    height: `calc(100% - ${headerHeight + collapseHeight}px)`,
    paddingTop: headerHeight > 0 ? '10px' : '52px',
    ...contentWidthStyle.value,
  };
});

const headerStyle = computed((): CSSProperties => {
  const { headerHeight, isSidebarMixed } = props;

  return {
    ...(isSidebarMixed ? { display: 'flex', justifyContent: 'center' } : {}),
    height: `${Math.max(headerHeight - 1, 0)}px`,
    ...contentWidthStyle.value,
  };
});

const extraContentStyle = computed((): CSSProperties => {
  const { collapseHeight, headerHeight } = props;
  return {
    height: `calc(100% - ${headerHeight + collapseHeight}px)`,
    paddingTop: headerHeight > 0 ? '10px' : '52px',
  };
});

const toolStyle = computed((): CSSProperties => {
  return {
    top: `${Math.max(10, (props.headerHeight - 36) / 2)}px`,
  };
});
const pinToolStyle: CSSProperties = {
  bottom: '16px',
  left: '12px',
};

watchEffect(() => {
  extraVisible.value = props.fixedExtra ? true : extraVisible.value;
});

function calcMenuWidthStyle(isHiddenDom: boolean): CSSProperties {
  const { extraWidth, fixedExtra, isSidebarMixed, show, width } = props;

  let widthValue =
    width === 0
      ? '0px'
      : `${width + (isSidebarMixed && fixedExtra && extraVisible.value ? extraWidth : 0)}px`;

  const { collapseWidth } = props;

  if (isHiddenDom && expandOnHovering.value && !expandOnHover.value) {
    widthValue = `${collapseWidth}px`;
  }

  return {
    ...(widthValue === '0px' ? { overflow: 'hidden' } : {}),
    flex: `0 0 ${widthValue}`,
    marginLeft: show ? 0 : `-${widthValue}`,
    maxWidth: widthValue,
    minWidth: widthValue,
    width: widthValue,
  };
}

function handleMouseenter() {
  // 未开启和未折叠状态不生效
  if (expandOnHover.value) {
    return;
  }
  if (!expandOnHovering.value) {
    collapse.value = false;
  }
  if (props.isSidebarMixed) {
    isLocked.value = true;
  }
  expandOnHovering.value = true;
}

function handleMouseleave() {
  emit('leave');
  if (props.isSidebarMixed) {
    isLocked.value = false;
  }
  if (expandOnHover.value) {
    return;
  }

  expandOnHovering.value = false;
  collapse.value = true;
  extraVisible.value = false;
}

function handleFixedToggle(nextValue: boolean) {
  if (nextValue) {
    collapse.value = false;
    extraVisible.value = true;
    expandOnHovering.value = false;
    return;
  }

  collapse.value = true;
  extraVisible.value = false;
  expandOnHovering.value = false;
  if (props.isSidebarMixed) {
    isLocked.value = false;
  }
}
</script>

<template>
  <div
    v-if="domVisible"
    :class="theme"
    :style="hiddenSideStyle"
    class="h-full transition-all duration-150"
  ></div>
  <aside
    :class="[
      theme,
      {
        'bg-[hsl(var(--glass-tint))/0.72]': isSidebarMixed,
        'bg-[hsl(var(--glass-tint))/0.82]': !isSidebarMixed,
      },
    ]"
    :style="style"
    class="fixed left-0 top-0 h-full overflow-hidden transition-all duration-150"
    @mouseenter="handleMouseenter"
    @mouseleave="handleMouseleave"
  >
    <div v-if="slots.logo" :style="headerStyle" class="relative z-10 px-2 pt-2">
      <slot name="logo"></slot>
    </div>
    <EasyFlowScrollbar :style="contentStyle" class="relative z-10">
      <slot></slot>
    </EasyFlowScrollbar>

    <div
      v-if="!isSidebarMixed && showFixedButton"
      :style="pinToolStyle"
      class="absolute z-20 flex"
    >
      <SidebarFixedButton
        v-model:expand-on-hover="expandOnHover"
        @toggle="handleFixedToggle"
      />
    </div>
    <div
      v-if="isSidebarMixed"
      ref="asideRef"
      :style="extraStyle"
      class="fixed top-0 h-full overflow-hidden transition-all duration-200"
    >
      <div
        v-if="!extraCollapse"
        :style="extraTitleStyle"
        class="relative z-10 px-3"
      >
        <slot name="extra-title"></slot>
      </div>
      <EasyFlowScrollbar :style="extraContentStyle" class="relative z-10 py-2">
        <slot name="extra"></slot>
      </EasyFlowScrollbar>
      <div
        v-if="expandOnHover || !extraCollapse"
        :style="toolStyle"
        class="absolute right-3 z-20 flex flex-col gap-2"
      >
        <SidebarCollapseButton
          v-if="expandOnHover"
          v-model:collapsed="extraCollapse"
        />
        <SidebarFixedButton
          v-if="!extraCollapse"
          v-model:expand-on-hover="expandOnHover"
          @toggle="handleFixedToggle"
        />
      </div>
    </div>
  </aside>
</template>
