import { useState } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';

import { fetchPageList, postNewPage, postLogOut } from '../apiTools.jsx';
import { useFixLinks } from '../clientStuff.jsx';

import { useLoggedIn } from '../AuthProvider.jsx';

import PageList from './PageList.jsx';
import GraphRender from './GraphRender.jsx';

import './Landing.css'

function Landing() {
  const queryClient = useQueryClient();
  const navigate = useNavigate();

  const makeNewPage = useMutation({ // for changing the value when we're done with it
    mutationFn: () => postNewPage(),
    onSettled: async (data, error, variables) => {
      // Invalidate and navigate to the new page
      console.log(data, error, variables);
      await queryClient.invalidateQueries({ queryKey: ['pages'] });
      navigate(`/${data}/edit`);
    },
  });

  const loggedIn = useLoggedIn();

  return (
    <div className="landing-column">
      <header>
        <h1>Welcome to the forest.</h1>
        <hr/>
      </header>
      <div className="landing-container">
        <section className="landing-section">
          <GraphRender />
        </section>
        <section className="landing-section">
          <PageList />
        </section>
        <section className="landing-section">
          { loggedIn
            ? 
            <>
              <button onClick={makeNewPage.mutate}>Dig new room!</button><br/>
              <button onClick={postLogOut}>Log Out</button><br/>
              <button onClick={() => navigate('/profile')}>Profile</button><br/>
              <button onClick={() => navigate('/live')}>Embody!</button><br/>
            </>
            :
            <>
              <button onClick={() => navigate('/register')}>Sign up</button><br/>
              <button onClick={() => navigate('/login')}>Log in</button><br/>
              <button onClick={() => navigate('/profile')}>Profile (but you're logged out, so it shouldn't work!)</button><br/>
            </>
          }
        </section>
      </div>
    </div>
  );
}

export default Landing;