import { useCallback } from "react";

import { useChat, useI18n, useOptions } from "../composables";
import type { ChatTopic } from "../types";

import "./TopicSelector.scss";

export default function TopicSelector() {
	const { t, te } = useI18n();
	const { options } = useOptions();
	const { selectTopic } = useChat();

	const topics = options.topics ?? [];
	if (!topics.length) {
		return null;
	}

	const hasHeading = te("topicSelectionHeading");
	const hasDescription = te("topicSelectionDescription");

	const handleSelect = useCallback(
		(topic: ChatTopic) => {
			const prefix = t("topicSelectionAcknowledgementPrefix");
			const acknowledgement = `${prefix} ${topic.label}`.trim();
			selectTopic(topic, acknowledgement);
		},
		[selectTopic, t],
	);

	return (
		<div className="chat-topic-selector" data-test-id="chat-topic-selector">
			{(hasHeading || hasDescription) && (
				<div className="chat-topic-selector__copy">
					{hasHeading && (
						<p className="chat-topic-selector__heading">
							{t("topicSelectionHeading")}
						</p>
					)}
					{hasDescription && (
						<p className="chat-topic-selector__description">
							{t("topicSelectionDescription")}
						</p>
					)}
				</div>
			)}
			<div className="chat-topic-selector__pills">
				{topics.map((topic) => (
					<button
						key={topic.slug}
						type="button"
						className="chat-topic-selector__pill"
						onClick={() => handleSelect(topic)}
					>
						{topic.label}
					</button>
				))}
			</div>
		</div>
	);
}
