import DOMPurify from 'dompurify';
import {useMemo} from 'react';
import {useSearchParams} from 'react-router-dom';
import {useContentDetail} from '../admin/feature/content/hook/query/useContentDetail.ts';

export function UserContentPreviewPage() {
  const [params] = useSearchParams();
  const cntId = params.get('cntId') ?? '';
  const cntDtId = params.get('cntDtId') ?? '';
  const {data, isLoading, error} = useContentDetail(cntId, cntDtId, {enabled: !!cntId});

  const contentHtml = useMemo(
    () => DOMPurify.sanitize(data?.cntCn ?? ''),
    [data?.cntCn],
  );

  if (!cntId) {
    return <div className="content_preview_empty">미리보기 콘텐츠 정보가 없습니다.</div>;
  }

  if (isLoading) {
    return <div className="content_preview_empty">미리보기를 불러오는 중입니다.</div>;
  }

  if (error) {
    return <div className="content_preview_empty">미리보기를 불러오지 못했습니다.</div>;
  }

  return (
    <article className="content_preview">
      <header className="content_preview_header">
        <h3>{data?.cntName}</h3>
        {data?.updtPnttm || data?.registPnttm ? (
          <p>{data.updtPnttm || data.registPnttm}</p>
        ) : null}
      </header>
      <div
        className="content_preview_body"
        dangerouslySetInnerHTML={{__html: contentHtml}}
      />
    </article>
  );
}
