'use client';

import { useState } from 'react';
import { fetchApi } from '@/lib/utils/client';
import { NoteSendRequest } from '@/types/request/note/send';

export default function NoteSendPage() {
	const [receiverID, setReceiverID] = useState('');
	const [title, setTitle] = useState('');
	const [content, setContent] = useState('');
	const [sending, setSending] = useState(false);
	const [result, setResult] = useState<{ success: boolean; message: string }|null>(null);

	const handleSend = async () => {
		if (!receiverID || !title.trim() || !content.trim()) {
			setResult({ success: false, message: '모든 필드를 입력해주세요.' });
			return;
		}

		setSending(true);
		setResult(null);

		try {
			const res = await fetchApi('/api/note/send', {
				method: 'POST',
				body: {
					receiverMemberID: parseInt(receiverID),
					title: title.trim(),
					content: content.trim()
				} as NoteSendRequest
			});

			if (res.success) {
				setResult({ success: true, message: '쪽지를 보냈습니다.' });
				setTitle('');
				setContent('');
			} else {
				setResult({ success: false, message: res.message || '전송에 실패했습니다.' });
			}
		} catch (e: unknown) {
			const message = e instanceof Error ? e.message : '전송에 실패했습니다.';
			setResult({ success: false, message });
		}

		setSending(false);
	};

	return (
		<div className="container mx-auto max-w-lg p-4">
			<h1 className="text-xl font-bold mb-4">쪽지 보내기</h1>

			{result && (
				<div className={`p-3 rounded-lg mb-4 text-sm ${result.success ? 'bg-green-50 text-green-700 dark:bg-green-950 dark:text-green-300' : 'bg-red-50 text-red-700 dark:bg-red-950 dark:text-red-300'}`}>
					{result.message}
				</div>
			)}

			<div className="flex flex-col gap-3">
				<div>
					<label className="text-sm font-medium mb-1 block">받는 사람 (회원 ID)</label>
					<input type="number" value={receiverID} onChange={e => setReceiverID(e.target.value)} placeholder="회원 ID" className="w-full border rounded-lg px-3 py-2 text-sm" />
				</div>
				<div>
					<label className="text-sm font-medium mb-1 block">제목</label>
					<input type="text" value={title} onChange={e => setTitle(e.target.value)} maxLength={200} placeholder="제목을 입력하세요" className="w-full border rounded-lg px-3 py-2 text-sm" />
				</div>
				<div>
					<label className="text-sm font-medium mb-1 block">내용</label>
					<textarea value={content} onChange={e => setContent(e.target.value)} maxLength={2000} rows={6} placeholder="내용을 입력하세요" className="w-full border rounded-lg px-3 py-2 text-sm resize-none" />
					<div className="text-xs text-gray-400 text-right mt-1">{content.length}/2000</div>
				</div>
				<button type="button" onClick={handleSend} disabled={sending} className="w-full bg-blue-500 text-white py-2.5 rounded-lg font-medium text-sm hover:bg-blue-600 disabled:opacity-50">
					{sending ? '전송 중...' : '보내기'}
				</button>
			</div>

			<div className="mt-4 text-center">
				<a href="/note/inbox" className="text-sm text-blue-500 hover:underline">받은 쪽지함으로 돌아가기</a>
			</div>
		</div>
	);
}