import type { Tag } from "@shared/schema";
import { Plus, X } from "lucide-react";
import { useEffect, useState } from "react";
import { useFormContext } from "react-hook-form";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { FormLabel } from "@/components/ui/form";
import {
	Select,
	SelectContent,
	SelectItem,
	SelectTrigger,
	SelectValue,
} from "@/components/ui/select";

interface TagManagerProps {
	name: string;
	tags: Tag[] | undefined;
	label?: string;
}

/**
 * Tag manager component for selecting and managing tags
 */
export function TagManager({ name, tags, label = "Tags" }: TagManagerProps) {
	const form = useFormContext();
	const [selectedTags, setSelectedTags] = useState<Tag[]>([]);
	const [selectedTagId, setSelectedTagId] = useState<string>("");

	// Initialize selected tags from form values
	useEffect(() => {
		const formTags = form.getValues(name) || [];
		if (tags && formTags.length > 0) {
			const initialTags = formTags
				.map((id: number) => tags.find((t) => t.id === id))
				.filter(Boolean) as Tag[];
			setSelectedTags(initialTags);
		}
	}, [tags, form, name]);

	// Handle tag selection
	const handleAddTag = () => {
		if (!selectedTagId) return;

		const tagId = parseInt(selectedTagId, 10);
		const tag = tags?.find((t) => t.id === tagId);

		if (tag && !selectedTags.some((t) => t.id === tag.id)) {
			setSelectedTags([...selectedTags, tag]);

			// Update form values
			const currentTags = form.getValues(name) || [];
			form.setValue(name, [...currentTags, tag.id], { shouldValidate: true });
		}

		setSelectedTagId("");
	};

	// Handle tag removal
	const handleRemoveTag = (tagId: number) => {
		setSelectedTags(selectedTags.filter((tag) => tag.id !== tagId));

		// Update form values
		const currentTags = form.getValues(name) || [];
		form.setValue(
			name,
			currentTags.filter((id: number) => id !== tagId),
			{ shouldValidate: true },
		);
	};

	return (
		<div>
			<FormLabel>{label}</FormLabel>
			<div className="flex flex-wrap gap-2 mb-2">
				{selectedTags.map((tag) => (
					<Badge
						key={tag.id}
						variant="secondary"
						className="px-2 py-1 flex items-center gap-1"
					>
						{tag.name}
						<Button
							type="button"
							variant="ghost"
							size="sm"
							className="h-4 w-4 p-0 text-navy/60 dark:text-cream/60 hover:text-navy hover:dark:text-cream hover:bg-transparent"
							onClick={() => handleRemoveTag(tag.id)}
						>
							<X className="h-3 w-3" />
							<span className="sr-only">Remove {tag.name}</span>
						</Button>
					</Badge>
				))}

				{selectedTags.length === 0 && (
					<p className="text-sm text-navy/60 dark:text-cream/60">
						No tags selected
					</p>
				)}
			</div>

			<div className="flex gap-2">
				<Select value={selectedTagId} onValueChange={setSelectedTagId}>
					<SelectTrigger className="w-[200px]">
						<SelectValue placeholder="Select a tag" />
					</SelectTrigger>
					<SelectContent>
						{tags?.map((tag) => (
							<SelectItem
								key={tag.id}
								value={tag.id.toString()}
								disabled={selectedTags.some((t) => t.id === tag.id)}
							>
								{tag.name}
							</SelectItem>
						))}
					</SelectContent>
				</Select>

				<Button
					type="button"
					variant="outline"
					onClick={handleAddTag}
					disabled={!selectedTagId}
					className="flex items-center gap-1"
				>
					<Plus className="h-4 w-4" />
					<span>Add Tag</span>
				</Button>
			</div>
		</div>
	);
}
