import { computed, onMounted, ref } from 'vue';

import type { FileTypeItem } from '#/api/core/file-gallery';
import { getFileTypes } from '#/api/core/file-gallery';

export const ALL_TYPE_VALUE = -1;

import { ALL_TYPE_ICON } from '#/composables/use-file-type-icon';

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

export function useFileGalleryFilter(storageKey: string) {
  const fileTypes = ref<FileTypeItem[]>([]);
  const activeType = ref<number>(ALL_TYPE_VALUE);
  const keyword = ref('');
  const typesLoading = ref(false);

  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,
    })),
  ]);

  function restoreActiveType() {
    const saved = localStorage.getItem(storageKey);
    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(storageKey, String(value));
  }

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

    if (activeType.value !== ALL_TYPE_VALUE) {
      params.type = activeType.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();
  });

  return {
    fileTypes,
    activeType,
    keyword,
    typesLoading,
    tabs,
    setActiveType,
    buildListParams,
    loadFileTypes,
  };
}
