import React, { useMemo } from 'react';
import type { ForumSection } from './types';
import * as t from './forumTheme.css';

type ForumTopicTargetFieldsProps = {
  sections: ForumSection[];
  category: string;
  topicRoomId: string;
  onCategoryChange: (category: string) => void;
  onTopicChange: (topicRoomId: string) => void;
  disabled?: boolean;
};

export function ForumTopicTargetFields({
  sections,
  category,
  topicRoomId,
  onCategoryChange,
  onTopicChange,
  disabled = false,
}: ForumTopicTargetFieldsProps) {
  const categoryTopics = useMemo(() => {
    if (category) {
      return sections.find((s) => s.title === category)?.topics ?? [];
    }
    return sections.flatMap((s) => s.topics);
  }, [category, sections]);

  return (
    <div className={t.ForumTopicTargetFields}>
      <select
        className={t.ForumFilterSelect}
        aria-label="Category"
        value={category}
        disabled={disabled}
        onChange={(e) => onCategoryChange(e.target.value)}
      >
        <option value="">All categories</option>
        {sections.map((section) => (
          <option key={section.title} value={section.title}>
            {section.title}
          </option>
        ))}
      </select>

      <select
        className={t.ForumFilterSelect}
        aria-label="Topic"
        value={topicRoomId}
        disabled={disabled || categoryTopics.length === 0}
        onChange={(e) => onTopicChange(e.target.value)}
      >
        <option value="">Select a topic</option>
        {categoryTopics.length === 0 && category ? (
          <option value="" disabled>
            No topics yet — use Add Topic
          </option>
        ) : null}
        {categoryTopics.map((topic) => (
          <option key={topic.roomId} value={topic.roomId}>
            {topic.name}
          </option>
        ))}
      </select>
    </div>
  );
}
