import { useState, useCallback } from 'react'; import { useNavigate } from 'react-router-dom'; import { sajuInterpret } from '../../../api'; const INITIAL_FORM = { name: '', year: '', month: '', day: '', hour: '', gender: 'male', calendar_type: 'solar', }; export default function useSajuForm() { const [form, setForm] = useState(INITIAL_FORM); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const navigate = useNavigate(); const handleChange = useCallback((field, value) => { setForm((prev) => ({ ...prev, [field]: value })); }, []); const handleSubmit = useCallback(async (e) => { if (e?.preventDefault) e.preventDefault(); setError(null); if (!form.year || !form.month || !form.day) { setError('생년월일을 모두 입력해주세요.'); return; } const year = parseInt(form.year, 10); const month = parseInt(form.month, 10); const day = parseInt(form.day, 10); if (year < 1900 || year > 2100 || month < 1 || month > 12 || day < 1 || day > 31) { setError('올바른 생년월일을 입력해주세요.'); return; } setLoading(true); try { const body = { year, month, day, gender: form.gender, calendar_type: form.calendar_type, }; if (form.hour !== '') { body.hour = parseInt(form.hour, 10); } const result = await sajuInterpret(body); navigate(`/saju/result?rid=${result.reading_id}`); } catch (err) { console.error('사주 분석 실패', err); setError(err.message || '잠시 후 다시 시도해주세요.'); } finally { setLoading(false); } }, [form, navigate]); return { form, handleChange, handleSubmit, loading, error }; }