'use client';

import { useCallback, useEffect, useState } from 'react';
import { fetchApi } from '@/lib/utils/client';
import { formatNoteCounterparty } from '@/lib/utils/note';
import Loading from '@/app/component/Loading';
import { NoteOutboxResponse, SentNotePreview } from '@/types/response/note/outbox';
import type { RecipientItem } from '@/types/response/note/searchRecipient';
import NoteComposeModal from '../_components/NoteComposeModal';
import NoteDetailModal from '../_components/NoteDetailModal';

export default function NoteOutboxPage()
{
	const [notes, setNotes] = useState<SentNotePreview[]>([]);
	const [total, setTotal] = useState(0);
	const [page, setPage] = useState(1);
	const [loading, setLoading] = useState(true);

	const [composeOpen, setComposeOpen] = useState(false);
	const [composeInitialReceiver, setComposeInitialReceiver] = useState<RecipientItem|null>(null);
	const [composeInitialTitle, setComposeInitialTitle] = useState<string|undefined>(undefined);
	const [detailNoteId, setDetailNoteId] = useState<number|null>(null);

	const loadNotes = useCallback(async () => {
		setLoading(true);
		try {
			const res = await fetchApi<NoteOutboxResponse>(`/api/note/outbox?page=${page}&perPage=20`);
			if (res.data) {
				setNotes(res.data.list || []);
				setTotal(res.data.total || 0);
			}
		} catch {}
		setLoading(false);
	}, [page]);

	useEffect(() => {
		loadNotes();
	}, [loadNotes]);

	const openNote = (note: SentNotePreview) => {
		setDetailNoteId(note.id);
	};

	const handleOpenCompose = () => {
		setComposeInitialReceiver(null);
		setComposeInitialTitle(undefined);
		setComposeOpen(true);
	};

	const handleSent = () => {
		loadNotes();
	};

	const handleDeleted = () => {
		loadNotes();
	};

	const readCount = notes.filter(n => n.isRead).length;

	const formatDate = (dateStr: string) => {
		const d = new Date(dateStr);
		return `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')} ${d.getHours().toString().padStart(2, '0')}:${d.getMinutes().toString().padStart(2, '0')}`;
	};

	return (
		<>
			<div className="note-page__header">
				<h1 className="note-page__title">보낸 쪽지함</h1>
				<div className="note-page__actions">
					<span className="note-page__meta">읽음 {readCount} / {notes.length}건</span>
					<button type="button" onClick={handleOpenCompose} className="note-page__compose-btn">
						쪽지 보내기
					</button>
				</div>
			</div>

			{loading && <Loading type={2} />}

			{!loading && notes.length === 0 && (
				<div className="note-page__empty">보낸 쪽지가 없습니다</div>
			)}

			{!loading && notes.length > 0 && (
				<div className="note-page__list">
					{notes.map(note => {
						const counterparty = formatNoteCounterparty({
							name: note.receiverName,
							sid: note.receiverSID,
							channelName: note.receiverChannelName,
							channelHandle: note.receiverChannelHandle
						});
						return (
							<div
								key={note.id}
								onClick={() => openNote(note)}
								className="note-page__item"
							>
								<div className="note-page__item-body">
									<div className="note-page__item-top">
										<span className={`note-page__badge${note.isRead ? ' note-page__badge--read' : ''}`}>
											{note.isRead ? '읽음' : '안읽음'}
										</span>
										<span className="note-page__item-title">{note.title}</span>
									</div>
									<div className="note-page__item-sub">
										<span className="note-page__item-party">{counterparty.primary}</span>
										{counterparty.secondary && <span className="note-page__item-handle">{counterparty.secondary}</span>}
										<span className="note-page__item-time">· {formatDate(note.createdAt)}</span>
									</div>
								</div>
							</div>
						);
					})}
				</div>
			)}

			{total > 20 && (
				<div className="note-page__pager">
					<button type="button" onClick={() => setPage(p => Math.max(1, p - 1))} disabled={page <= 1} className="note-page__pager-btn">이전</button>
					<span className="note-page__pager-info">{page} / {Math.ceil(total / 20)}</span>
					<button type="button" onClick={() => setPage(p => p + 1)} disabled={page >= Math.ceil(total / 20)} className="note-page__pager-btn">다음</button>
				</div>
			)}

			<NoteComposeModal
				open={composeOpen}
				onClose={() => setComposeOpen(false)}
				initialReceiver={composeInitialReceiver}
				initialTitle={composeInitialTitle}
				onSent={handleSent}
			/>

			<NoteDetailModal
				noteId={detailNoteId}
				onClose={() => setDetailNoteId(null)}
				onDeleted={handleDeleted}
			/>
		</>
	);
}
