import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useParams, useNavigate } from 'react-router-dom';
import { apiUrl, fetchPage, postPage } from '../apiTools.jsx';
import { useFixLinks } from '../clientStuff.jsx';

import './Pages.css';

function PageView() {
  const queryClient = useQueryClient();
  const navigate = useNavigate();
  const noLoad = useFixLinks();
  const { pagenumber } = useParams();
  
  const { isPending, error, data } = useQuery({ // fetch the currrent values
    queryKey: ['page', pagenumber],
    queryFn: () => fetchPage(pagenumber)
  })

  const ready = !(error || isPending);

  let {id, title, description, html} = data || {};

  return (
    <div className="main-column">
      <div>
        <header>
          <h1>
            <a href="/" {...noLoad}>🌳</a>{pagenumber}. {ready ? (title || " ") : "..."}</h1>
          <hr/>
        </header>
        <section>
        { ready ? 
          <div 
            className="page-contents" 
            dangerouslySetInnerHTML={{ __html: (html || " ") }}
            {...noLoad}
          />
          :
          (isPending ? "Loading..." : JSON.stringify(error))
        }
        <button onClick={(e) => { e.preventDefault(); navigate(`/${pagenumber}/edit`, {replace: true})}}>Edit this page!</button>
        </section>
      </div>
    </div>
  );
}

export default PageView;