'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 { useRankConfigContext } from '../context';
import { Separator } from '@/components/ui/separator';
import RankPreviewPanel from '../_components/RankPreviewPanel';
import RankFormPanel from '../_components/RankFormPanel';
import { createEmptyForm, parseInput } from '../types';
import type { FormState } from '../types';

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

	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;
		}

		setLocalSaving(true);
		setSaving(true);

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

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

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

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

				<Separator orientation="vertical" />

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