---
import BaseLayout from '../../layouts/BaseLayout.astro';
import TerminalWindow from '../../components/ui/TerminalWindow.astro';
import CommandPrompt from '../../components/ui/CommandPrompt.astro';
import FilterPill from '../../components/ui/FilterPill.astro';
import PostCard from '../../components/PostCard.astro';
import { api } from '../../lib/api/client';
import { getI18n } from '../../lib/i18n';
import type { Post } from '../../lib/types';
import { getAccentVars, getCategoryTheme, getPostTypeTheme, getTagTheme } from '../../lib/utils';

export const prerender = false;

const url = new URL(Astro.request.url);
const selectedQuery = url.searchParams.get('q')?.trim() || '';
const selectedType = url.searchParams.get('type') || 'all';
const selectedTag = url.searchParams.get('tag') || '';
const selectedCategory = url.searchParams.get('category') || '';
const requestedPage = Number.parseInt(url.searchParams.get('page') || '1', 10);
const normalizedSelectedTag = selectedTag.trim().toLowerCase();
const hasActiveFilters = Boolean(selectedType !== 'all' || selectedCategory || selectedTag);
const pageSize = 10;
const { t } = getI18n(Astro);

let paginatedResults: Post[] = [];
let facetResults: Post[] = [];
let apiError: string | null = null;
let totalResults = 0;
let filteredTotal = 0;
let totalPages = 1;
let currentPage = Number.isFinite(requestedPage) && requestedPage > 0 ? requestedPage : 1;

if (selectedQuery) {
  try {
    const pagePromise = api.searchPostsPage({
      query: selectedQuery,
      page: currentPage,
      pageSize,
      category: selectedCategory || undefined,
      tag: selectedTag || undefined,
      postType: selectedType !== 'all' ? selectedType : undefined,
    });
    const facetsPromise = api.searchPosts(selectedQuery, 100);
    const totalPromise = hasActiveFilters
      ? api.searchPostsPage({
          query: selectedQuery,
          page: 1,
          pageSize: 1,
        })
      : Promise.resolve(null);

    const [pageResult, sampledResults, unfilteredSummary] = await Promise.all([
      pagePromise,
      facetsPromise,
      totalPromise,
    ]);

    paginatedResults = pageResult.items;
    facetResults = sampledResults;
    filteredTotal = pageResult.total;
    totalResults = unfilteredSummary?.total ?? pageResult.total;
    totalPages = pageResult.totalPages;
    currentPage = pageResult.page;
  } catch (error) {
    apiError = error instanceof Error ? error.message : t('common.apiUnavailable');
    console.error('Search page error:', error);
  }
}

const categoryCounts = Array.from(
  facetResults.reduce((map, post) => {
    const name = post.category?.trim();
    if (!name) return map;
    map.set(name, (map.get(name) ?? 0) + 1);
    return map;
  }, new Map<string, number>()),
)
  .map(([name, count]) => ({ name, count }))
  .sort((left, right) => right.count - left.count || left.name.localeCompare(right.name));

const tagCounts = Array.from(
  facetResults.reduce((map, post) => {
    for (const tag of post.tags) {
      const name = tag.trim();
      if (!name) continue;
      map.set(name, (map.get(name) ?? 0) + 1);
    }
    return map;
  }, new Map<string, number>()),
)
  .map(([name, count]) => ({ name, count }))
  .sort((left, right) => right.count - left.count || left.name.localeCompare(right.name));

const postTypeFilters = [
  { id: 'all', name: t('common.all'), icon: 'fa-stream' },
  { id: 'article', name: t('common.article'), icon: 'fa-file-alt' },
  { id: 'tweet', name: t('common.tweet'), icon: 'fa-comment-dots' },
];

const buildSearchUrl = ({
  q = selectedQuery,
  type = selectedType,
  tag = selectedTag,
  category = selectedCategory,
  page,
}: {
  q?: string;
  type?: string;
  tag?: string;
  category?: string;
  page?: number;
}) => {
  const params = new URLSearchParams();

  if (q) params.set('q', q);
  if (type && type !== 'all') params.set('type', type);
  if (category) params.set('category', category);
  if (tag) params.set('tag', tag);
  if (page && page > 1) params.set('page', String(page));

  const queryString = params.toString();
  return queryString ? `/search?${queryString}` : '/search';
};

