'use client';

import { useParams } from 'next/navigation';
import { useState, useEffect, useCallback } from 'react';
import { NoticeDetail } from '@/components/customer-center/NoticeManagement';
import { transformPostToNotice, type Notice } from '@/components/customer-center/NoticeManagement/types';
import { getPost } from '@/components/customer-center/shared/actions';
import { ServerErrorPage } from '@/components/common/ServerErrorPage';
import { GenericPageSkeleton } from '@/components/ui/skeleton';

export default function NoticeDetailPage() {
  const params = useParams();
  const id = params.id as string;

  const [notice, setNotice] = useState<Notice | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchNotice = useCallback(async () => {
    setIsLoading(true);
    setError(null);

    const result = await getPost('notices', id);

    if (result.success && result.data) {
      setNotice(transformPostToNotice(result.data));
    } else {
      setError(result.error || '공지사항을 찾을 수 없습니다.');
    }

    setIsLoading(false);
  }, [id]);

  useEffect(() => {
    fetchNotice();
  }, [fetchNotice]);

  if (isLoading) return <GenericPageSkeleton />;

  if (error || !notice) {
    return (
      <ServerErrorPage
        title="공지사항을 불러올 수 없습니다"
        message={error || '공지사항을 찾을 수 없습니다.'}
        onRetry={fetchNotice}
        showBackButton={true}
        showHomeButton={true}
      />
    );
  }

  return <NoticeDetail notice={notice} />;
}
