<script setup lang="ts">
import type { SkillCategory, SkillInfo } from './types';

import { computed, markRaw, onMounted, reactive, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';

import { downloadFileFromBlob, formatDate } from '@easyflow/utils';

import {
  CopyDocument,
  Delete,
  Download,
  Edit,
  MoreFilled,
  Plus,
  Upload,
} from '@element-plus/icons-vue';
import {
  ElButton,
  ElDialog,
  ElDropdown,
  ElDropdownItem,
  ElDropdownMenu,
  ElEmpty,
  ElForm,
  ElFormItem,
  ElInput,
  ElMessage,
  ElMessageBox,
  ElOption,
  ElSelect,
  ElTable,
  ElTableColumn,
  ElTag,
} from 'element-plus';

import { hasPermission } from '#/api/common/hasPermission';
import HeaderSearch from '#/components/headerSearch/HeaderSearch.vue';
import PageData from '#/components/page/PageData.vue';
import PageSide from '#/components/page/PageSide.vue';
import {
  buildListRouteFullPath,
  mergeListRouteStateQuery,
  parseListRouteState,
  watchListRouteState,
} from '#/composables/useListRouteState';
import { $t } from '#/locales';
import { withListReturnTo } from '#/router/list-return-context';
import {
  canAiResourceDelete,
  canAiResourceOffline,
  canAiResourcePublish,
  canAiResourceRepublish,
} from '#/views/ai/shared/publish-status';

import {
  copySkill,
  deleteSkillCategory,
  exportSkills,
  getSkillCategories,
  submitSkillDeleteApproval,
  submitSkillOfflineApproval,
  submitSkillPublishApproval,
  validateSkillForPublish,
} from './api';
import {
  isSkillAccessDeniedError,
  resolveSkillApiErrorMessage,
} from './skill-api-error';
import { flattenSkillCategories } from './skill-category';
import { skillListRouteSchema } from './skill-list-route-state';
import SkillCategoryFormDialog from './SkillCategoryFormDialog.vue';
import SkillCreateDialog from './SkillCreateDialog.vue';

const route = useRoute();
const router = useRouter();
const initialState = parseListRouteState(route.query, skillListRouteSchema);
const pageDataRef = ref<any>();
const headerSearchRef = ref<{ reset: () => void }>();
const categories = ref<SkillCategory[]>([]);
const categoryLoading = ref(false);
const selectedCategoryId = ref<number | string>(initialState.categoryId);
const currentPageNumber = ref(initialState.pageNumber);
const currentPageSize = ref(initialState.pageSize);
const filters = reactive({
  keyword: initialState.keyword,
  publishStatus: initialState.publishStatus,
  visibilityScope: initialState.visibilityScope,
});
const createDialogOpen = ref(false);
const createMode = ref<'import' | 'manual'>('manual');
const categoryDialogOpen = ref(false);
const editingCategory = ref<SkillCategory>();
const categoryAction = ref('');
const copyDialogOpen = ref(false);
const copyLoading = ref(false);
const publishDialogOpen = ref(false);
const publishReason = ref('');
const publishTarget = ref<SkillInfo>();
const rowAction = ref('');
const copyForm = reactive({
  categoryId: '' as number | string,
  displayName: '',
  name: '',
  sourceId: '' as number | string,
});

const canCreate = computed(() => hasPermission(['/api/v1/skill/save']));
const canImport = computed(() => hasPermission(['/api/v1/skill/import']));
const canView = computed(() => hasPermission(['/api/v1/skill/getDetail']));
const canUpdate = computed(() => hasPermission(['/api/v1/skill/update']));
const canExport = computed(() => hasPermission(['/api/v1/skill/export']));
const canCopy = computed(() => canCreate.value);
const canPublish = computed(() =>
  hasPermission(['/api/v1/skill/submitPublishApproval']),
);
const canOffline = computed(() =>
  hasPermission(['/api/v1/skill/submitOfflineApproval']),
);
const canDelete = computed(() =>
  hasPermission(['/api/v1/skill/submitDeleteApproval']),
);
const canManageCategories = computed(() =>
  hasPermission(['/api/v1/skill/category']),
);
const flatCategories = computed(() => flattenSkillCategories(categories.value));
const categoryMenus = computed<SkillCategory[]>(() => [
  { categoryName: $t('common.allCategories'), id: '', status: 1 },
  ...categories.value,
]);
const hasFilters = computed(() =>
  Boolean(
    selectedCategoryId.value ||
      filters.keyword.trim() ||
      filters.publishStatus ||
      filters.visibilityScope,
  ),
);
const headerButtons = computed(() => [
  {
    data: { action: 'import' },
    icon: markRaw(Upload),
    key: 'import',
    permission: '/api/v1/skill/import',
    text: '批量导入',
  },
  {
    data: { action: 'create' },
    icon: markRaw(Plus),
    key: 'create',
    permission: '/api/v1/skill/save',
    text: '新建技能',
    type: 'primary',
  },
]);
const categoryControlButtons = computed(() =>
  canManageCategories.value
    ? [
        { icon: markRaw(Edit), label: '编辑', onClick: openCategoryDialog },
        {
          icon: markRaw(Delete),
          label: '删除',
          onClick: removeCategory,
          type: 'danger',
        },
      ]
    : [],
);
const categoryFooterButton = computed(() =>
  canManageCategories.value
    ? {
        icon: markRaw(Plus),
        label: '添加',
        onClick: () => openCategoryDialog(),
      }
    : undefined,
);

watchListRouteState(route, skillListRouteSchema, (state) => {
  selectedCategoryId.value = state.categoryId;
  filters.keyword = state.keyword;
  filters.publishStatus = state.publishStatus;
  filters.visibilityScope = state.visibilityScope;
  currentPageNumber.value = state.pageNumber;
  currentPageSize.value = state.pageSize;
  pageDataRef.value?.restoreState?.({
    pageNumber: state.pageNumber,
    pageSize: state.pageSize,
    queryParams: queryParams(),
  });
});

onMounted(loadCategories);

async function loadCategories() {
  categoryLoading.value = true;
  try {
    const response = await getSkillCategories();
    if (response.errorCode !== 0) throw new Error(response.message);
    categories.value = response.data || [];
  } catch (error) {
    categories.value = [];
    ElMessage.error(resolveSkillApiErrorMessage(error, '分类加载失败，请重试'));
  } finally {
    categoryLoading.value = false;
  }
}

function queryParams() {
  return {
    categoryId: selectedCategoryId.value || undefined,
    keyword: filters.keyword || undefined,
    publishStatus: filters.publishStatus || undefined,
    visibilityScope: filters.visibilityScope || undefined,
  };
}

function applyFilters() {
  pageDataRef.value?.setQuery?.(queryParams());
}

function handleSearch(keyword: string) {
  filters.keyword = keyword;
  applyFilters();
}

function clearFilters() {
  selectedCategoryId.value = '';
  filters.publishStatus = '';
  filters.visibilityScope = '';
  filters.keyword = '';
  headerSearchRef.value?.reset();
  applyFilters();
}

function selectCategory(category?: SkillCategory) {
  selectedCategoryId.value = category?.id || '';
  applyFilters();
}

function handleHeaderAction(payload: { key?: string }) {
  if (payload.key === 'import') openCreate('import');
  if (payload.key === 'create') openCreate('manual');
}

function openCreate(nextMode: 'import' | 'manual') {
  if (nextMode === 'import' && !canImport.value) return;
  if (nextMode === 'manual' && !canCreate.value) return;
  createMode.value = nextMode;
  createDialogOpen.value = true;
}

function openDetail(row: SkillInfo) {
  if (!canView.value || !row.id) return;
  void router.push({
    path: `/ai/skill/detail/${row.id}`,
    query: {
      navTitle: row.displayName || row.name || '技能',
      pageKey: '/ai/skill',
      ...withListReturnTo(currentListFullPath()),
    },
  });
}

function currentListFullPath() {
  return buildListRouteFullPath(
    router,
    route.query,
    {
      categoryId: String(selectedCategoryId.value || ''),
      keyword: filters.keyword,
      pageNumber: currentPageNumber.value,
      pageSize: currentPageSize.value,
      publishStatus: filters.publishStatus,
      visibilityScope: filters.visibilityScope,
    },
    skillListRouteSchema,
  );
}

function handlePageStateChange(state: {
  pageNumber: number;
  pageSize: number;
}) {
  currentPageNumber.value = state.pageNumber;
  currentPageSize.value = state.pageSize;
  const query = mergeListRouteStateQuery(
    route.query,
    {
      categoryId: String(selectedCategoryId.value || ''),
      keyword: filters.keyword,
      pageNumber: state.pageNumber,
      pageSize: state.pageSize,
      publishStatus: filters.publishStatus,
      visibilityScope: filters.visibilityScope,
    },
    skillListRouteSchema,
  );
  const target = router.resolve({ path: skillListRouteSchema.path, query });
  if (target.fullPath !== route.fullPath) void router.replace(target);
}

function scopeMeta(scope?: string) {
  return {
    DEPT: { label: '部门', type: 'primary' as const },
    PRIVATE: { label: '个人', type: 'success' as const },
    PUBLIC: { label: '全部', type: 'info' as const },
  }[scope || 'PRIVATE']!;
}

function rowPrimaryLabel(row: SkillInfo) {
  return row.manageable !== false && canUpdate.value ? '编辑' : '查看';
}

function canPublishRow(row: SkillInfo) {
  return (
    row.manageable !== false &&
    canPublish.value &&
    (canAiResourcePublish(row.displayPublishStatus, row.publishStatus) ||
      canAiResourceRepublish(row.displayPublishStatus, row.publishStatus))
  );
}

function rowPublishLabel(row: SkillInfo) {
  return canAiResourceRepublish(row.displayPublishStatus, row.publishStatus)
    ? '重新发布'
    : '发布';
}

function rowPublishButtonType(row: SkillInfo): 'success' | 'warning' {
  return canAiResourceRepublish(row.displayPublishStatus, row.publishStatus)
    ? 'warning'
    : 'success';
}

function canOfflineRow(row: SkillInfo) {
  return (
    row.manageable !== false &&
    canOffline.value &&
    canAiResourceOffline(row.displayPublishStatus, row.publishStatus)
  );
}

function canDeleteRow(row: SkillInfo) {
  return (
    row.manageable !== false &&
    canDelete.value &&
    canAiResourceDelete(row.displayPublishStatus, row.publishStatus)
  );
}

function isPublishRowBusy(row: SkillInfo) {
  return (
    rowAction.value === `publish:${row.id}` ||
    rowAction.value === `validate:${row.id}`
  );
}

function isMoreActionBusy(row: SkillInfo) {
  return !isPublishRowBusy(row) && rowAction.value.endsWith(`:${row.id}`);
}

async function openPublishDialog(row: SkillInfo) {
  if (!row.id || !canPublishRow(row) || rowAction.value) return;
  rowAction.value = `validate:${row.id}`;
  try {
    const response = await validateSkillForPublish(row.id);
    if (response.errorCode !== 0) return;
    if (!response.data.valid) {
      const issue = response.data.issues?.find(
        (item) => item.severity === 'ERROR',
      );
      ElMessage.warning(
        issue?.message
          ? `发布校验未通过：${issue.message}`
          : '发布校验未通过，请编辑技能后重试',
      );
      return;
    }
    publishTarget.value = row;
    publishReason.value = '';
    publishDialogOpen.value = true;
  } finally {
    rowAction.value = '';
  }
}

async function confirmPublish() {
  const target = publishTarget.value;
  const reason = publishReason.value.trim();
  if (!target?.id || rowAction.value) return;
  if (!reason) {
    ElMessage.warning('请输入发布说明');
    return;
  }
  if (reason.length > 500) return;
  rowAction.value = `publish:${target.id}`;
  try {
    const response = await submitSkillPublishApproval(target.id, reason);
    if (response.errorCode !== 0) return;
    publishDialogOpen.value = false;
    publishTarget.value = undefined;
    pageDataRef.value?.reload?.();
    ElMessage.success(response.message || '已提交发布');
  } finally {
    rowAction.value = '';
  }
}

async function handleRowCommand(command: string, row: SkillInfo) {
  if (command === 'copy') return openCopy(row);
  if (command === 'export') return exportOne(row);
  if (command === 'offline') return offline(row);
  if (command === 'delete') return remove(row);
}

function openCopy(row: SkillInfo) {
  if (!row.id) return;
  Object.assign(copyForm, {
    categoryId: row.categoryId || '',
    displayName: `${row.displayName || row.name || '技能'} 副本`,
    name: `${row.name || 'skill'}-copy`,
    sourceId: row.id,
  });
  copyDialogOpen.value = true;
}

async function confirmCopy() {
  if (copyLoading.value) return;
  if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(copyForm.name.trim())) {
    ElMessage.warning('标准名称仅支持小写字母、数字和连字符');
    return;
  }
  copyLoading.value = true;
  try {
    const response = await copySkill({
      categoryId: copyForm.categoryId || undefined,
      displayName: copyForm.displayName.trim(),
      name: copyForm.name.trim(),
      sourceId: copyForm.sourceId,
    });
    if (response.errorCode !== 0) return;
    copyDialogOpen.value = false;
    pageDataRef.value?.reload?.();
    ElMessage.success('已复制为草稿');
  } finally {
    copyLoading.value = false;
  }
}

