import React, { createContext, useContext, useState, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import DynamicModal from '../components/common/modal/DynamicModal';
import { modalTypes } from '../assets/data';
import ToastAlert from '../components/common/alert/ToastAlert';
import { alertTypes } from '../assets/data/types';

const AlertContext = createContext();

export const AlertProvider = ({ children }) => {
	const { t } = useTranslation();
	// 모달 알림 상태
	const [modalState, setModalState] = useState({
		isVisible: false,
		message: '',
		type: alertTypes.info,
		onConfirm: null,
		onCancel: null,
		children: null,
		ChildView: null
	});

	// 토스트 알림 상태 (여러 개를 관리하기 위해 배열 사용)
	const [toasts, setToasts] = useState([]);

	// 토스트 알림 표시 함수
	const showToast = useCallback((message, options = {}) => {
		const {
			type = alertTypes.info,
			duration = 5000,
			translateKey = true,
			position = 'top-center'  // 'top-left', 'top-center', 'top-right', 'bottom-left', 'bottom-center', 'bottom-right'
		} = options;

		const id = Date.now();
		const newToast = {
			id,
			message: translateKey ? t(message) : message,
			type,
			duration,
			position
		};

		setToasts(prev => [...prev, newToast]);

		// 자동 소멸
		if (duration > 0) {
			setTimeout(() => {
				removeToast(id);
			}, duration);
		}
	}, [t]);

	// 토스트 알림 제거 함수
	const removeToast = useCallback((id) => {
		setToasts(prev => prev.filter(toast => toast.id !== id));
	}, []);

	// 모달 알림 표시 함수
	const showModal = useCallback((message, options = {}) => {
		const {
			type = alertTypes.info,
			onConfirm = null,
			onCancel = null,
			translateKey = true,
			children = null,
			ChildView = null
		} = options;

		setModalState({
			isVisible: true,
			message: translateKey ? t(message) : message,
			type,
			onConfirm,
			onCancel,
			children,
			ChildView
		});
	}, [t]);

	// 모달 알림 숨기기 함수
	const hideModal = useCallback(() => {
		setModalState(prev => ({
			...prev,
			isVisible: false
		}));
	}, []);

	// 모달 확인 핸들러
	const handleConfirm = useCallback(() => {
		if (modalState.onConfirm) {
			modalState.onConfirm();
		}
		hideModal();
	}, [modalState.onConfirm, hideModal]);

	// 모달 취소 핸들러
	const handleCancel = useCallback(() => {
		if (modalState.onCancel) {
			modalState.onCancel();
		}
		hideModal();
	}, [modalState.onCancel, hideModal]);

	// 모달 타입에 따른 모달 타입 결정
	const getModalType = () => {
		switch (modalState.type) {
			case alertTypes.confirm:
				return modalTypes.confirmOkCancel;
			case alertTypes.confirmChildren:
				return modalTypes.childOkCancel;
			case alertTypes.success:
			case alertTypes.warning:
			case alertTypes.error:
			case alertTypes.info:
			default:
				return modalTypes.completed;
		}
	};

	return (
		<AlertContext.Provider value={{ showToast, removeToast, showModal, hideModal }}>
			{children}

			{/* 토스트 알림 컨테이너 */}
			<div className="toast-container">
				{toasts.map(toast => (
					<ToastAlert
						key={toast.id}
						id={toast.id}
						message={toast.message}
						type={toast.type}
						position={toast.position}
						onClose={() => removeToast(toast.id)}
					/>
				))}
			</div>

			{/* 모달 알림 */}
			<DynamicModal
				modalType={getModalType()}
				view={modalState.isVisible ? 'view' : 'hidden'}
				modalText={modalState.message}
				handleSubmit={handleConfirm}
				handleCancel={modalState.type === alertTypes.confirm || modalState.type === alertTypes.confirmChildren ? handleCancel : null}
				children={modalState.children}
				ChildView={modalState.ChildView}
			/>
		</AlertContext.Provider>
	);
};

export const useAlert = () => {
	const context = useContext(AlertContext);
	if (!context) {
		throw new Error('useAlert must be used within an AlertProvider');
	}
	return context;
};