import { useEffect, useState } from "react";
import { Link, useNavigate, useParams } from "react-router-dom";
import { getPost, updatePost } from "../services/postService";


export default function PostEdit() {
    const {id} = useParams();
    const [title, setTitle] = useState("");
    const [body, setBody] = useState("");
    const navigate = useNavigate()

    useEffect(() => {
        if (id) {
            getPost(Number(id)).then(res => {
                setTitle(res.data.title);
                setBody(res.data.body);
            }
            );
        }
    }, [id]);

    const submit = (e: React.FormEvent) => {
        e.preventDefault();
        updatePost(Number(id), {title: title, body: body}).then(() => 
            navigate("/"));
    }

    return (
    <div>
        <div className="p-3">
            <h1 className="text-2xl font-bold mb-4">Edit List</h1>
            <Link
            to="/"
            className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">
                Back
            </Link>
            <form onSubmit={submit} className="mt-4">
                <div className="mb-4">
                    <label className="block text-gray-700 text-sm font-bold mb-2">
                        Title
                    </label>
                    <input
                    id="title"
                    name="title"
                    value={title}
                    onChange={e => setTitle(e.target.value)}
                    className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
                    placeholder="Enter your title"
                    />
                    
                </div>

                <div className="mb-4">
                    <label className="block text-gray-700 text-sm font-bold mb-2">
                        body
                    </label>
                    <textarea
                    id="body"
                    name="body"
                    value={body}
                    onChange={e => setBody(e.target.value)}
                    className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
                    placeholder="Enter your body"
                    />
                    
                </div>
                <button
                type="submit"
                className="bg-green-500 hover:bg-green-700 text-white font-bold py-2 px-4 rounded">
                    Submit
                </button>
            </form>
        </div>
    </div>
  )
}