'use client';

import '@/app/styles/notification-bell.scss';
import { useState, useEffect } from 'react';
import { fetchApi } from '@/lib/utils/client';
import { useNotification, NotificationItem } from '@/hooks/useNotification';
import { NotificationListResponse } from '@/types/response/notification/list';
import { Sheet, SheetContent, SheetTitle, SheetClose } from '@/components/ui/sheet';
import { BellIcon } from 'lucide-react';

export default function NotificationBell()
{
	const { unreadNotifCount, unreadNoteCount, markNotifRead } = useNotification();
	const [open, setOpen] = useState(false);
	const [notifications, setNotifications] = useState<NotificationItem[]>([]);
	const [loading, setLoading] = useState(false);
	const totalUnread = unreadNotifCount + unreadNoteCount;

	// Sheet 열릴 때 첫 로드
	useEffect(() => {
		if (!open || notifications.length > 0) {
			return;
		}

		setLoading(true);
		fetchApi<NotificationListResponse>('/api/notification/list?page=1&perPage=10', { silent: true }).then((res) => {
			if (res.data?.list) {
				setNotifications(res.data.list);
			}
		}).catch(() => {}).finally(() => {
			setLoading(false);
		});
	}, [open, notifications.length]);

	// 읽음 처리
	const handleRead = async (item: NotificationItem) => {
		if (!item.isRead) {
			await markNotifRead(item.id);
			setNotifications(prev => prev.map(n => n.id === item.id ? { ...n, isRead: true } : n));
		}
		if (item.actionUrl) {
			window.location.href = item.actionUrl;
		}
	};

	// 전체 읽음
	const handleReadAll = async () => {
		await markNotifRead();
		setNotifications(prev => prev.map(n => ({ ...n, isRead: true })));
	};

	const formatTime = (dateStr: string) => {
		const d = new Date(dateStr);
		const now = new Date();
		const diff = Math.floor((now.getTime() - d.getTime()) / 60000);

		if (diff < 1) {
			return '방금';
		}
		if (diff < 60) {
			return `${diff}분 전`;
		}
		if (diff < 1440) {
			return `${Math.floor(diff / 60)}시간 전`;
		}
		return `${Math.floor(diff / 1440)}일 전`;
	};

	return (
		<div className="notification-bell">
			{/* 벨 버튼 */}
			<button type="button" onClick={() => setOpen(true)} className="notification-bell__button" title="알림">
				<BellIcon />
				{totalUnread > 0 && (
					<span className="notification-bell__badge">
						{totalUnread > 99 ? '99+' : totalUnread}
					</span>
				)}
			</button>

			{/* Drawer */}
			<Sheet open={open} onOpenChange={setOpen}>
				<SheetContent side="right" className="notification-bell__sheet">
					<div className="notification-bell__sheet-header">
						<SheetTitle asChild>
							<h2 className="notification-bell__sheet-title">알림</h2>
						</SheetTitle>
						<div className="notification-bell__sheet-header-right">
							{unreadNotifCount > 0 && (
								<button type="button" onClick={handleReadAll} className="notification-bell__read-all-btn">모두 읽음</button>
							)}
							<SheetClose asChild>
								<button type="button" aria-label="닫기" className="notification-bell__sheet-close">×</button>
							</SheetClose>
						</div>
					</div>

					<div className="notification-bell__sheet-body">
						{loading && <div className="notification-bell__loading">준비 중...</div>}
						{!loading && notifications.length === 0 && <div className="notification-bell__empty">알림이 없습니다</div>}
						{notifications.map(n => (
							<div key={n.id} onClick={() => handleRead(n)} className={`notification-bell__item ${n.isRead ? '' : 'notification-bell__item--unread'}`}>
								{n.imageUrl && <img src={n.imageUrl} alt={n.title} className="notification-bell__item-image" />}
								<div className="notification-bell__item-content">
									<div className={`notification-bell__item-title ${n.isRead ? 'notification-bell__item-title--read' : 'notification-bell__item-title--unread'}`}>{n.title}</div>
									<div className="notification-bell__item-message">{n.message}</div>
									<div className="notification-bell__item-time">{formatTime(n.createdAt)}</div>
								</div>
								{!n.isRead && <div className="notification-bell__item-dot" />}
							</div>
						))}
					</div>

					<div className="notification-bell__footer">
						<a href="/notification" className="notification-bell__footer-btn notification-bell__footer-btn--primary">
							모든 알림 보기
						</a>
						<a href="/note/inbox" className="notification-bell__footer-btn notification-bell__footer-btn--secondary">
							쪽지함 ({unreadNoteCount})
						</a>
					</div>
				</SheetContent>
			</Sheet>
		</div>
	);
}
