import React, { FormEventHandler, useCallback, useEffect, useState } from 'react';
import { IconButton, Text, Tooltip, TooltipProvider } from 'folds';
import { Icon } from '../../components/icons';
import type { ForumBoardQuery, ForumSection, ForumThreadSummary } from './types';
import { ForumSortIcons } from './forumLucideIcons';
import { ForumTopicSearchInput } from './ForumTopicSearchInput';
import * as t from './forumTheme.css';

const SORT_CYCLE: NonNullable<ForumBoardQuery['sort']>[] = ['hot', 'new', 'top'];
const SORT_ICON = {
  hot: ForumSortIcons.hot,
  new: ForumSortIcons.new,
  top: ForumSortIcons.top,
} as const;
const SORT_TITLE: Record<NonNullable<ForumBoardQuery['sort']>, string> = {
  hot: 'Hot — sort by activity',
  new: 'New — newest first',
  top: 'Top — most replies',
};

type ForumFilterBarProps = {
  sections: ForumSection[];
  threads: ForumThreadSummary[];
  query: ForumBoardQuery;
  hideCategoryTopic?: boolean;
  onQueryChange: (key: string, value: string | null) => void;
  onCategoryChange?: (category: string | null) => void;
};

export function ForumFilterBar({
  sections,
  threads,
  query,
  hideCategoryTopic = false,
  onQueryChange,
  onCategoryChange,
}: ForumFilterBarProps) {
  const categoryTopics = query.category
    ? sections.find((s) => s.title === query.category)?.topics ?? []
    : sections.flatMap((s) => s.topics);

  const [searchDraft, setSearchDraft] = useState(query.q || '');

  useEffect(() => {
    setSearchDraft(query.q || '');
  }, [query.q]);

  const applySearch = useCallback(() => {
    const trimmed = searchDraft.trim();
    onQueryChange('q', trimmed ? trimmed : null);
  }, [onQueryChange, searchDraft]);

  const handleSearchSubmit: FormEventHandler<HTMLFormElement> = (evt) => {
    evt.preventDefault();
    applySearch();
  };

  const cycleSort = useCallback(() => {
    const current = query.sort || 'hot';
    const idx = SORT_CYCLE.indexOf(current);
    const next = SORT_CYCLE[(idx + 1) % SORT_CYCLE.length];
    onQueryChange('sort', next);
  }, [query.sort, onQueryChange]);

  const sort = query.sort || 'hot';

  const handleCategoryChange = (value: string) => {
    const category = value || null;
    if (onCategoryChange) {
      onCategoryChange(category);
      return;
    }
    onQueryChange('category', category);
    if (query.topic) {
      onQueryChange('topic', null);
    }
  };

  return (
    <form
      className={hideCategoryTopic ? t.ForumFiltersCompact : t.ForumFilters}
      onSubmit={handleSearchSubmit}
      id="forumFilterForm"
    >
      <ForumTopicSearchInput value={searchDraft} onChange={setSearchDraft} threads={threads} />

      {!hideCategoryTopic && (
        <select
          className={t.ForumFilterSelect}
          aria-label="Category"
          value={query.category || ''}
          onChange={(e) => handleCategoryChange(e.target.value)}
        >
          <option value="">All categories</option>
          {sections.map((section) => (
            <option key={section.title} value={section.title}>
              {section.title}
            </option>
          ))}
        </select>
      )}

      {!hideCategoryTopic && (
        <select
          className={t.ForumFilterSelect}
          aria-label="Topic"
          value={query.topic || ''}
          onChange={(e) => onQueryChange('topic', e.target.value || null)}
        >
          <option value="">All topics</option>
          {categoryTopics.length === 0 && query.category ? (
            <option value="" disabled>
              No topics yet — use Add Topic in the menu
            </option>
          ) : null}
          {categoryTopics.map((topic) => (
            <option key={topic.roomId} value={topic.roomId}>
              {topic.name}
            </option>
          ))}
        </select>
      )}

      <TooltipProvider
        position="Bottom"
        align="Center"
        offset={4}
        tooltip={
          <Tooltip>
            <Text>{SORT_TITLE[sort]}</Text>
          </Tooltip>
        }
      >
        {(triggerRef) => (
          <IconButton
            ref={triggerRef}
            type="button"
            className={t.ForumSortCycleBtn}
            variant="SurfaceVariant"
            fill="None"
            size="300"
            radii="300"
            onClick={cycleSort}
            aria-label={SORT_TITLE[sort]}
          >
            <Icon src={SORT_ICON[sort]} size="200" />
          </IconButton>
        )}
      </TooltipProvider>
    </form>
  );
}
