import { useTranslation } from 'react-i18next';
import { motion } from 'framer-motion';
import { useLocation } from 'react-router';
import { NoticeDetailParams, NoticeDetailResponse, NoticeItem } from '../../model/types';
import { useCallback, useEffect, useRef, useState, useMemo } from 'react';
import { useNoticeDetailMutation } from '../../api/use-notice-detail-mutation';
import moment from 'moment';
import { DetailMotionDuration, DetailMotionStyle, DetailMotionVariants } from '@/entities/common/model/constant';
import { FullMenuClose } from '@/entities/common/ui/full-menu-close';
import { showAlert } from '@/widgets/show-alert';
import { snackBar, sanitizeHtmlContent } from '@/shared/lib';

export interface NoticeDetaillProps {
  detailOn: boolean;
  setDetailOn: (detailOn: boolean) => void;
  seq?: number | string;
};
export const NoticeDetail = ({
  detailOn,
  setDetailOn,
  seq
}: NoticeDetaillProps) => {
  const { t } = useTranslation();
  const [result, setResult] = useState<NoticeItem>({});
  const { mutateAsync: noticeDetail } = useNoticeDetailMutation();
  const modalRef = useRef<HTMLDivElement>(null);

  // HTML 콘텐츠 정제 (메모이제이션)
  const sanitizedContent = useMemo(() => {
    return sanitizeHtmlContent(result.contents || '', {
      imageClass: 'notice-content-img',
      linkClass: 'notice-content-link'
    });
  }, [result.contents]);

  const onClickToClose = useCallback(() => {
    setDetailOn(false);
  }, [setDetailOn]);

  const callDetail = useCallback(() => {
    if(seq){
      let detailParams: NoticeDetailParams = {
        seq: seq,
      };
      noticeDetail(detailParams).then((rs: NoticeDetailResponse) => {
        if(rs.seq){
          setResult(rs);
          // Scroll reset after data load
          setTimeout(() => {
            if (modalRef.current) {
              modalRef.current.scrollTop = 0;
            }
            window.scrollTo(0, 0);
            document.body.scrollTop = 0;
            document.documentElement.scrollTop = 0;

            const containerElement = document.querySelector('.full-menu-container');
            if (containerElement) {
              containerElement.scrollTop = 0;
            }

            const optionList = document.querySelector('.option-list');
            if (optionList) {
              optionList.scrollTop = 0;
            }
          }, 100);
        }
        else{
          snackBar(t('common.noData'));
          onClickToClose();
        }
      }).catch((e: any) => {
        if(e.response?.data?.error?.message){
          snackBar(e.response?.data?.error?.message);
          return;
        }
      });
    }
  }, [seq, noticeDetail, t, onClickToClose]);

  useEffect(() => {
    if (detailOn && seq) {
      callDetail();
    }
  }, [seq, detailOn, callDetail]);

  return (
    <>
      <motion.div
        ref={modalRef}
        className="full-menu-modal"
        initial="hidden"
        animate={ (detailOn)? 'visible': 'hidden' }
        variants={ DetailMotionVariants }
        transition={ DetailMotionDuration }
        style={ DetailMotionStyle }
      >
        { result.informCl &&
          <div className="full-menu-container pdw-16">
            <div className="full-menu-header">
              <div className="full-menu-title center">{ t('support.notice.title') }</div>
              <div className="full-menu-actions">
                <FullMenuClose
                  addClass="full-menu-close"
                  onClickToCallback={ onClickToClose }
                ></FullMenuClose>
              </div>
            </div>
            <div className="option-list">
              <div className="notice-detail">
                <div className="notice-detail__title">{ result.title }</div>
                <div className="notice-detail__meta">{ result.regDt? 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: sanitizedContent }}
                ></div>
              </div>
            </div>
          </div>
        }
      </motion.div>
    </>
  );
};