import { computed, ref, type Ref } from 'vue';
import { message, Modal } from 'ant-design-vue';
import { ArrayUtils, ObjectUtils } from '@imengyu/imengyu-utils';
import type {
  IHomeCommonCategoryDefine,
  IHomeCommonCategoryDetailDefine,
  IHomeCommonCategoryHomeDefine,
  IHomeCommonCategoryListDefine,
} from '../../CommonCategoryDefine';

export type PageTemplateType = 'Home' | 'CommonList' | 'Details';

function createHomePageTemplate(): IHomeCommonCategoryHomeDefine {
  return {
    type: 'Home',
    props: {
      title: '首页',
      subTitle: '',
      homeBanner: '',
      homeButtons: [],
      categorys: [],
      tabs: [],
    },
  };
}

function createCommonListPageTemplate(): IHomeCommonCategoryListDefine {
  return {
    type: 'CommonList',
    props: {
      showTab: true,
      showSearch: true,
      showTotal: true,
      tabs: [],
    },
  };
}

function createDetailPageTemplate(): IHomeCommonCategoryDetailDefine {
  return {
    type: 'Details',
    props: {
      showHead: true,
      introBlockDescs: [],
      introBlocks: [],
      tabs: [],
    },
  };
}

export function usePageList(
  editorJson: Ref<IHomeCommonCategoryDefine>,
  selectedPage: Ref<(IHomeCommonCategoryDefine['page'][0]) | null>
) {
  const pageList = computed(() => editorJson.value?.page ?? []);

  function getUniquePageName(prefix: string): string {
    const pages = editorJson.value?.page ?? [];
    const names = new Set(pages.map(p => p.name));
    let name = prefix;
    let n = 1;
    while (names.has(name)) {
      name = `${prefix}_${n}`;
      n++;
    }
    return name;
  }

  function movePageUp(page: IHomeCommonCategoryDefine['page'][0]) {
    const pages = editorJson.value?.page ?? [];
    ArrayUtils.upData(pages, pages.indexOf(page));
  }

  function movePageDown(page: IHomeCommonCategoryDefine['page'][0]) {
    const pages = editorJson.value?.page ?? [];
    ArrayUtils.downData(pages, pages.indexOf(page));
  }

  function duplicatePage(page: IHomeCommonCategoryDefine['page'][0]) {
    const pages = editorJson.value?.page ?? [];
    const newPage = ObjectUtils.clone(page);
    newPage.name = getUniquePageName(newPage.name);
    newPage.title = newPage.title + ' (克隆)';
    ArrayUtils.insert(pages, pages.indexOf(page) + 1, newPage);
    selectedPage.value = newPage;
    message.success('已克隆页面');
  }

  function confirmDeletePage(page: IHomeCommonCategoryDefine['page'][0]) {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除页面「${page.title || page.name}」吗？删除后不可恢复。`,
      okText: '删除',
      okType: 'danger',
      cancelText: '取消',
      onOk() {
        const pages = editorJson.value?.page ?? [];
        const next = pages.filter(p => p.name !== page.name);
        editorJson.value = { ...editorJson.value, page: next };
        if (selectedPage.value?.name === page.name) {
          selectedPage.value = next[0] ?? null;
        }
        message.success('已删除页面');
      },
    });
  }

  // 添加页面弹窗
  const addPageModalVisible = ref(false);
  const addPageTemplate = ref<PageTemplateType | null>(null);
  const addPageKey = ref('');
  const addPageTitle = ref('');
  const addPageLoading = ref(false);

  const templateLabelMap: Record<PageTemplateType, string> = {
    Home: 'Home',
    CommonList: 'CommonList',
    Details: 'Details',
  };

  function onAddPageMenuClick(template: PageTemplateType) {
    addPageTemplate.value = template;
    const prefixMap = { Home: 'home', CommonList: 'list', Details: 'detail' } as const;
    const titleMap = { Home: '首页', CommonList: '列表页', Details: '详情页' } as const;
    addPageKey.value = getUniquePageName(prefixMap[template] ?? 'page');
    addPageTitle.value = titleMap[template] ?? '页面';
    addPageModalVisible.value = true;
  }

  function confirmAddPage(): Promise<void> {
    const key = addPageKey.value?.trim();
    const title = addPageTitle.value?.trim();
    if (!key) {
      message.warning('请输入 key');
      return Promise.reject();
    }
    if (!title) {
      message.warning('请输入 title');
      return Promise.reject();
    }
    const pages = editorJson.value?.page ?? [];
    if (pages.some(p => p.name === key)) {
      message.warning(`key「${key}」已存在，请使用其他 key`);
      return Promise.reject();
    }
    const template = addPageTemplate.value;
    if (!template) return Promise.reject();

    let content: IHomeCommonCategoryHomeDefine | IHomeCommonCategoryListDefine | IHomeCommonCategoryDetailDefine;
    switch (template) {
      case 'Home':
        content = createHomePageTemplate();
        break;
      case 'CommonList':
        content = createCommonListPageTemplate();
        break;
      case 'Details':
        content = createDetailPageTemplate();
        break;
      default:
        message.warning(`不支持的模板：${template}`);
        return Promise.reject();
    }

    editorJson.value = {
      ...editorJson.value,
      page: [...pages, { name: key, title, content }],
    };
    const added = editorJson.value.page[editorJson.value.page.length - 1];
    selectedPage.value = added;
    addPageModalVisible.value = false;
    message.success(`已添加页面 ${title} (${key})`);
    return Promise.resolve();
  }

  return {
    pageList,
    getUniquePageName,
    movePageUp,
    movePageDown,
    duplicatePage,
    confirmDeletePage,
    addPageModalVisible,
    addPageTemplate,
    addPageKey,
    addPageTitle,
    addPageLoading,
    templateLabelMap,
    onAddPageMenuClick,
    confirmAddPage,
  };
}
