import { useQuery } from '@tanstack/react-query';
import { useParams, useNavigate } from 'react-router-dom';
import { fetchPageHistory } from '../apiTools.jsx';
import { useFixLinks } from '../clientStuff.jsx';

import './Pages.css';

function HistoryView() {
  const noLoad = useFixLinks();
  const { pagenumber, editid } = useParams();
  const navigate = useNavigate();
  
  const { isPending, error, data } = useQuery({ // fetch the currrent values
    queryKey: ['page history', pagenumber],
    queryFn: () => fetchPageHistory(pagenumber)
  })
  const edits = data;

  const ready = !(error || isPending);

  const pageTitle = edits ? edits[0]?.title : "[no title]";

  return (
    <div className="main-column">
      <div>
        <header>
          <h1><a href="/" {...noLoad}>🌳</a>{pagenumber}. {ready ? pageTitle : "..."}</h1>
          <hr/>
        </header>
        <section className="page-contents">
        { ready ? 
          <ol>
            { edits.map(({id, number, title, time, author}) => 
              <li key={id}>
                <a href={`/${number}/${id}`} {...noLoad}>{id} : "{title}", {time} by user #{author}</a>
              </li>
              ) }
          </ol>
          :
          (isPending ? "Loading..." : JSON.stringify(error))
        }
        </section>
        <button onClick={() => navigate(`/${pagenumber}`)}>Return to page</button>
      </div>
    </div>
  );
}

export default HistoryView;