async function exportOne(row: SkillInfo) {
  if (!row.id || rowAction.value) return;
  rowAction.value = `export:${row.id}`;
  try {
    const blob = await exportSkills([row.id]);
    downloadFileFromBlob({
      fileName: `${row.name || 'skill'}.zip`,
      source: blob,
    });
  } finally {
    rowAction.value = '';
  }
}

async function offline(row: SkillInfo) {
  if (!row.id || rowAction.value) return;
  try {
    await ElMessageBox.confirm('下架后将不可继续使用，确认下架？', '下架技能', {
      cancelButtonText: '取消',
      confirmButtonText: '下架',
      type: 'warning',
    });
  } catch {
    return;
  }
  rowAction.value = `offline:${row.id}`;
  try {
    const response = await submitSkillOfflineApproval(row.id);
    if (response.errorCode === 0) pageDataRef.value?.reload?.();
  } finally {
    rowAction.value = '';
  }
}

async function remove(row: SkillInfo) {
  if (!row.id || rowAction.value) return;
  try {
    await ElMessageBox.confirm('删除后无法恢复，确认删除？', '删除技能', {
      cancelButtonText: '取消',
      confirmButtonText: '删除',
      type: 'warning',
    });
  } catch {
    return;
  }
  rowAction.value = `delete:${row.id}`;
  try {
    const response = await submitSkillDeleteApproval(row.id);
    if (response.errorCode === 0) pageDataRef.value?.reload?.();
  } finally {
    rowAction.value = '';
  }
}

