import { computed, defineComponent, TransitionGroup } from 'vue'
import useLayoutStore from '../useLayoutStore'
import { OhVueIcon, addIcons } from 'oh-vue-icons'
import { MdAdd } from 'oh-vue-icons/icons'
import useRouterStore from '@/useRouterStore'
import { globalToast } from '@/main'
import LinkBlock from './LinkBlock'
import useSortable, { dragging } from './useSortable'

addIcons(MdAdd)

export default defineComponent(() => {
  const layout = useLayoutStore()
  const router = useRouterStore()
  const container = useSortable(
    computed(() => layout.currentPage.list),
    'page'
  )

  return () => (
    <div
      class="absolute left-0 top-0 w-full h-screen overflow-y-auto no-scrollbar pt-[240px] px-[calc((100%_-_var(--main-width))_/_2)]"
      onScroll={(e) => {
        const h = (e.target as any).scrollTop
        if (h > 60) {
          // 需要移动搜索框和时间
          layout.isCompact = true
        } else {
          layout.isCompact = false
        }
      }}
      onDragover={(e) => e.preventDefault()}
      onDrop={() => {
        // 处理移入（当前有内容不可移入）
        if (!dragging.id) return
        if (dragging.type === 'dock') {
          const oldIdx = layout.state.dock.findIndex((el) => el?.id === dragging.id)
          if (oldIdx < 0) return
          const block = layout.state.dock[oldIdx]
          if (!block) return
          layout.currentPage.list.push(block)
          layout.state.dock[oldIdx] = null
          return
        }
        if (dragging.type && dragging.type !== 'dock') {
          // TODO: 文件夹
          return
        }
      }}
    >
      <div
        class="w-full grid justify-center grid-flow-row-dense pb-[200px]"
        style="grid-template-columns:repeat(auto-fill, var(--block-size));grid-auto-rows:var(--block-size)"
        ref={container}
      >
        <TransitionGroup>
          {layout.currentPage.list.map((block, idx) => (
            <div
              class="w-full h-full p-[var(--block-padding)] relative"
              key={block.id}
              id={block.id}
              style={{
                gridColumn: `span ${block.w}`,
                gridRow: `span ${block.h}`
              }}
              data-transportable={block.link && !block.link.startsWith('id:') ? '1' : ''}
              onDragover={(e) => e.preventDefault()}
              onDrop={() => {
                // 处理移入（当前有内容不可移入）
                if (!dragging.id) return
                if (dragging.type === 'dock') {
                  const oldIdx = layout.state.dock.findIndex((el) => el?.id === dragging.id)
                  if (oldIdx < 0) return
                  const block = layout.state.dock[oldIdx]
                  if (!block) return
                  layout.currentPage.list.splice(idx, 0, block)
                  layout.state.dock[oldIdx] = null
                  return
                }
                if (dragging.type && dragging.type !== 'dock') {
                  // TODO: 文件夹
                  return
                }
              }}
            >
              <div
                class="w-full h-full overflow-hidden relative cursor-pointer shadow-lg"
                style="border-radius:calc(var(--block-radius) * var(--block-size))"
              >
                {block.link ? (
                  block.link.startsWith('id:') ? (
                    // 文件夹
                    <div></div>
                  ) : (
                    // 链接
                    <LinkBlock block={block} />
                  )
                ) : (
                  // 小组件
                  <div></div>
                )}
              </div>
              <div
                class="absolute left-0 -bottom-2 text-sm text-white text-center w-full overflow-hidden text-ellipsis whitespace-nowrap break-all font-bold"
                style="text-shadow: 0 0 4px rgba(0,0,0,.6)"
              >
                {block.label}
              </div>
            </div>
          ))}
        </TransitionGroup>
        <div class="w-full h-full flex justify-center items-center p-[var(--block-padding)] relative operation-button">
          <div
            class="w-full h-full overflow-hidden rounded-[calc(var(--block-radius)_*_var(--block-size))] bg-white/80 backdrop-blur flex justify-center items-center cursor-pointer hover:scale-105 transition-all"
            onClick={() => {
              if (layout.state.content[layout.state.current].pages[layout.state.currentPage]) {
                router.path = 'global-adder'
              } else {
                globalToast.warning('请先添加页面')
              }
            }}
          >
            <span style="filter:drop-shadow(0 0 10px hsl(32, 90%, 65%))">
              <OhVueIcon name="md-add" fill="white" scale={2.4} />
            </span>
          </div>
        </div>
      </div>
    </div>
  )
})
