import type { SearchKeywordOption } from '../../../components/search';
import type { LoadedSampleEntry } from '../../../samples/registry';
import {
  buildApisPath,
  buildChatPath,
  buildDocsPath,
  buildPlansPath,
  buildPlayAppPath,
  buildPlayPath,
  buildSavedLayoutPath,
  getDocsSectionLabel,
  PLAN_FILTER_LABELS,
  PLAN_GROUP_LABEL,
  PLAN_SIDEBAR_LABELS,
} from '../routes';
import { compactKeywords, scrollToElement } from '../mainView/utils';
import { getReadyPlayAppEntries } from '../../../views/play/apps/apps/appsRegistry';

function getCurrentPathnameWithSearch() {
  if (typeof window === 'undefined') {
    return '/';
  }

  return `${window.location.pathname}${window.location.search}${window.location.hash}`;
}

type BuildSearchOptionsParams = {
  componentSamples: LoadedSampleEntry[];
  widgetSamples: LoadedSampleEntry[];
  docFolders: string[];
  docsDocuments: Array<{
    id: string;
    title: string;
    folder: string;
    preview?: string;
  }>;
  savedLayouts: Array<{
    id: string;
    name: string;
  }>;
  hasAccess: boolean;
  navigateTo: (path: string) => void;
  setFocusedComponentId: (value: string | null) => void;
  requestPlanQuickFilter: (filter: 'working' | 'release-pending-main' | 'automation-failed' | null) => void;
};