function openCategoryDialog(category?: SkillCategory) {
  editingCategory.value = category ? { ...category } : undefined;
  categoryDialogOpen.value = true;
}

async function removeCategory(category: SkillCategory) {
  if (categoryAction.value) return;
  try {
    await ElMessageBox.confirm(
      `确认删除分类“${category.categoryName}”？`,
      '删除分类',
      {
        cancelButtonText: '取消',
        confirmButtonText: '删除',
        type: 'warning',
      },
    );
  } catch {
    return;
  }
  categoryAction.value = `delete:${category.id}`;
  try {
    const response = await deleteSkillCategory(category.id);
    if (response.errorCode !== 0) throw new Error(response.message);
    await loadCategories();
    pageDataRef.value?.reload?.();
  } catch (error) {
    ElMessage.error(resolveSkillApiErrorMessage(error, '分类删除失败，请重试'));
  } finally {
    categoryAction.value = '';
  }
}

async function handleCategorySaved() {
  await loadCategories();
  pageDataRef.value?.reload?.();
}
</script>

<template>
  <div class="skill-list-page">
    <HeaderSearch
      ref="headerSearchRef"
      :buttons="headerButtons"
      :initial-value="filters.keyword"
      search-placeholder="搜索技能名称、用途或创建人"
      @search="handleSearch"
      @button-click="handleHeaderAction"
    >
      <template #middle>
        <ElSelect
          v-model="selectedCategoryId"
          class="skill-list-page__mobile-category"
          aria-label="技能分类"
          placeholder="分类：全部"
          @change="applyFilters"
        >
          <ElOption label="全部分类" value="" />
          <ElOption
            v-for="category in flatCategories"
            :key="category.id"
            :label="`${'\u3000'.repeat(category.depth)}${category.categoryName}`"
            :value="category.id"
          />
        </ElSelect>
        <ElSelect
          v-model="filters.visibilityScope"
          class="skill-list-page__filter"
          placeholder="范围：全部"
          clearable
          @change="applyFilters"
        >
          <ElOption label="个人" value="PRIVATE" />
          <ElOption label="部门" value="DEPT" />
          <ElOption label="全部" value="PUBLIC" />
        </ElSelect>
        <ElSelect
          v-model="filters.publishStatus"
          class="skill-list-page__filter"
          placeholder="状态：全部"
          clearable
          @change="applyFilters"
        >
          <ElOption label="草稿" value="DRAFT" />
          <ElOption label="待审核" value="PUBLISH_PENDING" />
          <ElOption label="已发布" value="PUBLISHED" />
          <ElOption label="已下线" value="OFFLINE" />
        </ElSelect>
      </template>
    </HeaderSearch>

    <section class="skill-list-page__workspace">
      <PageSide
        v-loading="categoryLoading"
        aria-label="技能分类"
        children-key="children"
        :control-btns="categoryControlButtons"
        :default-selected="selectedCategoryId"
        :footer-button="categoryFooterButton"
        label-key="categoryName"
        :menus="categoryMenus"
        value-key="id"
        @change="selectCategory"
      />

      <main class="skill-list-page__content">
        <PageData
          ref="pageDataRef"
          page-url="/api/v1/skill/page"
          :page-size="initialState.pageSize"
          :page-sizes="[10, 20, 50]"
          :initial-page-number="initialState.pageNumber"
          :initial-query-params="queryParams()"
          @state-change="handlePageStateChange"
        >
          <template #default="{ pageList }">
            <ElTable
              :data="pageList"
              row-key="id"
              class="skill-list-page__table"
              @row-dblclick="openDetail"
            >
              <ElTableColumn label="技能" min-width="184">
                <template #default="{ row }">
                  <button
                    type="button"
                    class="skill-list-page__identity"
                    @click="openDetail(row)"
                  >
                    <span aria-hidden="true">S</span>
                    <strong>{{ row.displayName || row.name }}</strong>
                  </button>
                </template>
              </ElTableColumn>
              <ElTableColumn
                prop="description"
                label="用途"
                min-width="224"
                show-overflow-tooltip
              >
                <template #default="{ row }">
                  {{ row.description || '—' }}
                </template>
              </ElTableColumn>
              <ElTableColumn label="创建人" min-width="168">
                <template #default="{ row }">
                  <div class="skill-list-page__creator">
                    <span>{{ row.createdByName || '—' }}</span>
                    <small>{{
                      row.created ? formatDate(row.created, 'YYYY-MM-DD') : ''
                    }}</small>
                  </div>
                </template>
              </ElTableColumn>
              <ElTableColumn label="范围" width="88">
                <template #default="{ row }">
                  <ElTag
                    :type="scopeMeta(row.visibilityScope).type"
                    effect="plain"
                  >
                    {{ scopeMeta(row.visibilityScope).label }}
                  </ElTag>
                </template>
              </ElTableColumn>
              <ElTableColumn label="操作" width="208" fixed="right">
                <template #default="{ row }">
                  <div class="skill-list-page__actions">
                    <ElButton text type="primary" @click="openDetail(row)">
                      {{ rowPrimaryLabel(row) }}
                    </ElButton>
                    <ElButton
                      v-if="canPublishRow(row)"
                      text
                      :type="rowPublishButtonType(row)"
                      :disabled="Boolean(rowAction)"
                      :loading="isPublishRowBusy(row)"
                      @click="openPublishDialog(row)"
                    >
                      {{ rowPublishLabel(row) }}
                    </ElButton>
                    <ElDropdown
                      v-if="
                        canExport ||
                        canCopy ||
                        canOfflineRow(row) ||
                        canDeleteRow(row)
                      "
                      :disabled="Boolean(rowAction)"
                      @command="handleRowCommand($event, row)"
                    >
                      <ElButton
                        text
                        :icon="MoreFilled"
                        aria-label="更多操作"
                        :loading="isMoreActionBusy(row)"
                      />
                      <template #dropdown>
                        <ElDropdownMenu>
                          <ElDropdownItem
                            v-if="canCopy"
                            command="copy"
                            :icon="CopyDocument"
                          >
                            复制
                          </ElDropdownItem>
                          <ElDropdownItem
                            v-if="canExport"
                            command="export"
                            :icon="Download"
                          >
                            导出
                          </ElDropdownItem>
                          <ElDropdownItem
                            v-if="canOfflineRow(row)"
                            command="offline"
                          >
                            <span class="skill-list-page__danger-action">
                              下架
                            </span>
                          </ElDropdownItem>
                          <ElDropdownItem
                            v-if="canDeleteRow(row)"
                            command="delete"
                            :icon="Delete"
                            divided
                          >
                            删除
                          </ElDropdownItem>
                        </ElDropdownMenu>
                      </template>
                    </ElDropdown>
                  </div>
                </template>
              </ElTableColumn>
            </ElTable>
          </template>
          <template #empty>
            <ElEmpty :description="hasFilters ? '没有匹配的技能' : '暂无技能'">
              <ElButton v-if="hasFilters" @click="clearFilters">
                清除筛选
              </ElButton>
              <ElButton
                v-else-if="canCreate"
                type="primary"
                @click="openCreate('manual')"
              >
                新建技能
              </ElButton>
            </ElEmpty>
          </template>
          <template #error="{ error, retry }">
            <ElEmpty
              :description="
                isSkillAccessDeniedError(error)
                  ? '没有查看权限'
                  : '加载失败，请重试'
              "
            >
              <ElButton v-if="!isSkillAccessDeniedError(error)" @click="retry">
                重新加载
              </ElButton>
            </ElEmpty>
          </template>
        </PageData>
      </main>
    </section>

    <SkillCreateDialog
      v-model="createDialogOpen"
      :categories="categories"
      :categories-loading="categoryLoading"
      :default-category-id="selectedCategoryId"
      :default-mode="createMode"
      @created="openDetail"
      @imported="pageDataRef?.reload?.()"
    />

    <SkillCategoryFormDialog
      v-if="canManageCategories"
      v-model="categoryDialogOpen"
      :category="editingCategory"
      @saved="handleCategorySaved"
    />

    <ElDialog
      v-model="copyDialogOpen"
      title="复制技能"
      width="min(480px, calc(100vw - 32px))"
      :close-on-click-modal="false"
    >
      <ElForm label-position="top">
        <ElFormItem label="标准名称" required>
          <ElInput v-model="copyForm.name" maxlength="64" />
        </ElFormItem>
        <ElFormItem label="显示名称" required>
          <ElInput v-model="copyForm.displayName" maxlength="128" />
        </ElFormItem>
        <ElFormItem label="分类">
          <ElSelect
            v-model="copyForm.categoryId"
            clearable
            placeholder="未分类"
          >
            <ElOption
              v-for="category in flatCategories"
              :key="category.id"
              :label="`${'\u3000'.repeat(category.depth)}${category.categoryName}`"
              :value="category.id"
            />
          </ElSelect>
        </ElFormItem>
      </ElForm>
      <template #footer>
        <ElButton :disabled="copyLoading" @click="copyDialogOpen = false">
          取消
        </ElButton>
        <ElButton type="primary" :loading="copyLoading" @click="confirmCopy">
          复制
        </ElButton>
      </template>
    </ElDialog>

    <ElDialog
      v-model="publishDialogOpen"
      width="min(520px, calc(100vw - 32px))"
      :close-on-click-modal="false"
      :close-on-press-escape="!rowAction.startsWith('publish:')"
      :show-close="!rowAction.startsWith('publish:')"
      :title="
        publishTarget ? `${rowPublishLabel(publishTarget)}技能` : '发布技能'
      "
    >
      <ElForm label-position="top">
        <ElFormItem label="发布说明" required>
          <ElInput
            v-model="publishReason"
            type="textarea"
            :rows="6"
            maxlength="500"
            show-word-limit
            placeholder="填写本次发布内容"
          />
        </ElFormItem>
      </ElForm>
      <template #footer>
        <ElButton
          :disabled="rowAction.startsWith('publish:')"
          @click="publishDialogOpen = false"
        >
          取消
        </ElButton>
        <ElButton
          :type="
            publishTarget ? rowPublishButtonType(publishTarget) : 'success'
          "
          :loading="rowAction.startsWith('publish:')"
          @click="confirmPublish"
        >
          {{ publishTarget ? rowPublishLabel(publishTarget) : '发布' }}
        </ElButton>
      </template>
    </ElDialog>
  </div>
