'use client';

import React, { useState, useCallback, KeyboardEvent } from 'react';
import { filterSpecialCharacters } from '@/lib/utils/client';

type Props = {
	value: string[];
	onChange: (tags: string[]) => void;
	maxTags?: number;
};

export default function PostTagInput({ value, onChange, maxTags = 10 }: Props)
{
	const [inputValue, setInputValue] = useState<string>('');

	const handleKeyDown = useCallback((e: KeyboardEvent<HTMLInputElement>) => {
		if (e.key === 'Enter' && inputValue.trim() !== '') {
			e.preventDefault();

			// 중복 방지
			const newTag = inputValue.trim();
			const isDuplicate = value.some(tag => tag.toLowerCase() === newTag.toLowerCase());
			if (isDuplicate) {
				setInputValue('');
				return;
			}

			if (maxTags <= 0 || (value.length < maxTags)) {
				onChange([...value, newTag]);
				setInputValue('');
			}

		} else if (e.key === 'Backspace' && inputValue === '') { // 삭제
			onChange(value.slice(0, -1));
		}
	}, [inputValue, value, maxTags, onChange]);

	const handleChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
		const filtered = filterSpecialCharacters(e.target.value); // 특수문자는 입력 제외
		if (filtered.length > 20) {
			return;
		}

		setInputValue(filtered);
	}, []);

	const handleRemoveTag = useCallback((index: number) => {
		onChange(value.filter((_, i) => i !== index));
	}, [value, onChange]);

	return (
		<div className="tag-input">

			{/* 태그 표시 */}
			{value.map((tag, index) => (
				<span key={index} className="tag">
					<small>#{tag}</small>
					<button type="button" onClick={() => handleRemoveTag(index)}>x</button>
				</span>
			))}

			{/* 최대 태그 수에 도달하지 않았을 때만 입력 표시 */}
			{(maxTags <= 0 || (value.length < maxTags)) && (
				<input
					type="text"
					value={inputValue}
					onChange={handleChange}
					onKeyDown={handleKeyDown}
					maxLength={20}
					placeholder={`# 태그를 입력해주세요. (최대 ${maxTags}개)`}
					autoComplete="off"
				/>
			)}

		</div>
	);
}