export function buildSearchOptions({
  componentSamples,
  widgetSamples,
  docFolders,
  docsDocuments,
  savedLayouts,
  hasAccess,
  navigateTo,
  setFocusedComponentId,
  requestPlanQuickFilter,
}: BuildSearchOptionsParams): SearchKeywordOption[] {
  const onSelectWindow = () => {
    setFocusedComponentId(null);
  };

  return [
    {
      id: 'page:apis:components',
      label: 'APIs / Components',
      group: 'Page',
      keywords: ['api', 'components', '컴포넌트'],
      onSelect: () => {
        requestPlanQuickFilter(null);
        navigateTo(buildApisPath('components'));
        setFocusedComponentId(null);
      },
      onSelectWindow,
    },
    {
      id: 'page:apis:widgets',
      label: 'APIs / Widgets',
      group: 'Page',
      keywords: ['api', 'widgets', '위젯'],
      onSelect: () => {
        requestPlanQuickFilter(null);
        navigateTo(buildApisPath('widgets'));
        setFocusedComponentId(null);
      },
      onSelectWindow,
    },
    {
      id: 'page:plans:all',
      label: `${PLAN_GROUP_LABEL} / ${PLAN_FILTER_LABELS.all}`,
      group: 'Page',
      keywords: ['plans', 'automation', '자동화', '실행', '현황', 'worker'],
      onSelect: () => {
        requestPlanQuickFilter(null);
        navigateTo(buildPlansPath('all'));
        setFocusedComponentId(null);
      },
      onSelectWindow,
    },
    ...(hasAccess
      ? [
          {
            id: 'page:plans:board',
            label: `${PLAN_GROUP_LABEL} / ${PLAN_SIDEBAR_LABELS.board}`,
            group: 'Page',
            keywords: ['plans', 'plan', '플랜', '게시판', 'board', '요청', '작업 요청', '접수', '계획'],
            onSelect: () => {
              requestPlanQuickFilter(null);
              navigateTo(buildPlansPath('board'));
              setFocusedComponentId(null);
            },
            onSelectWindow,
          } satisfies SearchKeywordOption,
          {
            id: 'page:plans:server-command',
            label: `Servers / ${PLAN_SIDEBAR_LABELS['server-command']}`,
            group: 'Page',
            keywords: ['plans', 'plan', 'server', 'command', 'server command', '서버', '명령', '재기동'],
            onSelect: () => {
              requestPlanQuickFilter(null);
              navigateTo(buildPlansPath('server-command'));
              setFocusedComponentId(null);
            },
            onSelectWindow,
          } satisfies SearchKeywordOption,
        ]
      : []),
    {
      id: 'page:plans:release-review',
      label: `${PLAN_GROUP_LABEL} / ${PLAN_SIDEBAR_LABELS['release-review']}`,
      group: 'Page',
      keywords: ['release', 'review', '검수', '릴리즈', 'release 검수'],
      onSelect: () => {
        requestPlanQuickFilter(null);
        navigateTo(buildPlansPath('release-review'));
        setFocusedComponentId(null);
      },
      onSelectWindow,
    },
    {
      id: 'page:plans:charts',
      label: `${PLAN_GROUP_LABEL} / ${PLAN_SIDEBAR_LABELS.charts}`,
      group: 'Page',
      keywords: ['plans', 'plan', '차트', 'chart', '스케줄 차트'],
      onSelect: () => {
        requestPlanQuickFilter(null);
        navigateTo(buildPlansPath('charts'));
        setFocusedComponentId(null);
      },
      onSelectWindow,
    },
    {
      id: 'page:plans:schedule',
      label: `${PLAN_GROUP_LABEL} / ${PLAN_SIDEBAR_LABELS.schedule}`,
      group: 'Page',
      keywords: ['plans', 'plan', '스케줄', 'schedule', '반복 작업'],
      onSelect: () => {
        requestPlanQuickFilter(null);
        navigateTo(buildPlansPath('schedule'));
        setFocusedComponentId(null);
      },
      onSelectWindow,
    },
    ...(hasAccess
      ? [
          {
            id: 'page:plans:automation-type',
            label: `${PLAN_GROUP_LABEL} / ${PLAN_SIDEBAR_LABELS['automation-type']}`,
            group: 'Page',
            keywords: ['plans', 'plan', 'automation type', '자동화 유형', '자동화 처리', '유형 관리'],
            onSelect: () => {
              requestPlanQuickFilter(null);
              navigateTo(buildPlansPath('automation-type'));
              setFocusedComponentId(null);
            },
            onSelectWindow,
          } satisfies SearchKeywordOption,
          {
            id: 'page:plans:automation-context',
            label: `${PLAN_GROUP_LABEL} / ${PLAN_SIDEBAR_LABELS['automation-context']}`,
            group: 'Page',
            keywords: ['plans', 'plan', 'context', 'context type', '컨텍스트', 'Context 유형', '부모 context'],
            onSelect: () => {
              requestPlanQuickFilter(null);
              navigateTo(buildPlansPath('automation-context'));
              setFocusedComponentId(null);
            },
            onSelectWindow,
          } satisfies SearchKeywordOption,
          {
            id: 'page:plans:token-setting',
            label: `토큰관리 / ${PLAN_SIDEBAR_LABELS['token-setting']}`,
            group: 'Page',
            keywords: ['plans', 'plan', 'token', 'token setting', '토큰', '토큰 설정', '권한 설정', '앱 권한'],
            onSelect: () => {
              requestPlanQuickFilter(null);
              navigateTo(buildPlansPath('token-setting'));
              setFocusedComponentId(null);
            },
            onSelectWindow,
          } satisfies SearchKeywordOption,
          {
            id: 'page:plans:shared-resource',
            label: `토큰관리 / ${PLAN_SIDEBAR_LABELS['shared-resource']}`,
            group: 'Page',
            keywords: ['plans', 'plan', 'share token', 'shared resource', '공유 리소스', '공유 토큰', '권한 회수', '활동 내역'],
            onSelect: () => {
              requestPlanQuickFilter(null);
              navigateTo(buildPlansPath('shared-resource'));
              setFocusedComponentId(null);
            },
            onSelectWindow,
          } satisfies SearchKeywordOption,
          {
            id: 'page:plans:history',
            label: `${PLAN_GROUP_LABEL} / ${PLAN_SIDEBAR_LABELS.history}`,
            group: 'Page',
            keywords: ['plans', 'plan', '히스토리', 'history', '방문자 이력'],
            onSelect: () => {
              requestPlanQuickFilter(null);
              navigateTo(buildPlansPath('history'));
              setFocusedComponentId(null);
            },
            onSelectWindow,
          } satisfies SearchKeywordOption,
        ]
      : []),
    {
      id: 'page:preview:app',
      label: 'Preview App / 모바일 앱 열기',
      group: 'Page',
      keywords: ['preview', 'iframe', '미리보기', 'preview app', '프리뷰 앱', '모바일 앱', 'cbt app'],
      description: 'preview.sm-home.cloud에서 실제 앱 컨테이너 화면을 모바일 해상도로 엽니다.',
      onSelect: () => {
        requestPlanQuickFilter(null);
        navigateTo(buildPlayPath('cbt'));
        setFocusedComponentId(null);
      },
      onSelectWindow,
    },
    {
      id: 'page:chat:live',
      label: 'Codex Live / Codex Live',
      group: 'Page',
      keywords: ['codex live', 'chat', 'codex', '채팅', '대화', '메시지'],
      onSelect: () => {
        requestPlanQuickFilter(null);
        navigateTo(buildChatPath('live'));
        setFocusedComponentId(null);
      },
      onSelectWindow,
    },
    {
      id: 'page:chat:system',
      label: '채팅 / 시스템 채팅',
      group: 'Page',
      keywords: ['system chat', 'system', 'chat', '시스템 채팅', '시스템', '채팅 ui'],
      onSelect: () => {
        requestPlanQuickFilter(null);
        navigateTo(buildChatPath('system'));
        setFocusedComponentId(null);
      },
      onSelectWindow,
    },
    {
      id: 'page:chat:changes',
      label: 'Codex Live / 변경 이력',
      group: 'Page',
      keywords: ['codex live', 'changes', 'source', 'diff', '변경', '소스', '채팅 변경', '채팅 diff'],
      onSelect: () => {
        requestPlanQuickFilter(null);
        navigateTo(buildChatPath('changes'));
        setFocusedComponentId(null);
      },
      onSelectWindow,
    },
    {
      id: 'page:chat:resources',
      label: '리소스 관리 / 리소스 관리',
      group: 'Page',
      keywords: ['codex live', 'resource', 'resources', 'file', 'files', '리소스', '파일', '파일 시스템'],
      onSelect: () => {
        requestPlanQuickFilter(null);
        navigateTo(buildChatPath('resources'));
        setFocusedComponentId(null);
      },
      onSelectWindow,
    },
    {
      id: 'page:chat:errors',
      label: '앱로그 / 에러 로그',
      group: 'Page',
      keywords: ['app log', 'applog', '앱로그', 'error', 'errors', '에러', '로그'],
      onSelect: () => {
        requestPlanQuickFilter(null);
        navigateTo(buildChatPath('errors'));
        setFocusedComponentId(null);
      },
      onSelectWindow,
    },
    {
      id: 'page:chat:manage',
      label: '채팅 관리 / 유형 권한 관리',
      group: 'Page',
      keywords: ['chat manage', 'chat type', 'permission', '권한', '채팅 유형', '채팅 관리'],
      onSelect: () => {
        requestPlanQuickFilter(null);
        navigateTo(buildChatPath('manage'));
        setFocusedComponentId(null);
      },
      onSelectWindow,
    },
    {
      id: 'page:chat:manage-defaults',
      label: '채팅 관리 / 공통 문맥 관리',
      group: 'Page',
      keywords: ['chat manage', 'default type', 'default context', '기본 유형', '공통 문맥', '기본 context', '채팅 관리'],
      onSelect: () => {
        requestPlanQuickFilter(null);
        navigateTo(buildChatPath('manage-defaults'));
        setFocusedComponentId(null);
      },
      onSelectWindow,
    } satisfies SearchKeywordOption,
    {
      id: 'page:chat:manage-share',
      label: '채팅 관리 / 공유채팅 생성',
      group: 'Page',
      keywords: ['chat manage', 'shared chat', 'share room', '공유채팅', '공유 채팅', '채팅방 생성', '공유 url'],
      onSelect: () => {
        requestPlanQuickFilter(null);
        navigateTo(buildChatPath('manage-share'));
        setFocusedComponentId(null);
      },
      onSelectWindow,
    } satisfies SearchKeywordOption,
    ...docFolders.map((folder) => ({
      id: `docs-folder:${folder}`,
      label: `Docs / ${getDocsSectionLabel(folder)}`,
      group: 'Docs Folder',
      keywords: [folder, 'docs', '문서'],
      onSelect: () => {
        requestPlanQuickFilter(null);
        navigateTo(buildDocsPath(folder));
        setFocusedComponentId(null);
      },
      onSelectWindow,
    })),
    ...docsDocuments.map((document) => ({
      id: `doc:${document.id}`,
      label: document.title,
      group: `Docs / ${getDocsSectionLabel(document.folder)}`,
      keywords: [document.folder, document.id, document.title],
      description: document.preview,
      onSelect: () => {
        requestPlanQuickFilter(null);
        navigateTo(buildDocsPath(document.folder));
        setFocusedComponentId(`doc:${document.id}`);
        scrollToElement(`document-preview-${document.id}`);
      },
      onSelectWindow,
    })),
    ...savedLayouts.map((layout) => ({
      id: `page:play:layout-record:${layout.id}`,
      label: `Play / ${layout.name}`,
      group: 'Play Layout',
      keywords: compactKeywords([layout.name, layout.id, 'play', 'layout', 'saved layout', '저장 레이아웃', '메모']),
      onSelect: () => {
        requestPlanQuickFilter(null);
        navigateTo(buildSavedLayoutPath(layout.id));
        setFocusedComponentId(null);
      },
      onSelectWindow,
    })),
    ...getReadyPlayAppEntries().map((entry) => ({
      id: `page:play:app:${entry.id}`,
      label: `Apps / ${entry.name}`,
      group: 'Play App',
      keywords: compactKeywords([entry.id, entry.name, 'apps', 'app', 'game', '게임', ...(entry.searchKeywords ?? [])]),
      description: entry.searchDescription,
      onSelect: () => {
        requestPlanQuickFilter(null);
        navigateTo(buildPlayAppPath(entry.id, 'embedded', getCurrentPathnameWithSearch()));
        setFocusedComponentId(null);
      },
      onSelectWindow,
    })),
    ...componentSamples.map((entry) => ({
      id: `component:${entry.sampleMeta.componentId}:${entry.sampleMeta.id}`,
      label: entry.sampleMeta.title,
      group: 'Component',
      keywords: compactKeywords([
        entry.sampleMeta.componentId,
        entry.sampleMeta.id,
        entry.sampleMeta.category,
        entry.sampleMeta.kind,
        entry.sampleMeta.variantLabel ?? '',
      ]),
      description: entry.sampleMeta.description,
      onSelect: () => {
        requestPlanQuickFilter(null);
        navigateTo(buildApisPath('components'));
        setFocusedComponentId(`component:${entry.sampleMeta.componentId}`);
        scrollToElement(`component-sample-${entry.sampleMeta.componentId}`);
      },
      onSelectWindow,
    })),
    ...widgetSamples.map((entry) => ({
      id: `widget:${entry.sampleMeta.componentId}:${entry.sampleMeta.id}`,
      label: entry.sampleMeta.title,
      group: 'Widget',
      keywords: compactKeywords([
        entry.sampleMeta.componentId,
        entry.sampleMeta.id,
        entry.sampleMeta.category,
        entry.sampleMeta.kind,
        entry.sampleMeta.variantLabel ?? '',
      ]),
      description: entry.sampleMeta.description,
      onSelect: () => {
        requestPlanQuickFilter(null);
        navigateTo(buildApisPath('widgets'));
        setFocusedComponentId(`widget:${entry.sampleMeta.componentId}`);
      },
      onSelectWindow,
    })),
  ];
}
