'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import { fetchApi } from '@/lib/utils/client';
import { useStudioContext } from '@/app/studio/context';
import { useGoalConfigContext } from '../context';
import { Separator } from '@/components/ui/separator';
import GoalPreviewPanel from '../_components/GoalPreviewPanel';
import GoalFormPanel from '../_components/GoalFormPanel';
import { createEmptyForm, parseInput } from '../types';
import type { FormState } from '../types';

export default function GoalAddPage()
{
	const router = useRouter();
	const { channelID } = useStudioContext();
	const { setSaving, fetchList } = useGoalConfigContext();

	const [form, setForm] = useState<FormState>(createEmptyForm());
	const [localSaving, setLocalSaving] = useState(false);

	// ── 폼 필드 변경 ────────────────────────────────
	const handleFormChange = <K extends keyof FormState>(field: K, value: FormState[K]) => {
		setForm(prev => ({ ...prev, [field]: value }));
	};

	// ── 저장 ─────────────────────────────────────────
	const handleSave = async () => {
		if (!channelID) {
			return;
		}

		if (!form.title.trim()) {
			alert('제목을 입력해 주세요.');
			return;
		}
		if (form.targetAmount < 1) {
			alert('목표금액은 1원 이상이어야 합니다.');
			return;
		}

		setLocalSaving(true);
		setSaving(true);

		try {
			await fetchApi('/api/studio/donation/goal/config', {
				method: 'POST',
				body: {
					channelID,
					...form,
					startAt: parseInput(form.startAt ?? '') || undefined,
					endAt: parseInput(form.endAt ?? '') || undefined,
					titleFontFamily: form.titleFontFamily || null,
					amountFontFamily: form.amountFontFamily || null
				}
			});

			alert('등록되었습니다.');
			fetchList();
			router.push('/studio/donation/goal/list');
		} catch (err) {
			alert(err instanceof Error ? err.message : '저장에 실패했습니다.');
		} finally {
			setLocalSaving(false);
			setSaving(false);
		}
	};

	// ── 취소 ─────────────────────────────────────────
	const handleCancel = () => {
		router.push('/studio/donation/goal/list');
	};

	return (
		<>
			<div className="studio-page__title-row">
				<h1 className="studio-page__title">후원 목표 추가</h1>
				<Link href="/studio/donation/goal/list" className="goal-config__btn goal-config__btn--sm">＜ 목록으로</Link>
			</div>
			<div className="pt-5 pb-5">
				<Separator orientation="horizontal" />
			</div>
			<div className="goal-config__layout">
				<GoalPreviewPanel form={form} />

				<Separator orientation="vertical" />

				<GoalFormPanel
					form={form}
					editingItem={null}
					saving={localSaving}
					onFormChange={handleFormChange}
					onSave={handleSave}
					onCancel={handleCancel}
				/>
			</div>
		</>
	);
}