import React, { useState } from 'react';

import { v4 as uuid } from 'uuid';
import { Link, useNavigate } from 'react-router-dom';
  
export default function Create() {
  
    // Making usestate for setting and
    // fetching a value in jsx
    const [name, setName] = useState('');
  
    // Using useNavigation for redirecting to pages
    let history = useNavigate();
  
    async function createItem(e){
	e.preventDefault();
	//console.log("Home:createItem() name: " + name);
	const url='https://v1rgncy.api.swingbe.de/entities/create';
	//console.log('Home:createItem() url: ' + url);
	let data = new FormData();
	data.append('name',name);
	return fetch(url, {
	    method: "POST",
	    mode: "cors",
	    body: data
	})
	    .then(response => {
		if (!response.ok) {
		    console.error('Home:createItem() rsp error: ' + response);
		}else{
		    //console.log('Home:createItem() rsp fine');
		    // We need to re-render the page for getting
		    // the results so redirect to same page.
		    history('/')
		    //console.log('Home:createItem() Done.');
		}
	    })
	    .catch((error) => {
		console.error('Home:createItem() error: ' + error);
		// We need to re-render the page for getting
		// the results so redirect to same page.
		//console.log('Home:createItem() Done.');
	    });
    };

    return (
	<div>
	    <h1>Create</h1>
	    <form
		onSubmit={e => createItem(e)}
	    >
		<label>
		    Enter name (input:{name}):
		    <input
			onChange={e => setName(name => e.target.value)}
			type="text"
			value={name}
			placeholder="Enter Name"
			required
		    />
		</label>
		<button
		    onClick={e => createItem(e)}
		    type="submit"
		>
		    Create
		</button>
		<Link
		    to='/'
		>
		    <button>
			Home
		    </button>
		</Link>
	    </form>
	</div>
    );
};
