'use client';

import dynamic from 'next/dynamic';
import { useState, useRef, useEffect } from 'react';
import { EmojiClickData, EmojiStyle, Categories } from 'emoji-picker-react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faFaceSmile } from '@fortawesome/free-regular-svg-icons';
import '@/styles/emoji-picker.scss';

const Picker = dynamic(
	() => {
		return import('emoji-picker-react');
	},
	{ ssr: false }
);

type Props = {
	onEmojiSelect: (emoji: string) => void;
};

export default function EmojiPicker({ onEmojiSelect }: Props) {
	const [showPicker, setShowPicker] = useState(false);
	const wrapperRef = useRef<HTMLDivElement>(null);

	const handleEmojiClick = (emojiData: EmojiClickData) => {
		onEmojiSelect(emojiData.emoji);
		setShowPicker(false); // 선택 후 자동으로 닫기
	};

	useEffect(() => {
		const handleClickOutside = (event: MouseEvent) => {
			if (wrapperRef.current && !wrapperRef.current.contains(event.target as Node)) {
				setShowPicker(false);
			}
		};

		if (showPicker) {
			document.addEventListener('mousedown', handleClickOutside);
		} else {
			document.removeEventListener('mousedown', handleClickOutside);
		}

		return () => {
			document.removeEventListener('mousedown', handleClickOutside);
		};
	}, [showPicker]);

	return (
		<>
			<div id='emojiPicker' ref={wrapperRef}>
				<button type="button" onClick={() => setShowPicker(prev => !prev)} title='이모지 선택'>
					<FontAwesomeIcon icon={faFaceSmile} />
				</button>

				{showPicker && (
					<Picker
						searchPlaceholder="그림 이모니콘 검색"
						onEmojiClick={handleEmojiClick}
						emojiStyle={EmojiStyle.NATIVE}
						previewConfig={{ 
							showPreview: false 
						}}
						lazyLoadEmojis={true}
						width="30rem"
						height="20rem" 
						categories={[
							{ category: Categories.SMILEYS_PEOPLE, name: '인물' },
							{ category: Categories.ANIMALS_NATURE, name: '자연' },
							{ category: Categories.FOOD_DRINK, name: '음식' },
							{ category: Categories.TRAVEL_PLACES, name: '여행' },
							{ category: Categories.ACTIVITIES, name: '활동' },
							{ category: Categories.OBJECTS, name: '사물' },
							{ category: Categories.SYMBOLS, name: '기호' },
							{ category: Categories.FLAGS, name: '국기' }
						]}
					/>
				)}
			</div>
		</>
	);
}