import { useEffect, useMemo, useState } from 'react';
import { useQuery } from 'react-query';
import { PageContentProps } from '~/types/pageContent';
import { getPageContent } from '~/services/pageContent';

type Props = {
  path: string;
};

const PageContent = ({ path }: Props) => {
  const [localData, setData] = useState<PageContentProps>();
  const [shouldFetch, setShouldFetch] = useState(false);

  useEffect(() => {
    const localData = localStorage.getItem(`page-content:${path}`);
    if (localData) {
      setData(JSON.parse(localData));
    }else{
      setShouldFetch(true);
    }
  },[])
  
  const { data, isLoading } = useQuery<PageContentProps>(
    `page-content:${path}`,
    async () => await getPageContent({ path }), {
      enabled: shouldFetch,
      onSuccess: (data) => {
        if (data) {
          localStorage.setItem(`page-content:${path}`, JSON.stringify(data));
          setData(data);
        }
      },
    }
  );

  const parsedContent = useMemo<string>(() => {
    if (!localData) return '';
    return localData.content.replaceAll(
      'src="/web/image',
      `src="${process.env.NEXT_PUBLIC_ODOO_API_HOST}/web/image`
    );
  }, [localData]);
  if (isLoading) return <PageContentSkeleton />;

  return <div dangerouslySetInnerHTML={{ __html: parsedContent || '' }}></div>;
};

const PageContentSkeleton = () => (
  <div className='animate-pulse grid gap-y-4'>
    <div className='w-full h-10 bg-gray-300 rounded' />
    <div className='h-2' />
    <div className='w-full h-4 bg-gray-300 rounded' />
    <div className='w-full h-4 bg-gray-300 rounded' />
    <div className='w-full h-4 bg-gray-300 rounded' />
    <div className='w-8/12 h-4 bg-gray-300 rounded' />
    <div className='h-2' />
    <div className='w-full h-4 bg-gray-300 rounded' />
    <div className='w-full h-4 bg-gray-300 rounded' />
    <div className='w-full h-4 bg-gray-300 rounded' />
    <div className='w-1/2 h-4 bg-gray-300 rounded' />
  </div>
);

export default PageContent;
