'use client';

import { useState, useEffect } from 'react';
import {
	DialogContent,
	DialogDescription,
	DialogFooter,
	DialogHeader,
	DialogTitle,
	DialogClose
} from '@/components/ui/dialog';
import { fetchApi } from '@/lib/utils/client';
import type { DocumentResponse } from '@/types/response/page/document';

export default function TermsDialog({ subject, code }: { subject: string; code: string }) {
	const [content, setContent] = useState<string | null>(null);
	const [loading, setLoading] = useState(true);

	useEffect(() => {
		fetchApi<DocumentResponse>(`/api/document/${code}`)
			.then((res) => {
				if (res.success && res.data) {
					setContent(res.data.content);
				}
			})
			.finally(() => setLoading(false));
	}, [code]);

	return (
		<DialogContent className='sm:max-w-[600px] max-h-[80vh]'>
			<DialogHeader>
				<DialogTitle>{subject}</DialogTitle>
				<DialogDescription asChild>
					<div className='mt-2 max-h-[60vh] overflow-y-auto text-sm'>
						{loading ? (
							<p className='text-center py-4'>준비 중...</p>
						) : content ? (
							<section dangerouslySetInnerHTML={{ __html: content }} />
						) : (
							<p className='text-center py-4'>내용이 없습니다.</p>
						)}
					</div>
				</DialogDescription>
			</DialogHeader>
			<DialogFooter className='sm:justify-center'>
				<DialogClose asChild>
					<button type='button' className='btn btn-default w-1/2'>확인</button>
				</DialogClose>
			</DialogFooter>
		</DialogContent>
	);
}