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


export default function PostShow() {
    const {id} = useParams();
    const [title, setTitle] = useState("");
    const [body, setBody] = useState("");
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        if (id) {
            setLoading(true);
            showPost(Number(id))
                .then(res => {
                    console.log('Full response:', res); // Debug full response
                    console.log('Response data:', res.data); // Debug data
                    
                    // Handle both response structures
                    const post = res.data || res.data;
                    
                    setTitle(post.title || "No title");
                    setBody(post.body || "No body");
                    setLoading(false);
                })
                .catch(err => {
                    console.error('Error fetching post:', err);
                    console.error('Error response:', err.response);
                    setLoading(false);
                });
        }
    }, [id]);

    return (
    <div>
        <div className="p-3">
            <h1 className="text-2xl font-bold mb-4">Show Post</h1>
            <Link
            to="/"
            className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded mb-4 inline-block">
                Back
            </Link>

            {loading ? (
                <p className="mt-4">Loading...</p>
            ) : (
                <div className="mt-4 bg-white p-4 rounded shadow">
                    <div className="mb-4">
                        <strong className="text-lg">Title:</strong>
                        <p className="mt-2">{title}</p>
                    </div>
                    <div>
                        <strong className="text-lg">Body:</strong>
                        <p className="mt-2">{body}</p>
                    </div>
                </div>
            )}
        </div>
    </div>
  )
}