const activeQueryCommand = selectedQuery
  ? t('searchPage.promptQuery', { query: selectedQuery })
  : t('searchPage.promptIdle');
const searchTagHrefBase = buildSearchUrl({ tag: '', page: 1 });
const searchTagHrefPrefix = `${searchTagHrefBase}${searchTagHrefBase.includes('?') ? '&' : '?'}tag=`;
const pageTitle = selectedQuery
  ? `${t('searchPage.pageTitle')} · ${selectedQuery}`
  : t('searchPage.pageTitle');
---

<BaseLayout title={`${pageTitle} - Termi`} canonical="/search" noindex>
  <div class="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
    <TerminalWindow title="~/search/index" class="w-full">
      <div class="px-4 pb-2">
        <CommandPrompt command={activeQueryCommand} />

        <div class="ml-4 mt-4 space-y-3">
          <h1 class="text-3xl font-bold tracking-tight text-[var(--title-color)]">{t('searchPage.title')}</h1>
          <p class="max-w-3xl text-sm leading-7 text-[var(--text-secondary)]">
            {t('searchPage.intro')}
          </p>

          <div class="flex flex-wrap gap-2">
            <span class="terminal-stat-pill">
              <i class="fas fa-magnifying-glass text-[var(--primary)]"></i>
              <span>{t('searchPage.resultSummary', { count: totalResults })}</span>
            </span>
            {selectedQuery && (
              <span class="terminal-stat-pill terminal-stat-pill--accent" style={getAccentVars(getPostTypeTheme('article'))}>
                <i class="fas fa-terminal"></i>
                <span>{t('searchPage.queryLabel')}: {selectedQuery}</span>
              </span>
            )}
            {hasActiveFilters && (
              <span class="terminal-stat-pill">
                <i class="fas fa-filter text-[var(--primary)]"></i>
                <span>{t('searchPage.filteredSummary', { count: filteredTotal })}</span>
              </span>
            )}
          </div>

          <div class="rounded-2xl border border-[var(--border-color)] bg-[var(--terminal-bg)]/60 px-4 py-3 text-sm leading-6 text-[var(--text-secondary)]">
            <i class="fas fa-circle-info mr-2 text-[var(--primary)]"></i>
            {t('searchPage.searchTips')}
          </div>
        </div>
      </div>

      {apiError && (
        <div class="px-4 pb-4">
          <div class="ml-4 rounded-2xl border border-[var(--danger)]/20 bg-[var(--danger)]/10 p-4 text-sm text-[var(--danger)]">
            {apiError}
          </div>
        </div>
      )}

      {!selectedQuery ? (
        <div class="px-4 py-8">
          <div class="terminal-empty ml-4">
            <div class="mx-auto flex max-w-md flex-col items-center gap-3 text-center">
              <span class="terminal-section-icon">
                <i class="fas fa-magnifying-glass"></i>
              </span>
              <h2 class="text-xl font-semibold text-[var(--title-color)]">{t('searchPage.emptyQueryTitle')}</h2>
              <p class="text-sm leading-7 text-[var(--text-secondary)]">
                {t('searchPage.emptyQueryDescription')}
              </p>
            </div>
          </div>
        </div>
      ) : (
        <>
          <div class="px-4 pb-2 space-y-4">
            <div class="ml-4">
              <CommandPrompt command={t('searchPage.filtersTitle')} typing={false} />
              <div class="mt-3 flex flex-wrap gap-3">
                {postTypeFilters.map((filter) => (
                  <FilterPill
                    href={buildSearchUrl({ type: filter.id, page: 1 })}
                    tone={filter.id === 'all' ? 'neutral' : 'accent'}
                    active={selectedType === filter.id}
                    style={filter.id === 'all' ? undefined : getAccentVars(getPostTypeTheme(filter.id))}
                  >
                    <i class={`fas ${filter.icon}`}></i>
                    <span class="font-medium">{filter.name}</span>
                  </FilterPill>
                ))}
              </div>
            </div>

            {categoryCounts.length > 0 && (
              <div class="ml-4">
                <div class="mt-3 flex flex-wrap gap-3">
                  <FilterPill href={buildSearchUrl({ category: '', page: 1 })} tone="amber" active={!selectedCategory}>
                    <i class="fas fa-folder-tree"></i>
                    <span class="font-medium">{t('searchPage.allCategories')}</span>
                  </FilterPill>
                  {categoryCounts.map((category) => (
                    <FilterPill
                      href={buildSearchUrl({ category: category.name, page: 1 })}
                      tone="accent"
                      active={selectedCategory.toLowerCase() === category.name.toLowerCase()}
                      style={getAccentVars(getCategoryTheme(category.name))}
                    >
                      <i class="fas fa-folder-open"></i>
                      <span class="font-medium">{category.name}</span>
                      <span class="text-xs text-[var(--text-tertiary)]">{category.count}</span>
                    </FilterPill>
                  ))}
                </div>
              </div>
            )}

            {tagCounts.length > 0 && (
              <div class="ml-4">
                <div class="mt-3 flex flex-wrap gap-3">
                  <FilterPill href={buildSearchUrl({ tag: '', page: 1 })} tone="teal" active={!selectedTag}>
                    <i class="fas fa-hashtag"></i>
                    <span class="font-medium">{t('searchPage.allTags')}</span>
                  </FilterPill>
                  {tagCounts.map((tag) => (
                    <FilterPill
                      href={buildSearchUrl({ tag: tag.name, page: 1 })}
                      tone="accent"
                      active={normalizedSelectedTag === tag.name.toLowerCase()}
                      style={getAccentVars(getTagTheme(tag.name))}
                    >
                      <i class="fas fa-hashtag"></i>
                      <span class="font-medium">{tag.name}</span>
                      <span class="text-xs text-[var(--text-tertiary)]">{tag.count}</span>
                    </FilterPill>
                  ))}
                </div>
              </div>
            )}
          </div>

          <div class="px-4 pb-8">
            {filteredTotal > 0 ? (
              <div class="ml-4 mt-4 space-y-4">
                {paginatedResults.map((post) => (
                  <PostCard
                    post={post}
                    selectedTag={selectedTag}
                    highlightTerm={selectedQuery}
                    tagHrefPrefix={searchTagHrefPrefix}
                  />
                ))}
              </div>
            ) : (
              <div class="terminal-empty ml-4 mt-4">
                <div class="mx-auto flex max-w-md flex-col items-center gap-3 text-center">
                  <span class="terminal-section-icon">
                    <i class="fas fa-folder-open"></i>
                  </span>
                  <h2 class="text-xl font-semibold text-[var(--title-color)]">{t('searchPage.emptyTitle')}</h2>
                  <p class="text-sm leading-7 text-[var(--text-secondary)]">
                    {t('searchPage.emptyDescription')}
                  </p>
                  <div class="flex flex-wrap justify-center gap-3">
                    <a
                      href={buildSearchUrl({ type: 'all', category: '', tag: '', page: 1 })}
                      class="terminal-action-button terminal-action-button-primary"
                    >
                      <i class="fas fa-rotate-left"></i>
                      <span>{t('common.resetFilters')}</span>
                    </a>
                    <a href={`/ask?q=${encodeURIComponent(selectedQuery)}`} class="terminal-action-button">
                      <i class="fas fa-robot"></i>
                      <span>{t('searchPage.askFallback')}</span>
                    </a>
                  </div>
                </div>
              </div>
            )}
          </div>

          <div class="px-4 py-6">
            <div
              class:list={[
                'terminal-panel-muted ml-4 mt-4 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between',
                totalPages <= 1 && 'hidden',
              ]}
            >
              <span class="text-sm text-[var(--text-secondary)]">
                {t('searchPage.pageSummary', { current: currentPage, total: totalPages, count: filteredTotal })}
              </span>
              <div class="flex flex-wrap gap-2">
                {currentPage > 1 && (
                  <a href={buildSearchUrl({ page: currentPage - 1 })} class="terminal-action-button">
                    <i class="fas fa-chevron-left"></i>
                    <span>{t('searchPage.previous')}</span>
                  </a>
                )}
                {currentPage < totalPages && (
                  <a href={buildSearchUrl({ page: currentPage + 1 })} class="terminal-action-button terminal-action-button-primary">
                    <span>{t('searchPage.next')}</span>
                    <i class="fas fa-chevron-right"></i>
                  </a>
                )}
              </div>
            </div>
          </div>
        </>
      )}
    </TerminalWindow>
  </div>
</BaseLayout>
