<script lang="ts" setup>
import { Badge, Button, Empty, Input, Spin } from 'ant-design-vue';
import { PlusOutlined, SearchOutlined } from '@ant-design/icons-vue';

import InlineFieldEditor from '#/views/system/process/components/inline-field-editor.vue';

import type { TreeSidebarRow } from './types';

export type { TreeSidebarRow };

withDefaults(
  defineProps<{
    addLabel: string;
    emptyText: string;
    filteredLevel1: TreeSidebarRow[];
    keyword: string;
    loading: boolean;
    searchPlaceholder: string;
    selectedLevel1Id: number | null;
    title: string;
    totalCount: number;
  }>(),
  {
    addLabel: '新增',
    emptyText: '暂无数据',
    searchPlaceholder: '搜索名称',
    title: '分类',
  },
);

const emit = defineEmits<{
  addLevel1: [];
  contextmenu: [event: MouseEvent, row: TreeSidebarRow];
  saveName: [row: TreeSidebarRow, name: string];
  select: [id: number];
  'update:keyword': [value: string];
}>();
</script>

<template>
  <aside
    class="flex w-[240px] shrink-0 flex-col rounded-lg border border-border bg-card p-3"
  >
    <div class="mb-3 flex items-center justify-between gap-2">
      <span class="text-sm font-medium text-foreground">{{ title }}</span>
      <Badge
        :count="totalCount"
        :number-style="{ backgroundColor: 'hsl(var(--primary))' }"
        :overflow-count="999"
        show-zero
      />
    </div>

    <Button block class="mb-3" type="primary" @click="emit('addLevel1')">
      <PlusOutlined />
      {{ addLabel }}
    </Button>

    <Input
      :value="keyword"
      allow-clear
      class="mb-3"
      :placeholder="searchPlaceholder"
      @update:value="(val) => emit('update:keyword', val ?? '')"
    >
      <template #prefix>
        <SearchOutlined class="text-muted-foreground" />
      </template>
    </Input>

    <Spin :spinning="loading">
      <div
        v-if="filteredLevel1.length"
        class="flex max-h-[calc(100vh-300px)] flex-col gap-1 overflow-auto"
      >
        <div
          v-for="item in filteredLevel1"
          :key="item.id"
          class="relative cursor-pointer rounded-md py-2.5 pl-3 pr-2 transition-colors duration-200 hover:bg-muted/50"
          :class="{
            'bg-primary/10 ring-1 ring-primary/20': selectedLevel1Id === item.id,
          }"
          @click="emit('select', item.id)"
          @contextmenu="emit('contextmenu', $event, item)"
        >
          <span
            v-if="selectedLevel1Id === item.id"
            class="absolute bottom-2 left-0 top-2 w-[3px] rounded-full bg-primary"
          />
          <InlineFieldEditor
            :value="item.name"
            @click.stop
            @save="(val) => emit('saveName', item, String(val))"
          />
        </div>
      </div>
      <Empty v-else :description="emptyText" />
    </Spin>
  </aside>
</template>
