'use client';

import { useState } from 'react';
import { useDocsSearch } from 'fumadocs-core/search/client';
import searchTags from '@/.generated/search-tags.json';
import {
  SearchDialog,
  SearchDialogClose,
  SearchDialogContent,
  SearchDialogFooter,
  SearchDialogHeader,
  SearchDialogIcon,
  SearchDialogInput,
  SearchDialogList,
  SearchDialogOverlay,
  type SharedProps,
} from 'fumadocs-ui/components/dialog/search';

const projectTags = [
  ['recette', 'Recettes'],
  ['sap-tower', 'My SAP Tower'],
];
const topicTags = searchTags.filter((tag) => !projectTags.some(([project]) => project === tag));

export function CustomSearchDialog(props: SharedProps) {
  const [tag, setTag] = useState<string>();
  const search = useDocsSearch({ type: 'fetch', tag });

  return (
    <SearchDialog
      {...props}
      search={search.search}
      onSearchChange={search.setSearch}
      isLoading={search.isLoading}
      data={search.data}
      error={search.error}
    >
      <SearchDialogOverlay />
      <SearchDialogContent>
        <SearchDialogHeader>
          <SearchDialogIcon />
          <SearchDialogInput
            type="search"
            name="site-search"
            autoComplete="off"
            data-bwignore="true"
            data-1p-ignore="true"
            data-lpignore="true"
            placeholder="Chercher une recette, un ingrédient ou un sujet SAP…"
          />
          <SearchDialogClose />
        </SearchDialogHeader>
        <SearchDialogList />
        <SearchDialogFooter className="flex flex-wrap items-center gap-2">
          <select
            className="rounded-md border bg-fd-background px-2 py-1 text-sm"
            aria-label="Filtrer la recherche par projet ou par tag"
            value={tag ?? ''}
            onChange={(event) => setTag(event.target.value || undefined)}
          >
            <option value="">Tous les projets et tags</option>
            <optgroup label="Projets">
              {projectTags.map(([value, label]) => <option key={value} value={value}>{label}</option>)}
            </optgroup>
            <optgroup label="Tags">
              {topicTags.map((value) => <option key={value} value={value}>{value.replaceAll('-', ' ')}</option>)}
            </optgroup>
          </select>
        </SearchDialogFooter>
      </SearchDialogContent>
    </SearchDialog>
  );
}