</template>

<style scoped>
.skill-list-page {
  display: flex;
  flex-direction: column;
  gap: var(--space-6);
  height: 100%;
  min-height: 0;
  padding: var(--space-6);
}

.skill-list-page__filter {
  width: 160px;
}

.skill-list-page__mobile-category {
  display: none;
  width: 160px;
}

.skill-list-page__workspace {
  display: grid;
  flex: 1;
  grid-template-columns: 224px minmax(0, 1fr);
  gap: var(--space-6);
  min-height: 0;
  overflow: hidden;
}

.skill-list-page__content {
  min-width: 0;
  min-height: 0;
  overflow: hidden;
  background: hsl(var(--surface-panel));
  border: 1px solid hsl(var(--line-subtle));
  border-radius: var(--radius-panel);
}

.skill-list-page :deep(.page-data-container) {
  width: 100%;
  height: 100%;
  padding: 0;
}

.skill-list-page__table {
  height: 100%;
}

.skill-list-page__identity {
  display: flex;
  gap: var(--space-3);
  align-items: center;
  width: 100%;
  padding: 0;
  color: hsl(var(--foreground));
  text-align: left;
  cursor: pointer;
  background: transparent;
  border: 0;
}

.skill-list-page__identity > span {
  display: grid;
  flex: none;
  width: 34px;
  height: 34px;
  place-items: center;
  color: hsl(var(--nav-item-active-foreground));
  background: hsl(var(--nav-item-active));
  border-radius: var(--radius-control);
}

.skill-list-page__identity strong {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.skill-list-page__identity:focus-visible {
  outline: 2px solid hsl(var(--primary) / 72%);
  outline-offset: 3px;
}

.skill-list-page__creator {
  display: grid;
  gap: 2px;
}

.skill-list-page__creator small {
  color: hsl(var(--text-muted));
}

.skill-list-page__actions {
  display: flex;
  align-items: center;
}

.skill-list-page__danger-action {
  color: hsl(var(--destructive));
}

@media (max-width: 900px) {
  .skill-list-page {
    padding: var(--space-4);
  }

  .skill-list-page__workspace {
    grid-template-columns: minmax(0, 1fr);
  }

  .skill-list-page__workspace > :first-child {
    display: none;
  }

  .skill-list-page__mobile-category {
    display: block;
  }
}
</style>
