import { useEffect, useState } from 'react';
import { useLocation } from 'react-router';
import { useTranslation } from 'react-i18next';
import { PATHS } from '@/shared/constants/paths';
import { useNoticeDetailMutation } from '@/entities/support/api/use-notice-detail-mutation';
import { useNavigate } from '@/shared/lib/hooks/use-navigate';
import { HeaderType } from '@/entities/common/model/types';
import { NoticeDetailParams, NoticeDetailResponse, NoticeItem } from '@/entities/support/model/types';
import {
  useSetHeaderTitle,
  useSetHeaderType,
  useSetFooterMode,
  useSetOnBack
} from '@/widgets/sub-layout/use-sub-layout';
import moment from 'moment';

export const NoticeDetailPage = () => {
  const { navigate } = useNavigate();
  const location = useLocation();
  const { t } = useTranslation();

  const [result, setResult] = useState<NoticeItem>({});
  
  let from = location?.state.from;

  useSetHeaderTitle(t('support.notice.title'));
  useSetHeaderType(HeaderType.RightClose);
  useSetFooterMode(false);
  useSetOnBack(() => {
    if(from){
      navigate(from);
    }
    else{
      navigate(PATHS.support.notice.list);
    }
  });

  const { mutateAsync: noticeDetail } = useNoticeDetailMutation();

  const callDetail = () => {
    let detailParams: NoticeDetailParams = {
      seq: location?.state.seq,
    };
    noticeDetail(detailParams).then((rs: NoticeDetailResponse) => {
      setResult(rs);
    });
  };

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

  return (
    <>
      <main>
        { result.informCl &&
          <div className="tab-content">
            <div className="tab-pane sub active">
              <div className="option-list">
                <div className="notice-detail">
                  <div className="notice-detail__title">{ result.title }</div>
                  <div className="notice-detail__meta">{ moment(result.regDt).format('YYYY.MM.DD') } | { t(`support.notice.categories.${result.informCl}`) }</div>
                  <div className="notice-detail__divider"></div>
                  <div className="notice-detail__body" dangerouslySetInnerHTML={{ __html: result.contents || '' }}></div>
                </div>
              </div>
            </div>
          </div>
        }
      </main>
    </>
  );
};