import { useState, useEffect } from 'react'
import reactLogo from './assets/react.svg'
import viteLogo from '/vite.svg'
import './App.css'
import {createBrowserHistory} from 'history';
import {Router} from 'react-router-dom'
import {NamedRoute, NamedLink, HashRoute, createPrivateRoute} from './lib';

const history = createBrowserHistory()

const SwapiPeople = ({data:{name, eye_color}}) =>
<div>
    <h3 style={{color: eye_color}}>{name}</h3>
    <HashRoute path="/foo"  component={() => <h1>FOO</h1>} />
    <HashRoute path="/bar"  component={() => <h1>BAR</h1>} />
    <a href="#/foo">go to foo</a>
    <a href="#/bar">go to bar</a>
</div>

const SwapiPlanet = ({data:{name, diameter}}) =>
<div>
    <h3>{name}</h3>
    <h4>{diameter}</h4>
</div>

const queries = {
    people({id}){
        return fetch('https://swapi.dev/api/people/' + id).then(res => res.json())
    },
    planet({id}){
        if (id == 2) 
            return {
                "name": "Alderaan",
                "diameter": "12500"
            }
        return fetch('https://swapi.dev/api/planets/' + id).then(res => res.json())
    }
}

const Pending = () => <h1>Loading</h1>
const Error   = ({error}) => <h1>Error: {error.message}</h1>

const UserNamedRoute = createPrivateRoute(() => ['user'], history => history.goBack())(NamedRoute)

const Dashboard = () => <h1>dashboard</h1>


function App() {
  return (
    <Router history={history}>
      <div>
        <NamedRoute name="people" 
                    query={queries.people}
                    path="/people/:id" 
                    pendingQueryComponent={Pending}
                    errorQueryComponent={Error}
                    component={SwapiPeople}/>
        <NamedRoute routeName="planet" 
                    query={queries.planet}
                    pendingQueryComponent={Pending}
                    errorQueryComponent={Error}
                    path="/planet/:id" 
                    component={SwapiPlanet}/>
        <UserNamedRoute routeName="dashboard" path="/dashboard" component={Dashboard} roles={['admin']} />
      </div>
      <p className="read-the-docs">
        <NamedLink routeName="people" params={{id: 1}}>Luke</NamedLink>
        <NamedLink routeName="people" params={{id: 2}}>C3PO</NamedLink>
      </p>
      <p className="read-the-docs">
        <NamedLink routeName="planet" params={{id: 1}}>Tatooin</NamedLink>
        <NamedLink routeName="planet" params={{id: 2}}>Alderaan</NamedLink>
      </p>
    </Router>
  )
}

export default App
