"use client";

import { useState } from "react";
import { api } from "~/trpc/react";

export function EmbeddingSettings() {
	const [isReembedding, setIsReembedding] = useState(false);
	const [result, setResult] = useState<{ total: number; updated: number } | null>(null);
	const embeddingInfoQuery = api.memory.embeddingInfo.useQuery();
	const reembedMutation = api.memory.reembed.useMutation({
		onMutate: () => {
			setIsReembedding(true);
			setResult(null);
		},
		onSettled: () => {
			setIsReembedding(false);
		},
		onSuccess: (data) => {
			setResult(data);
		},
	});
	const handleReembed = () => {
		if (confirm("This will re-index all your memories for search. Continue?")) {
			reembedMutation.mutate();
		}
	};
	const isAvailable = embeddingInfoQuery.data?.available ?? false;

	return (
		<div className="border border-[#2a2a2a] bg-[#0f0f0f] p-4">
			<p className="mb-2 text-white">search indexing</p>
			<p className="mb-4 text-sm text-[#666666]">
				re-index all memories to improve search results.
			</p>

			{result && (
				<p className="mb-4 text-sm text-[#66b366]">
					indexed {result.updated} of {result.total} memories
				</p>
			)}

			{reembedMutation.error && (
				<p className="mb-4 text-sm text-[#b36666]">
					{reembedMutation.error.message}
				</p>
			)}

			{!isAvailable && !embeddingInfoQuery.isLoading && (
				<p className="mb-4 text-sm text-[#996666]">
					search requires server configuration.
				</p>
			)}

			<button
				className="border border-[#2a2a2a] bg-[#0f0f0f] px-4 py-2 text-white transition hover:border-[#666666] disabled:text-[#666666] disabled:hover:border-[#2a2a2a]"
				disabled={isReembedding || !isAvailable}
				onClick={handleReembed}
				type="button"
			>
				{isReembedding ? "indexing ..." : "re-index all"}
			</button>
		</div>
	);
}
