import { computed, onMounted, ref, toValue, type MaybeRefOrGetter } from 'vue';

import type { FileTypeItem } from '#/api/core/file-gallery';
import { getFileTypes } from '#/api/core/file-gallery';
import type { FileGroupOptionItem } from '#/api/core/file-group';
import { useFileGroupCache } from '#/composables/use-file-group-cache';
import { ALL_TYPE_ICON } from '#/composables/use-file-type-icon';

export const ALL_TYPE_VALUE = -1;

export const ALL_GROUP_VALUE = 0;

export interface FileGalleryTab {
  key: string;
  value: number;
  label: string;
  icon?: string;
}

/**
 * 文件库筛选（类型 tab + 分组 + 关键字）
 * @param storageKeyInput localStorage 键；支持动态 getter，便于按 acceptTypes 隔离记忆
 */
export function useFileGalleryFilter(
  storageKeyInput: MaybeRefOrGetter<string> = 'file-picker-active-type',
) {
  const fileTypes = ref<FileTypeItem[]>([]);
  const activeType = ref<number>(ALL_TYPE_VALUE);
  const activeGroupId = ref<number>(ALL_GROUP_VALUE);
  const keyword = ref('');
  const typesLoading = ref(false);

  const { groupOptions, loadGroupOptions } = useFileGroupCache();

  function resolveStorageKey() {
    return toValue(storageKeyInput);
  }

  const tabs = computed<FileGalleryTab[]>(() => [
    { key: 'all', value: ALL_TYPE_VALUE, label: '全部', icon: ALL_TYPE_ICON },
    ...fileTypes.value.map((item) => ({
      key: String(item.value),
      value: item.value,
      label: item.name,
      icon: item.icon,
    })),
  ]);

  /** 分组 Tab（独立于文件类型） */
  const groupTabs = computed<FileGalleryTab[]>(() => [
    { key: 'group-all', value: ALL_GROUP_VALUE, label: '全部分组' },
    ...groupOptions.value.map((item: FileGroupOptionItem) => ({
      key: `group-${item.id}`,
      value: item.id,
      label: item.name,
    })),
  ]);

  function restoreActiveType() {
    const saved = localStorage.getItem(resolveStorageKey());
    if (saved === null) {
      activeType.value = ALL_TYPE_VALUE;
      return;
    }
    const parsed = Number.parseInt(saved, 10);
    if (parsed === ALL_TYPE_VALUE) {
      activeType.value = ALL_TYPE_VALUE;
      return;
    }
    const exists = fileTypes.value.some((item) => item.value === parsed);
    activeType.value = exists ? parsed : ALL_TYPE_VALUE;
  }

  function setActiveType(value: number) {
    activeType.value = value;
    localStorage.setItem(resolveStorageKey(), String(value));
  }

  function setActiveGroupId(value: number) {
    activeGroupId.value = value;
  }

  function buildListParams(page: number, pageSize: number) {
    const params: {
      page: number;
      page_size: number;
      pid: number;
      type?: number;
      group_id?: number;
      keyword?: string;
    } = {
      page,
      page_size: pageSize,
      pid: 0,
    };

    if (activeType.value !== ALL_TYPE_VALUE) {
      params.type = activeType.value;
    }

    if (activeGroupId.value > 0) {
      params.group_id = activeGroupId.value;
    }

    const kw = keyword.value.trim();
    if (kw) {
      params.keyword = kw;
    }

    return params;
  }

  async function loadFileTypes() {
    typesLoading.value = true;
    try {
      const res = await getFileTypes();
      const data = (res as any)?.data ?? res;
      fileTypes.value = Array.isArray(data) ? data : [];
      restoreActiveType();
    } finally {
      typesLoading.value = false;
    }
  }

  onMounted(() => {
    void loadFileTypes();
    void loadGroupOptions();
  });

  return {
    fileTypes,
    activeType,
    activeGroupId,
    keyword,
    typesLoading,
    tabs,
    groupTabs,
    groupOptions,
    setActiveType,
    setActiveGroupId,
    buildListParams,
    loadFileTypes,
    loadGroupOptions,
  };
}
